Reputation: 113
I have a very simple, choose your path, Java game that I am working on in the NetBeans IDE. Basically what happens is the user will click one of the three buttons, and pre-made JLabel
's which are set to ""
(nothing) will be reset to whatever text I decide that label should then use. I do this by adding the code below.
private void option1ActionPerformed(java.awt.event.ActionEvent evt) {
jLabel6.setText("You go down the dark tunnel...");
}
Now all this works fine but I'd like a way to restart/reset my application by clicking a button labelled "restart". I don't mind if it has to close the application and then open it again or if it will simply reset all the JLabel's back to "". I just don't want to have to type out the code below for every single JLabel.
jLabel1.setText("");
jLabel2.setText("");
jLabel3.setText("");
I have done some research on this site and none of the code that people provide seems to work for my situation, either because it simply doesn't work or because I am doing something wrong. Any help would be greatly appreciated and please try and be specific because I am fairly new to writing Java and don't understand everything.
It would also work for me if someone could provide a way for me to close 1 window in an application instead of the whole thing, like when
System.exit(0);
is used.
Upvotes: 0
Views: 34547
Reputation: 113
Found the answer to my own question:
Thanks to Holger for suggesting "dispose". This is what I found worked.
private void restartButtonActionPerformed(ActionEvent evt) {
if(evt.getSource() == restartButton)
{
dispose();
MyGUI game = new MyGUI();
game.setVisible(true);
}
}
Upvotes: 1
Reputation: 5712
If you are having your program as a executable jar file then you can use
public void restert(){
Runtime.getRuntime().exec("java -jar yourapp.jar");
System.exit(0);
}
If you want to know more about restarting java application you can go through this
Upvotes: 0
Reputation: 987
First, I recommend importing the JLabel class specifically so you can write JLabel
instead of javax.swing.JLabel
:
import javax.swing.JLabel;
Instead of declaring each JLabel individually, create an Array of JLabels:
JLabel[] jLabels = new JLabel[N]; // where N is the number of JLabels
Whenever you need to access a JLabel, use:
jLabels[6].setText("You go down the dark tunnel...");
When you want to reset all the JLabels, use:
for (JLabel jLabel : jLabels) {
jLabel.setText("");
}
For more details on Arrays, read http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Upvotes: 2