Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing JFrame with button click [duplicate]

Tags:

java

swing

I have the jButton1 private member of JFrame and i wanted to close the frame when the button is clicked.

jButton1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
    }
});

I wanted to do super.close() but could not find close for super. Is there some way to refer to the JFrame

like image 870
Mohit BAnsal Avatar asked Feb 28 '10 21:02

Mohit BAnsal


People also ask

How do you make a JFrame close when a button is pressed?

You can use super. dispose() method which is more similar to close operation. Show activity on this post. You cat use setVisible () method of JFrame (and set visibility to false ) or dispose () method which is more similar to close operation.

How do you make a JFrame close itself?

EXIT_ON_CLOSE (defined in JFrame) : Exit the application using the System exit method. Use this only in applications. might still be useful: You can use setVisible(false) on your JFrame if you want to display the same frame again. Otherwise call dispose() to remove all of the native screen resources.

How do I close a JFrame without exiting?

Use anything for setDefaultCloseOperation excepting EXIT_ON_CLOSE . Then, for the cancel button, just dispose() the window. If the application has another running thread, it won't exit. You can also hide a window by calling setVisible(false) .

How do you exit a button in Java?

If you want a JButton that closes the application, you would create the button: JButton Button = new JButton("Close");


Video Answer


4 Answers

You will need a reference to the specific frame you want to close but assuming you have the reference dispose() should close the frame.

jButton1.addActionListener(new ActionListener() {     public void actionPerformed(ActionEvent e)     {        frameToClose.dispose();     } }); 
like image 84
Anton Avatar answered Oct 05 '22 20:10

Anton


JButton b3 = new JButton("CLOSE");  b3.setBounds(50, 375, 250, 50);  b3.addActionListener(new ActionListener() {     public void actionPerformed(ActionEvent e)     {         System.exit(0);     } }); 
like image 42
acp Avatar answered Oct 05 '22 18:10

acp


It appears to me that you have two issues here. One is that JFrame does not have a close method, which has been addressed in the other answers.

The other is that you're having trouble referencing your JFrame. Within actionPerformed, super refers to ActionListener. To refer to the JFrame instance there, use MyExtendedJFrame.super instead (you should also be able to use MyExtendedJFrame.this, as I see no reason why you'd want to override the behaviour of dispose or setVisible).

like image 34
lins314159 Avatar answered Oct 05 '22 19:10

lins314159


You can use super.dispose() method which is more similar to close operation.

like image 36
Shriji Infotech Avatar answered Oct 05 '22 19:10

Shriji Infotech