How to set action for close button?
Asked Answered
A

6

5

I've created a stand-alone java desktop application in Netbeans 6.9. I want to set the action for the close button of my application. I want to know how and where to set the code for the action of that close button. Can anyone please help me regarding this?

Ambassadress answered 6/2, 2011 at 11:7 Comment(1)
You should set aside your IDE and learn Java.Rivalee
L
4

You have to register an ActionListener on your close button. In this listener you can define what do to.

How add ActionListener to JButton in Java Swing

Lallygag answered 6/2, 2011 at 11:9 Comment(1)
I don't know netbeans has automaticaaly created it when I chose Java Desktop Application option in create new project dialog.Ambassadress
D
2

Right-click on the button then, > Events > Action > actionPerformed. NetBeans will generate the action listener for you:)

Edit: If you want a close listener, then read here.

Diaconicon answered 6/2, 2011 at 11:10 Comment(2)
@user - Ah, you want the button in the header. I thought you had your own JButton. See my updated answer:)Diaconicon
@Peter your answer works for the Jbutton that we create but what to do about the one that is automatically created by Netbeans when we create a desktop app through it??Ambassadress
O
2

I think answers for How to close a java swing application from the code will be helpful too

Obed answered 6/2, 2011 at 11:18 Comment(0)
G
2

Once you have the handler working, one convenient approach is to "set the default button by invoking the setDefaultButton() method on a top-level container's root pane." See the tutorial section How to Use JButton Features for details.

Guinea answered 6/2, 2011 at 20:14 Comment(0)
A
2

I dislike to wake up the zombies but, here is what I would do (this is considering that you are working in a Window based application, otherwise this is going to be useless!!!):

  1. I would set a window listener for the close operation here is the way to do it.
  2. Then I will delete manually the temp folders and files...

Obviously the window listener I'm talking about would go on the last window you (as a user) should close, this would not work either if you want it to happen when the last window is closed, but there is not an order specified to do that, some workarounds for that is making all your windows to share a flag/counter to indicate if it is time to delete the temp files/folders.

Again if your application is going to work underground sometimes (I mean that you can dispose all windows without shutting down the application), or is a daemon this won't work

Alejandro answered 8/2, 2013 at 14:24 Comment(0)
F
1

If you just want to exit the application when the close button is hit, you can use

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

as explained in the Oracle tutorial

Frothy answered 7/4, 2013 at 11:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.