1

I'm a rookie when it comes to programming. We have this project about a log-in profile account. I just started doing it; and I came across a specific problem. I want to close a frame using a button.

buttonenter.setText("Enter");
     buttonenter.addActionListener(new ActionListener (){
       public void actionPerformed (ActionEvent ae){

           }
    });

I tried placing my frame.dispose();, set.Visible(false) etc. but i just got an error. I don't quite get. I really appreciate the help! Thank you!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Frances T.
  • 25
  • 1
  • 5
  • Look like duplicated question: http://stackoverflow.com/questions/12688874/close-window-on-button-click – Farnabaz Oct 05 '12 at 16:04

3 Answers3

4

Here's a simple example of what you're trying to do. What errors are you receiving?

private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton btnClose = new JButton("CLOSE");
    btnClose.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            frame.setVisible(false);
        }
    });
    frame.getContentPane().add(btnClose, BorderLayout.NORTH);
}
Drose
  • 116
  • 5
  • Thank you so much for your help. :D I got my answer. the setVisible and dispose() was helpful. I guess I should read more. :D Problem solve! :D – Frances T. Oct 07 '12 at 14:21
3

from JButtons ActionListener you can to call

  • JFrame#dispose(); (terminating current JVM)

  • JFrame#setVisible(false); (hide JFrame)

  • System.exit(0); (terminating current JVM)

and/or with (another standard ways are)

mKorbel
  • 109,525
  • 20
  • 134
  • 319
0

when you close any objects by false visible, actually you just hide that object whereas the object stays in the memory yet.

you better use the frame.dispatchEvent(new windowEvent(frame,windowEvent.window_closeing)); method

reza
  • 1