Results 1 to 11 of 11
  1. #1
    Kligham is offline Member
    Join Date
    Sep 2009
    Posts
    30
    Rep Power
    0

    Default 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:

    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 the main file:

    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();
                }
            });
        }
    }
    And here the real question: How do I get acces to the frame from the main class in:

    Java Code:
    Container contentPane = [B]frame[/B].getContentPane();
                    contentPane.removeAll();
                    contentPane.add(new YourPanel());
                    contentPane.invalidate();
                    contentPane.repaint();
    I hope anyone can help me out with this.

    Grtz

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  3. #3
    Kligham is offline Member
    Join Date
    Sep 2009
    Posts
    30
    Rep Power
    0

    Default

    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;}
     
    }
    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;
     
        }
    }
    The problem is marked in bold. I tried this, but this isn't right at all:

    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");
    }
    }
    );
    Here is the error report, if you could use it:

    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)
    I hope someone can help me out with this one.
    Last edited by Kligham; 01-06-2010 at 09:54 PM.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    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;
      }
    
    }

  5. #5
    Kligham is offline Member
    Join Date
    Sep 2009
    Posts
    30
    Rep Power
    0

    Default

    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.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Kligham View Post
    Hi, first of all thanks for that response and your time, it helps me a lot further.
    You're quite welcome.

    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).
    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.

    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?
    Many programs do just this: set up their screens in advance on start up.

    So can the needed JPanel be created on the fly and added to the cardlayout and be shown?
    Yes, of course.

    How would you do that? Can you give me a tip or hint in what direction I should search for.
    my tip is try it and see. :)

  7. #7
    Kligham is offline Member
    Join Date
    Sep 2009
    Posts
    30
    Rep Power
    0

    Default

    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)

    Java Code:
    public void setMainPanel(MainPanel panel) {
        this.mainPanel = panel;
      }
    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?

    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 :

    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;
      }
    
    }
    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?

    Grtz
    Last edited by Kligham; 01-07-2010 at 02:17 AM.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    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.

  9. #9
    Kligham is offline Member
    Join Date
    Sep 2009
    Posts
    30
    Rep Power
    0

    Default

    Hi,

    I got it to working with this code in the MainPanel class:

    Java Code:
      public void addCard(JPanel panel, String key) {
          mainPanel.add(panel, key);
      }
    However I still don't get the some things, so can anyone explain these 2 questions:

    1)

    Java Code:
    public void setMainPanel(MainPanel panel) {
        this.mainPanel = panel;
      }
    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?

    2)I saw you made a get and set MainPanel, but I don't see where it used (called)?

    grtz

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Kligham View Post
    Hi,
    I got it to working with this code in the MainPanel class:
    Java Code:
      public void addCard(JPanel panel, String key) {
          mainPanel.add(panel, key);
      }
    Good deal! :)

    Java Code:
    public void setMainPanel(MainPanel panel) {
        this.mainPanel = panel;
      }
    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?
    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.

    2)I saw you made a get and set MainPanel, but I don't see where it used (called)?
    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:
    Java Code:
        nieuweClientItem.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            // tell the GUI to swap panels
            mainPanel.swapCards(MainPanel.NEXT_PANEL);
          }
        });

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. Passing data from one JFrame to another JFrame
    By tarami in forum New To Java
    Replies: 3
    Last Post: 08-06-2009, 05:44 PM
  2. Replies: 4
    Last Post: 04-22-2009, 11:02 PM
  3. How to obtain the name of the JMenuItem?
    By Azuxard in forum AWT / Swing
    Replies: 1
    Last Post: 03-23-2009, 03:33 AM
  4. Help in JFrame
    By kirtesh4u in forum New To Java
    Replies: 2
    Last Post: 11-18-2008, 12:40 AM
  5. More than one KeyStroke (Shortcut) for a JMenuItem
    By hannehomuth in forum Advanced Java
    Replies: 0
    Last Post: 07-25-2008, 03:35 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •