Results 1 to 8 of 8
  1. #1
    Psyclone is offline Member
    Join Date
    Jan 2010
    Posts
    81
    Rep Power
    0

    Default How do I close a frame with a button?

    I built a GUI that creates a frame with a bunch of buttons, lists, etc. I have all of the components (buttons, lists, comboboxes, etc) working correctly with action listeners. I'm actually only having an issue with the Exit button. I want to have an Exit button that has the same effect as closing the program by hitting the X button on the frame in the top right corner.

    I've been able to get sub-frames to close with action listeners, but since the main frame is static... how do I close the frame from another action listener?

    I also would like to make the main frame disabled when another window opens, but this brings me back to the same problem.

    Java Code:
    public class DungeonEditor extends JPanel  {
    
        // declarations
    
        public DungeonEditor () throws IOException, BiffException, WriteException {
            super(new BorderLayout());
     
        // constructor
    
        public static void buildGUI() throws IOException, BiffException, WriteException {
            JFrame frame = new JFrame("Dungeon Editor");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setPreferredSize(new Dimension(1120, 700));
    
            JComponent newContentPane = new DungeonEditor();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
    
            frame.pack();
            frame.setVisible(true);
        }
     
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        buildGUI();
                    } catch (IOException ex) {
                        Logger.getLogger(DungeonEditor.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (BiffException ex) {
                        Logger.getLogger(DungeonEditor.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (WriteException ex) {
                        Logger.getLogger(DungeonEditor.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
        }
    }
    Last edited by Psyclone; 02-19-2010 at 02:23 AM.

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

    Default

    Something like this has worked for me:
    Java Code:
          JButton exitBtn = new JButton(new AbstractAction("Exit") {
             public void actionPerformed(ActionEvent arg0) {
                Window win = SwingUtilities.getWindowAncestor(mainPanel);
                win.dispose();
             }
          });

  3. #3
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    "Close the frame" can mean different things. You can set its visibility to false, which will hide it. You dispose() it and set any references to it to null, which will get rid of it. That could also end the application, if no other top-level windows exist. Or, you can end the application using System.exit(0).

  4. #4
    Psyclone is offline Member
    Join Date
    Jan 2010
    Posts
    81
    Rep Power
    0

    Default

    "Close the frame" can mean different things.
    Sorry, I meant closing the frame and exiting the program.

    Both suggestions (Fubarable and Steve) worked great.

    I have a follow-up question now. I have a button on my mainFrame that brings up a subFrame. I want the mainFrame to be disabled while the subFrame is up and then get enabled when the subFrame is closed.

    I have 2 buttons in the subFrame ("OK" and "Cancel"). Both buttons dispose the subFrame and re-enable the mainFrame. The first thing that the subFrame does when it is activated is to disable the mainFrame. I used Fubarables suggestion to do this using...

    Java Code:
            Window win = SwingUtilities.getWindowAncestor(mainPanel);
            win.setEnabled(false);
    The subFrame is just a simple frame that brings up a JTextField and the 2 buttons ("OK" and "Cancel"). When the user inputs a valid string into the TextField... pressing Enter or clicking OK will dispose the subFrame and re-enable the mainFrame. Or if the user clicks Cancel, it also disposes the subFrame and re-enables the mainFrame. My problem now is that when the user exits the subFrame by exiting via the X button (windows close button), I don't know how to re-enable the mainFrame.

    Is there a way to execute a command or method when someone exits in this way? Just a simple mainFrame.setEnable(true) would be enough.

    Java Code:
        JButton renameButton = new JButton("Rename");
        panelLeft2.add(renameButton);
        renameButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                renameButton(e);
                  }
                });
     
        public void renameButton(ActionEvent e) {
            Window win = SwingUtilities.getWindowAncestor(mainPanel);
            win.setEnabled(false);
    
            // execute
            
                    renameTextField.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    closeRenameWindow = false;
                    renameButtonOK(e);
                    if(closeRenameWindow == true) {
                        Window win = SwingUtilities.getWindowAncestor(mainPanel);
                        win.setEnabled(true);
                        renameFrame.dispose();}
                      }
                    });
     
            JButton renameButtonOK = new JButton("OK");
            renameButtonOK.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    closeRenameWindow = false;
                    renameButtonOK(e);
                    if(closeRenameWindow == true) {
                        Window win = SwingUtilities.getWindowAncestor(mainPanel);
                        win.setEnabled(true);
                        renameFrame.dispose();}
                      }
                    });
     
            JButton renameButtonCancel = new JButton("Cancel");
            renameButtonCancel.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    Window win = SwingUtilities.getWindowAncestor(mainPanel);
                    win.setEnabled(true);
                    renameFrame.dispose();
                      }
                    });
            }
        }
    
        public void renameButtonOK(ActionEvent e) {
                if(renameTextField.getText().length() > 0 && renameTextField.getText().length() < 16)
                    closeRenameWindow = true;
                else if(renameTextField.getText().length() == 0)
                    renameError.setText("Name cannot be blank.");
                else if(renameTextField.getText().length() > 0)
                    renameError.setText("Name cannot be longer than 15 characters.");
                renameTextField.setText("");
            }

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

    Default

    Use either a JOptionPane or a modal JDialog for the "subframe" as this is what they are specifically built to do.

  6. #6
    Psyclone is offline Member
    Join Date
    Jan 2010
    Posts
    81
    Rep Power
    0

    Default

    Use either a JOptionPane or a modal JDialog for the "subframe" as this is what they are specifically built to do.
    I started reading and learning how to do this, but wasn't sure how do arrange the layout based on the tutorials I was reading. While I was searching for the answer, I found out that I can add WindowListeners to the renameFrame.

    I just added the following code and it works like a charm. I had to add win.setVisible(true) in order for it to keep the mainFrame from being minimized after disposing the renameFrame. It only happens when I dispose of the from by X-ing out.

    Java Code:
            renameFrame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosed(WindowEvent e) {
                    Window win = SwingUtilities.getWindowAncestor(mainPanel);
                    win.setEnabled(true);
                    win.setVisible(true);
                }
            });

  7. #7
    Psyclone is offline Member
    Join Date
    Jan 2010
    Posts
    81
    Rep Power
    0

    Default

    Thanks again as always Fubarable!

  8. #8
    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 Psyclone View Post
    I started reading and learning how to do this, but wasn't sure how do arrange the layout based on the tutorials I was reading.
    Put everything into a JPanel using whatever layout you desire. Then place that JPanel into a JDialog's contentPane just as you would put it into a JFrame's contentPane, pack the dialog, call setVisible(true), and that's it.

    While I was searching for the answer, I found out that I can add WindowListeners to the renameFrame.

    I just added the following code and it works like a charm. I had to add win.setVisible(true) in order for it to keep the mainFrame from being minimized after disposing the renameFrame. It only happens when I dispose of the from by X-ing out.

    Java Code:
            renameFrame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosed(WindowEvent e) {
                    Window win = SwingUtilities.getWindowAncestor(mainPanel);
                    win.setEnabled(true);
                    win.setVisible(true);
                }
            });
    While this may work for this situation, I think you're far better off learning to use dialogs as they are the proper solution for this kind of problem, and this knowledge will be applicable in multiple other situations.

Similar Threads

  1. add tabbed pane to the frame on a button click
    By Mahaveer in forum New To Java
    Replies: 0
    Last Post: 11-20-2009, 10:19 AM
  2. New button in new frame
    By billbo123 in forum New To Java
    Replies: 0
    Last Post: 03-01-2009, 11:32 PM
  3. how disable the display of close button on the frame
    By kalanidhi in forum New To Java
    Replies: 6
    Last Post: 11-19-2008, 10:51 AM
  4. close a frame..
    By tajinvillage in forum New To Java
    Replies: 5
    Last Post: 04-27-2008, 11:22 PM
  5. Frame close operation
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-21-2007, 09:39 AM

Posting Permissions

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