Results 1 to 11 of 11
Thread: JFrame and JMenuItem
- 01-06-2010, 06:54 PM #1
Member
- Join Date
- Sep 2009
- Posts
- 30
- Rep Power
- 0
JFrame and JMenuItem
Hi,
What I want to do is when a JMenuItem is clicked, the previous JPanel needs to be destroyed and the one you asked needs to be created and added to the JFrame.
I have the following:
And the main file:Java Code:package test; import java.awt.event.InputEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Container; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.KeyStroke; public class MenuGUI { private JMenuBar menuBar; /** Constructs the menu bar. */ public MenuGUI(){ menuBar = new JMenuBar(); JMenu consultatie = new JMenu("Consultatie"); menuBar.add(consultatie); JMenuItem nieuweClientItem= new JMenuItem("Nieuwe Cliënt"); nieuweClientItem.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK)); consultatie.add(nieuweClientItem); JMenu boekhouding = new JMenu("Boekhouding"); menuBar.add(boekhouding); nieuweClientItem.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent e) { Container contentPane = frame.getContentPane(); contentPane.removeAll(); contentPane.add(new YourPanel()); contentPane.invalidate(); contentPane.repaint(); } } ); } /** Returns the menu bar corresponding to this menu. */ public JMenuBar getMenuBar() {return menuBar;} }
And here the real question: How do I get acces to the frame from the main class in:Java Code:package test; import javax.swing.*; public class Main { private static void createAndShowGUI(){ JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // construct a Menu object... MenuGUI menu = new MenuGUI(); // ...and obtain its menu bar frame.setJMenuBar(menu.getMenuBar()); JPanel voorPagina = new JPanel(); JLabel welkom = new JLabel("Welkom, u kunt dit programma naar hartelust gebruiken"); voorPagina.add(welkom); frame.add(voorPagina); frame.pack(); frame.setSize(500,500); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
I hope anyone can help me out with this.Java Code:Container contentPane = [B]frame[/B].getContentPane(); contentPane.removeAll(); contentPane.add(new YourPanel()); contentPane.invalidate(); contentPane.repaint();
Grtz
-
Google for the tutorial on using a CardLayout as this is what you want to use here.
- 01-06-2010, 09:51 PM #3
Member
- Join Date
- Sep 2009
- Posts
- 30
- Rep Power
- 0
Oke, I looked at google and gave it a go but I don't really know how to implement the stuff in the actionlistener from the JMenuItem:
Java Code:package test; import javax.swing.*; import java.awt.event.*; import java.awt.CardLayout; import java.awt.Container; public class Main implements ItemListener{ JPanel contentPane; private JPanel voorPagina; private JLabel welkom; final private String VOORPAGINAPANEL = "Card with voorpagina"; public void addComponentToPane(Container pane){ voorPagina = new JPanel(); welkom = new JLabel("Welkom, u **** dit programma naar hartelust gebruiken"); voorPagina.add(welkom); //Create the panel that contains the "cards". contentPane = new JPanel(new CardLayout()); contentPane.add(voorPagina, VOORPAGINAPANEL); pane.add(contentPane); } public void itemStateChanged(ItemEvent evt) { CardLayout cl = (CardLayout)(contentPane.getLayout()); cl.show(contentPane, (String)evt.getItem()); } public JPanel getPanel(){ return contentPane; } private static void createAndShowGUI(){ JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // construct a Menu object... MenuGUI menu = new MenuGUI(); // ...and obtain its menu bar frame.setJMenuBar(menu.getMenuBar()); //Create and set up the content pane. Main componentToPane = new Main(); componentToPane.addComponentToPane(frame.getContentPane()); frame.pack(); frame.setSize(500,500); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }Java Code:package test; import java.awt.event.InputEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.KeyStroke; public class MenuGUI { private JMenuBar menuBar; /** Constructs the menu bar. */ public void MenuGUI() { menuBar = new JMenuBar(); JMenu consultatie = new JMenu("Consultatie"); menuBar.add(consultatie); JMenuItem nieuweClientItem= new JMenuItem("Nieuwe Cliënt"); nieuweClientItem.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK)); consultatie.add(nieuweClientItem); JMenu boekhouding = new JMenu("Boekhouding"); menuBar.add(boekhouding); [B]nieuweClientItem.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent e) { } } );[/B] } /** Returns the menu bar corresponding to this menu. */ public JMenuBar getMenuBar() {return menuBar;} }The problem is marked in bold. I tried this, but this isn't right at all:Java Code:package test; import java.awt.FlowLayout; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JTextField; public class NieuweClientGUI { private JPanel panel; private JLabel clientIdLabel; Blablablablabla .... public NieuweClientGUI (){ panel = new JPanel(new FlowLayout()); clientIdLabel = new JLabel("Cliënt ID:"); patientIdLabel = new JLabel("Patiënt ID:"); blablablablabla .... } public JPanel getPanel(){ return panel; } }
Here is the error report, if you could use it:Java Code:nieuweClientItem.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent e) { NieuweClientGUI nc = new NieuweClientGUI(); Main m = new Main(); m.getPanel().add(nc.getPanel(), "Card with Nieuwe Client"); } } );
I hope someone can help me out with this one.Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code
at vetflow.MenuGUI$1.actionPerformed(MenuGUI.java:39)
at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:242)
at javax.swing.AbstractButton.doClick(AbstractButton. java:357)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Bas icMenuItemUI.java:1225)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mou seReleased(BasicMenuItemUI.java:1266)
at java.awt.Component.processMouseEvent(Component.jav a:6263)
at javax.swing.JComponent.processMouseEvent(JComponen t.java:3267)
at java.awt.Component.processEvent(Component.java:602 8)
at java.awt.Container.processEvent(Container.java:204 1)
at java.awt.Component.dispatchEventImpl(Component.jav a:4630)
at java.awt.Container.dispatchEventImpl(Container.jav a:2099)
at java.awt.Component.dispatchEvent(Component.java:44 60)
at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4168)
at java.awt.Container.dispatchEventImpl(Container.jav a:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475 )
at java.awt.Component.dispatchEvent(Component.java:44 60)
at java.awt.EventQueue.dispatchEvent(EventQueue.java: 599)
at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:122)Last edited by Kligham; 01-06-2010 at 09:54 PM.
-
Your first post was hampered by not having a true OOPs GUI class, and that is what is required for your to do OOP programming -- in other words to have your menu object interact with the GUI object. I would do something along these lines.
Java Code:import javax.swing.*; public class Main { private static void createAndShowGUI() { MainPanel panel = new MainPanel(); MenuGUI menu = new MenuGUI(); menu.setMainPanel(panel); JFrame frame = new JFrame("What the heck"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(menu.getMenuBar()); frame.getContentPane().add(panel.getMainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }Java Code:import java.awt.CardLayout; import java.awt.Dimension; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; class MainPanel { public static final String WELCOME = "Welcome"; public static final String NEXT_PANEL = "Next Panel"; private static final Dimension MAIN_SIZE = new Dimension(500, 500); private CardLayout cardlayout = new CardLayout(); private JPanel mainPanel = new JPanel(cardlayout); public MainPanel() { JPanel nextPanel = new JPanel(); nextPanel.add(new JButton("This Button Does Nothing")); mainPanel.setPreferredSize(MAIN_SIZE); mainPanel.add(new JLabel("Welkom, u kunt dit programma naar hartelust gebruiken", SwingConstants.CENTER), WELCOME); mainPanel.add(nextPanel, NEXT_PANEL); } public void swapCards(String key) { cardlayout.show(mainPanel, key); } public JPanel getMainPanel() { return mainPanel; } }Java Code:import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.KeyStroke; class MenuGUI { private JMenuBar menuBar; private MainPanel mainPanel; public MenuGUI() { menuBar = new JMenuBar(); JMenu consultatie = new JMenu("Consultatie"); menuBar.add(consultatie); JMenuItem nieuweClientItem = new JMenuItem("Nieuwe Cliënt"); nieuweClientItem.setAccelerator( KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK)); consultatie.add(nieuweClientItem); JMenu boekhouding = new JMenu("Boekhouding"); menuBar.add(boekhouding); nieuweClientItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // tell the GUI to swap panels mainPanel.swapCards(MainPanel.NEXT_PANEL); } }); } // pass the GUI to the menu so it can act on it public void setMainPanel(MainPanel panel) { this.mainPanel = panel; } public JMenuBar getMenuBar() { return menuBar; } }
- 01-07-2010, 12:11 AM #5
Member
- Join Date
- Sep 2009
- Posts
- 30
- Rep Power
- 0
Hi, first of all thanks for that response and your time, it helps me a lot further. Now, I do have a question. I don't know if I'm right but it seems that right now all the JPanels are created at startup from the program? So lets say if I have 30 JMenuItems all with their own JPanel. They are all created at startup, so is there a way to create the JPanel only when asked (so when there was clicked on the needed JMenuItem). I ask this because there are a lot (more than the half) of the JPanels that won't be used regularly, so it seems a bit unuseful to let them be created even though they won't be used?
So can the needed JPanel be created on the fly and added to the cardlayout and be shown?
How would you do that? Can you give me a tip or hint in what direction I should search for.
-
You're quite welcome.
No, all JPanels do not need to be created at start up but can be created at any time and added to the CardLayout-using container.Now, I do have a question. I don't know if I'm right but it seems that right now all the JPanels are created at startup from the program?
So lets say if I have 30 JMenuItems all with their own JPanel. They are all created at startup, so is there a way to create the JPanel only when asked (so when there was clicked on the needed JMenuItem).
Many programs do just this: set up their screens in advance on start up.I ask this because there are a lot (more than the half) of the JPanels that won't be used regularly, so it seems a bit unuseful to let them be created even though they won't be used?
Yes, of course.So can the needed JPanel be created on the fly and added to the cardlayout and be shown?
my tip is try it and see. :)How would you do that? Can you give me a tip or hint in what direction I should search for.
- 01-07-2010, 02:15 AM #7
Member
- Join Date
- Sep 2009
- Posts
- 30
- Rep Power
- 0
Well I'm back. I tried to make it create a JPanel on the fly, but this doesn't seem to be so easy as I "hoped" it would be. I also have some questions about the script, so I'll start with these:
1)
The parameter MainPanel panel => what does is send, I know it sends all of the strings, the methods, the getter also, but the .add() function doesn't work. How come?Java Code:public void setMainPanel(MainPanel panel) { this.mainPanel = panel; }
2)I saw you made a get and set MainPanel, but I don't see where it used (called)?
Here is what I tried. The questions above are related to the problems I get:
1) the .add function that doesn't work for the mainPanel as described earlier.
2) For some reason the string TEST isn't recognized. Netbeans says: Cannot find symbol => Variable TEST.
I only changed MenuGUI.java :
Beside this problem, I would like your opinion: Do I really have to worry about performance issues, and instead load all the JPanels at startup?Java Code:import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.KeyStroke; import javax.swing.JPanel; import javax.swing.JLabel; class MenuGUI { private JMenuBar menuBar; private MainPanel mainPanel; public final String TEST = "This is a test!!!"; public MenuGUI() { menuBar = new JMenuBar(); JMenu consultatie = new JMenu("Consultatie"); menuBar.add(consultatie); JMenuItem nieuweClientItem = new JMenuItem("Nieuwe Cliënt"); nieuweClientItem.setAccelerator( KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK)); consultatie.add(nieuweClientItem); JMenu boekhouding = new JMenu("Boekhouding"); menuBar.add(boekhouding); JMenuItem afrekening = new JMenuItem("Afrekening"); nieuweClientItem.setAccelerator( KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK)); boekhouding.add(afrekening); nieuweClientItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // tell the GUI to swap panels mainPanel.swapCards(MainPanel.NEXT_PANEL); } }); afrekening.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JPanel test = new JPanel(); JLabel testLabel = new JLabel(); test.add(testLabel); mainPanel. mainPanel.add(test); mainPanel.swapCards(MainPanel.TEST); } }); } // pass the GUI to the menu so it can act on it public void setMainPanel(MainPanel panel) { this.mainPanel = panel; } public JMenuBar getMenuBar() { return menuBar; } }
GrtzLast edited by Kligham; 01-07-2010 at 02:17 AM.
-
In my program, since my CardLayout-using main JPanel is somewhat hidden from view, the best way to set it up to accept "card" panels is to give the MainPanel class a public method that allows it to add JPanels and their related Strings.
- 01-07-2010, 08:17 PM #9
Member
- Join Date
- Sep 2009
- Posts
- 30
- Rep Power
- 0
Hi,
I got it to working with this code in the MainPanel class:
However I still don't get the some things, so can anyone explain these 2 questions:Java Code:public void addCard(JPanel panel, String key) { mainPanel.add(panel, key); }
1)
The parameter MainPanel panel => what does is send, I know it sends all of the strings, the methods, the getter also, but the .add() function doesn't work. How come?Java Code:public void setMainPanel(MainPanel panel) { this.mainPanel = panel; }
2)I saw you made a get and set MainPanel, but I don't see where it used (called)?
grtz
-
Good deal! :)
Sorry, I should have added more comments to my code. As a general rule, I try to avoid extending other classes unless I have to, and this includes Swing classes such as JPanel and JFrame. If I'm not changing any of the basic behaviors of say a JPanel, then I feel that my code is safer if I tuck the JPanel away into a private field of the class, and only expose the parts of it that I want in my class. This prevents me from writing code that causes unexpected side effects such as those that happened when a class did extend JPanel and also had unknowningly overridden JPanel's getX() and getY() methods. I could never this panel because it's location was way off of the JFrame. Also, it makes it easier to use my class with my IDE as it's intellisense editor will have only a few methods to suggest to me, and they're all methods that I've written. So with that in mind, my MainPanel class encapsulates the idea of a main JPanel without actually extending JPanel. Instead it holds a JPanel object in its mainPanel variable and will return this JPanel on demand (on calling the getPanel() method). Otherwise all interaction with this mainPanel will be only through methods that I write.The parameter MainPanel panel => what does is send, I know it sends all of the strings, the methods, the getter also, but the .add() function doesn't work. How come?Java Code:public void setMainPanel(MainPanel panel) { this.mainPanel = panel; }
My Control class (MenuGUI) has a getMainPanel method to set it's mainPanel variable, and then it uses the variable within one of the menu item's ActionListener actionPerformed methods:2)I saw you made a get and set MainPanel, but I don't see where it used (called)?
Java Code:nieuweClientItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // tell the GUI to swap panels mainPanel.swapCards(MainPanel.NEXT_PANEL); } });
-
Similar Threads
-
Passing data from one JFrame to another JFrame
By tarami in forum New To JavaReplies: 3Last Post: 08-06-2009, 05:44 PM -
How to make a Jframe un-focusable when another Jframe is active?
By Robert_85 in forum Advanced JavaReplies: 4Last Post: 04-22-2009, 11:02 PM -
How to obtain the name of the JMenuItem?
By Azuxard in forum AWT / SwingReplies: 1Last Post: 03-23-2009, 03:33 AM -
Help in JFrame
By kirtesh4u in forum New To JavaReplies: 2Last Post: 11-18-2008, 12:40 AM -
More than one KeyStroke (Shortcut) for a JMenuItem
By hannehomuth in forum Advanced JavaReplies: 0Last Post: 07-25-2008, 03:35 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks