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?

tshepang
  • 10,772
  • 21
  • 84
  • 127
user594860
  • 51
  • 1
  • 1
  • 2

6 Answers6

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

RoflcoptrException
  • 49,973
  • 34
  • 147
  • 199
  • I don't know netbeans has automaticaaly created it when I chose Java Desktop Application option in create new project dialog. – user594860 Feb 06 '11 at 11:11
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

Ordiel
  • 2,151
  • 3
  • 31
  • 47
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.

Petar Minchev
  • 44,805
  • 11
  • 98
  • 117
  • @user - Ah, you want the button in the header. I thought you had your own JButton. See my updated answer:) – Petar Minchev Feb 06 '11 at 11:26
  • @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?? – user594860 Feb 06 '11 at 18:12
2

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

Community
  • 1
  • 1
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.

trashgod
  • 196,350
  • 25
  • 213
  • 918
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