Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 14 of 14

Thread: Creating a close button

  1. #1
    Junior Member Zomby's Avatar
    Join Date
    Oct 2012
    Location
    California
    Posts
    7
    My Mood
    Cynical
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Creating a close button

    Okay so I am currently learning java, so my knowledge is limited. I have read through allot of threads but have not found exactly what I need.

    package glasshelloworldredux;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
     
    public class GlassHelloWorldRedux extends JFrame
    {
        private JFrame window;
        private JLabel message;
        private JButton button;
        private JPanel panel;
        private final int WINDOWWIDTH = 300,
                          WINDOWHEIGHT = 150;
     
        public GlassHelloWorldRedux()
        {
            super("Glass Hello World Redux!");
     
            setSize(WINDOWWIDTH, WINDOWHEIGHT);
     
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            buildPanel();
     
            add(panel);
     
            setVisible(true);
        }
     
        private void buildPanel()
        {
            message = new JLabel("Hello World!");
            button = new JButton("Close");
            panel = new JPanel();
     
            panel.add(message);
            panel.add(button);
     
            button.addActionListener(new ButtonListener() );
        }
     
        private class ButtonListener implements ActionListener
        {
     
            @Override
            public void actionPerformed(ActionEvent e)
            {
                setVisible(false);
            }
        }
    }

    Here is my code excluding the main class, witch simply just calls this class. So I can get the frame to close by setting the visibility to false, but the program is still running. I cant seem to figure out what to do next to get the program to end when setVisible(false) is active. And help would be great full, and thank you all for your time.


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Creating a close button

    The method you are looking for is called dispose.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Creating a close button

    to get the program to end
    Calling the System class's exit() method will end the program.
    If you don't understand my answer, don't ignore it, ask a question.

  4. #4
    Member
    Join Date
    Oct 2012
    Posts
    38
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Creating a close button

    Quote Originally Posted by Norm View Post
    Calling the System class's exit() method will end the program.
    I'm told that's not a good idea, as it simply pulls the main process without disposing of reserved resources, but I can't say whether this is the case or not.

    I do know I prefer to use dispose(), myself. However, when using dispose() on a JFrame, you need to make sure that you've already killed all other windows that that JFrame has called, or else the Frame won't dispose entirely and will be left waiting for the windows to close. This will cause your programme to appear like it's closed but still be left running in the background. Typically, any object you add to a frame using its getContentPane.add() will include anything you add as a child and run its own dispose() method to try and shut it down, but that doesn't always work.

    I know I've had trouble with JOptionPane instances called through the JOptionPane factory methods, specifically assigning a JFrame as a parent for one, which the kept throwing exceptions claiming it's being called from something that's not its parent, until I figured out I had the supply the JFrame's actual contentPane object as a parent since that's actually calling it. Or was it the other way around? Point is, sometimes you'll call dispose() on a frame and it'll disappear, but your programme won't end because other windows are hidden but still running. My only real advise is call dispose() on any extra window when you don't need it any more, especially if you've called it through a factory method as opposed to adding it to the frame directly.

    ---

    Basically, I tend to try and avoid using System.exit(int) if I can help it, as well as the JFrame.EXIT_ON_CLOSE behaviour. It's easier and quicker, but it seems to me to be much too quick to clean up after itself.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Creating a close button

    The API doc says:
    Terminates the currently running Java Virtual Machine.

    When the JVM ends, there is nothing left of your java program.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Member
    Join Date
    Oct 2012
    Posts
    38
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Creating a close button

    Fair enough. I'm not that familiar with Java's guts workings so I'm going by what I've been told by random people over the years. I don't remember what the stated problem was, basically.

  7. #7
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Creating a close button

    System.exit() will terminate your program, full stop (well, there are a few bits of code you can get to run after/inside of System.exit(), but essentially it's the end).

    The primary reason not to use System.exit() has to deal with code reuse/integration. You may create one application window which does some work, and at some point and time the user closes the window. It's fine and dandy to either dispose the dialog or use System.exit() to end the JVM if you are certain you always want to stop the JVM. If instead you simply want to get rid of your window, use dispose(). This means if you decide later you want to integrate your window with other windows/dialogs you don't have to worry about abruptly ending the other windows/dialogs (again, if you intend to do that you may want to consider using System.exit()).

    However, disposing and getting your program to close "normally" isn't a guaranteed way to end your program. An exception you weren't expecting or forgetting to stop a thread will keep the JVM from ending even if that's what you wanted. It could be argued that these are bugs and you should go and fix them properly, but in life and business time is money and you may not need the "proper" solution if it comes at a significant cost.

    The best recommendation I can provide is evaluate your situation on a case-by-case basis. Usually you can determine which method is preferred (the reason may even be personal/team preference, experience is a powerful tool). If you don't have a reason to choose one method over the other, choose "normal" program termination (a.k.a. dispose of your resources properly).

    Another option you may want to consider is you can set the close action to JFrame.DISPOSE_ON_CLOSE (or technically, WindowConstants.DISPOSE_ON_CLOSE).
    Last edited by helloworld922; October 9th, 2012 at 12:12 PM.

  8. The Following 2 Users Say Thank You to helloworld922 For This Useful Post:

    Fazan (October 9th, 2012), Zomby (October 11th, 2012)

  9. #8
    Junior Member Zomby's Avatar
    Join Date
    Oct 2012
    Location
    California
    Posts
    7
    My Mood
    Cynical
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Creating a close button

    Thank you all for your time in responding to my question, it was all very helpful.

  10. #9
    Junior Member Zomby's Avatar
    Join Date
    Oct 2012
    Location
    California
    Posts
    7
    My Mood
    Cynical
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Creating a close button

    So after playing around with the System.exit() command and seeing what that can do and how it works with the specific program I was writing, I was happy to see it work the way I wanted it to. But know I am trying to figure out how the dispose() command works. When I use the dispose() command the program throws a list of errors and dose not stop running.

    Here is the Code.
    /*
     * 
     *  
     * 
     * 
     */
    package glasshelloworldredux;
     
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.*;    // Imports awt.event.*
    import javax.swing.*;
     
    public class GlassHelloWorldRedux extends JFrame
    {
        private JFrame window;                  // Adds a JFrame and names it window
        private JLabel message;                 // Adds a JLabel and names it meesage
        private JButton button;                 // Adds a JButton and names it button
        private JPanel panel;                   // Adds a JPanel and names it panel
        private final int WINDOWWIDTH = 300,    // Sers height and width for window
                          WINDOWHEIGHT = 150;
     
        public GlassHelloWorldRedux()
        {
            super("Glass Hello World Redux!");  // Names the JFrame
     
            setSize(WINDOWWIDTH, WINDOWHEIGHT); // Calls the width and height
     
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
            // Sets action when window is closed
     
            buildPanel();   // Builds panel
     
            add(panel);     // Adds panel
     
            setVisible(true);   // Sets the window visibilty to true
        }
     
        private void buildPanel()       // Specifiys how panel will look
        {
            message = new JLabel("Hello World!");   //  
            button = new JButton("<html><b><u>Close</u></b></html>");
            panel = new JPanel();
     
            message.setFont(new Font("Courier New", Font.BOLD, 24));
            message.setForeground(Color.WHITE);
            panel.setBackground(Color.BLACK);
            button.setFont(new Font("Impact", Font.PLAIN, 14));
            button.setBackground(Color.BLACK);
            button.setForeground(Color.WHITE);
            button.setBorder(null);
     
            panel.add(message);
            panel.add(button);
     
            button.addActionListener(new ButtonListener() );
        }
     
        private class ButtonListener implements ActionListener
        {
     
            @Override
            public void actionPerformed(ActionEvent e)
            {
                setVisible(false);
                window.dispose();
                //System.exit(WINDOWWIDTH);
            }
        }
    }

    And here are the exeptions that I am getting.
     

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at glasshelloworldredux.GlassHelloWorldRedux$ButtonLi stener.actionPerformed(GlassHelloWorldRedux.java:6 6)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.jav a:6505)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3321)
    at java.awt.Component.processEvent(Component.java:627 0)
    at java.awt.Container.processEvent(Container.java:222 9)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4861)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2287)
    at java.awt.Component.dispatchEvent(Component.java:46 87)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719 )
    at java.awt.Component.dispatchEvent(Component.java:46 87)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:713)
    at java.awt.EventQueue.access$000(EventQueue.java:104 )
    at java.awt.EventQueue$3.run(EventQueue.java:672)
    at java.awt.EventQueue$3.run(EventQueue.java:670)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:686)
    at java.awt.EventQueue$4.run(EventQueue.java:684)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 683)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:244)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:147)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:139)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:97)




    at glasshelloworldredux.GlassHelloWorldRedux$ButtonLi stener.actionPerformed(GlassHelloWorldRedux.java:6 6)
    this line of code is window.dispose();

    So my question is where do I start to work through these thrown errors so I can learn exactly what I am doing wrong? Am I missing something small in my code? I know that I still have a lot to learn but any help will be appreciated.
    Last edited by Zomby; October 12th, 2012 at 02:20 PM.

  11. #10
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Creating a close button

    You never set the window field to anything so it's null to begin with. I'm guessing you want it to dispose of the current window so in your constructor you can set window to this.

    Better yet, modify your ButtonListener class to hold the reference to the window rather than having it in your GlassHelloWorldRedux class. Then create a constructor which takes the parent class.

  12. #11
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Creating a close button

    You should not be extending JFrame unless there is a need to do so. The code shown here does not show a need to override JFrame, just to use one.

    Just a note. Don't let 400 lines of error report discourage you. Always treat code as if there is exactly one error. The compilers do a great job of looking over the code, but a mistake as simple as missing a } or { can cause mass confusion in the way the compiler sees the code. This leads to reporting many errors that just do not exist. Take the first complaint in the error message, and correct it. From there try to compile again. If there is an error at that point, there is exactly one error to fix. Continue this one-at-a-time process until the code compiles.

    You say that the error points to window.dispose(). What is the value of window at that point? Has it been initialized to a value?
    Somewhere in the code there should be a line that says window = new <something of type JFrame>

    In this case maybe you meant to make window refer to an instance of your class that extends JFrame?

  13. #12
    Junior Member Zomby's Avatar
    Join Date
    Oct 2012
    Location
    California
    Posts
    7
    My Mood
    Cynical
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Creating a close button

    Now that I realized I did not initialize the window I no longer get the errors, but the program still continues to run until I stop it in the IDE or kill the java.exe through the task manager.

  14. #13
    Member
    Join Date
    Jun 2012
    Posts
    41
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Creating a close button

    You still have a System.exit() call? It must not actually be called, because...well...that stops EVERYTHING.

  15. #14
    Member
    Join Date
    Sep 2012
    Location
    The Netherlands
    Posts
    84
    My Mood
    Inspired
    Thanks
    4
    Thanked 1 Time in 1 Post

    Default Re: Creating a close button

    If you have a panel/frame with a JButton on it.
    And when it is clicked it will close the whole program.
    To do this as said by other poster you need to use the System.exit(0);
    It will idd close everthing, it also should stop it from working the program in the IDE.

    If you do use the System.exit(0) in your code, maybe the button is not good connected with the actionPerformed()

    If you have more problems with it maybe you can show a little bit of code?
    Of where it goed wrong.

    Hope I helped a little.

Similar Threads

  1. How to close a frame on a button click ??
    By rk0887 in forum AWT / Java Swing
    Replies: 1
    Last Post: August 22nd, 2012, 08:58 AM
  2. Replies: 1
    Last Post: February 10th, 2012, 10:05 AM
  3. Is this correct.Am I close? Help please
    By eagle09 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: June 26th, 2011, 07:26 AM
  4. Trying to add a close button
    By coyboss in forum Java Theory & Questions
    Replies: 5
    Last Post: February 12th, 2011, 03:28 PM
  5. close JDialog on button click
    By Christophe in forum AWT / Java Swing
    Replies: 4
    Last Post: April 4th, 2010, 11:04 PM

Tags for this Thread