Does anyone know how to make a jbutton close a gui? I think it is like System.CLOSE(0);
but that didnt work. it also could be exitActionPerformed(evt);
, but that didn't work either. just the line of code will work.
EDIT: never mind guys. the answer was System.exit(0);
. thanks for the help though!
This question is related to
java
swing
user-interface
jbutton
Create a method and call it to close the JFrame, for example:
public void CloseJframe(){
super.dispose();
}
You may use Window#dispose() method to release all of the native screen resources, subcomponents, and all of its owned children.
The System.exit(0)
will terminates the currently running Java Virtual Machine.
JButton close = new JButton("Close");
close.addActionListener(this);
public void actionPerformed(ActionEvent closing) {
// getSource() checks for the source of clicked Button , compares with the name of button in which here is close .
if(closing.getSource()==close)
System.exit(0);
// This exit Your GUI
}
/*Some Answers were asking for @override which is overriding the method the super class or the parent class and creating different objects and etc which makes the answer too long . Note : we just need to import java.awt.*; and java.swing.*; and Adding this command : class className implements actionListener{} */
See JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)
1. You might also use EXIT_ON_CLOSE
, but it is better to explicitly clean up any running threads, then when the last GUI element becomes invisible, the EDT & JRE will end.
The 'button' to invoke this operation is already on a frame.
DISPOSE_ON_CLOSE
functionality.In Java 8, you can use Lambda expressions to make it simpler.
JButton btnClose = new JButton("Close");
btnClose.addActionListener(e -> System.exit(0));
JButton btnClose = new JButton("Close");
btnClose.addActionListener(e -> this.dispose());
By using System.exit(0); you would close the entire process. Is that what you wanted or did you intend to close only the GUI window and allow the process to continue running?
The quickest, easiest and most robust way to simply close a JFrame or JPanel with the click of a JButton is to add an actionListener to the JButton which will execute the line of code below when the JButton is clicked:
this.dispose();
If you are using the NetBeans GUI designer, the easiest way to add this actionListener is to enter the GUI editor window and double click the JButton component. Doing this will automatically create an actionListener and actionEvent, which can be modified manually by you.
Source: Stackoverflow.com