Java Application Restart or Reset Button - java

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.

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

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

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);
}
}

Related

Handling button event from another class in Jframe

I am using netbeans to make a GUI. To make it simple, let say what I want to do is that when I press a button it just opens a new JFrame and print a text on a JPanel, a text entered by the user.
It sounds easy if I just complete the automatically generated function from Netbeans :
private void popUpButtonActionPerformed(java.awt.event.ActionEvent evt) {
// I added these three lines
JFrame newFrame = new myPopUpWindow();
myPopupWindow.getTextLabel().setText("Hello" + enteredText.getText());
this.dispose();
}
And everything works as I want. Now what I want to do is having a cleaner code. I want to put these two line in a class ButtonHandler.java in a function handleHelloPopUp(String enteredStringText) Now comes the dilemma:
If I make handleHelloPopUp static, I get some error when I access some non static variable
If I don't make handleHelloPopUp I just have to pass it as argument in my Jframe -> horrible code structure
What is the best way to do this ? Please help ...

Setting JFrame Defaults

There seems to be three lines where I'm wondering why do I need them. To me, it just seems like Java could eliminate this by setting it as the default and letting you turn off.
To me it's assumed that of course I want my label displayed, the exit to actually exit, and my textbox to be visible, otherwise why would I go through all the trouble to build.
Is it possible to remove those lines to have the same code?
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GuiClass extends JFrame {
private JLabel myLabel;
public GuiClass(){
super("The title bar");
setLayout (new FlowLayout());
myLabel = new JLabel ("this is a main text");
myLabel.setToolTipText ("this is the hover text");
add(myLabel); //why do i need this?
}
}
GuiClassMain
import javax.swing.JOptionPane;
import javax.swing.JFrame;
public class GuiClassMain {
GuiClass myText = new GuiClass();
myText.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//why do i need this?
myText.setSize(275,80);
myText.setVisible(true);//why do i need this?
}
}
add(myLabel); //why do i need this?
Just because you create a component, the program doesn't know where you want to add the component. You may have two different panels, which is normal for a more complex GUI. It also doesn't know what layout manager is being used and you may need to specify a "constraint" for the layout manager.
Read the section from the Swing tutorial on Using Layout Manager for more information on layout managers that require constraints. The BorderLayout would be the easiest to start with.
myText.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//why do i need this?
Try removing the statement and see what happens. Who says you want to always exit the application? Maybe you just want to hide the frame so it can be redisplayed.
myText.setVisible(true);//why do i need this?
This tells Swing that all components have been added to the frame so know you can display the frame.
myText.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//why do i need this?
This allows you to change the default close operation of the window, obviously, because you don't want ever window you create to terminate the VM. The default value is set to HIDE_ON_CLOSE for safety reasons, because you simply don't want ever window you create to terminate the VM, usually, you only want the main window to do this...
myText.setVisible(true);//why do i need this?
By default all windows are invisible when they are created. This is done for a number of reasons, the main reason actually tries to solve an issue with how a window's contents is validated. It also means that when you create a window, you can decide when you actually want it to be displayed, rather then showing, what would be, a blank window...
add(myLabel); //why do i need this?
This is one of this "why not?" questions. You need to associate a component with a container, otherwise it has no clue about where it should be displayed.
Because you may have many containers, all with different layout requirements, you need to specify which container each component should be associated with.
As you create more complex interfaces, this will make more sense.
You are kind of right. The developers can make them by default, but this will restrict you. All your questions are only valid if there is only one JFrame or JPanel.
There may be more than one JFrame or JPanel and you may wish to add a JLabel to any one of them. If it is done by default, one will be selected and you can not change.
Well, you may not always exit the program when you close a JFrame. Say, you have two windows: when the master window is closed it exits (or, terminates) the program; but when the slave window is closed it only disposes (JFrame.DISPOSE_ON_CLOSE) the slave window, the master window still works on- that means only this slave window will be closed, but the program will not be terminated.
Again, consider the case when you have created more than one window, but want not to display all of them. All of them won't be visible by default (To me, it is unclear why it is set by default).
I'll give you examples quickly.

Using KeyListener for a Calculator in NetBeans

I have written a calculator in NetBeans and it functions perfectly. However, I have to actually click the buttons to insert numbers and am trying to remedy that with a KeyListener. I have all my numbers and function buttons set inside a JPanel named buttons. I have my display label in a JPanel named display.
I set my class to implement KeyListener and it inserted the KeyPressed, -Typed, and -Released methods; however I stuck from there. I'm not sure how to make my buttons actually listen for the KeyPressed event, and when it hears the event - activate the button. Also, my buttons are named by their number (e.g. the Zero Button is named zero, One button is one, etc.).
I've read that you actually have to implement a KeyListener somewhere by using: something.addKeyListener(something);
but I cannot seem to figure this out.
Can I get some help here? I'm new to Java and this is my first solo project. And let me know if I didn't provide enough information.
EDIT: Most of my code is NetBeans Generated and I cannot edit the initialization of the components which seems to be my problem I think?
My class declaration:
public class Calculator extends javax.swing.JFrame implements KeyListener {
//Creates new form Calculator
public Calculator() {
initComponents();
}
One of my buttonPressed actions (all identical with changes for actual number):
private void zeroActionPerformed(java.awt.event.ActionEvent evt) {
if (display.getText().length() >= 16)
{
JOptionPane.showMessageDialog(null, "Cannot Handle > 16 digits");
return;
}
else if (display.getText().equals("0"))
{
return;
}
display.setText(display.getText().concat("0"));
Main method supplied by NetBeans:
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Calculator().setVisible(true);
}
});
}
The initComponents() netbeans generated is absolutely massive (about 500 lines of code) and I cannot edit any of it. Let me know if I can supply any more helpful information.
Could there be an issue of Focus, and if so how can I resolve the issue?
Yes there is probably an issue with focus. That is why you should NOT be using a KeyListener.
Swing was designed to be used with Key Bindings. That is you create an Action that does what you want. Then this Action can be added to your JButton. It can also be bound to a KeyStroke. So you have nice reusable code.
Read the Swing tutorial on How to Use Key Bindings for more information. Key Bindings don't have the focus issue that you currently have.
I'm not sure I completely understand your question, and some code would help, but I'll take a crack, since it sounds like a problem I used to have a lot.
It sounds like the reason that your key presses aren't being recognized is that the focus is on one of the buttons. If you add keylisteners to the buttons, then you shouldn't have any problem.
In netbeans you can add keylisteners through the design screen really easily.
Here's a picture showing you how to add a keyPressed listener to a button in a jPanel.
private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {
//Check which key is pressed
//do whatever you need to do with the keypressed information
}
It is nice to be able to write out the listeners yourself, but if you are just learning, then it is also nice to get as much help as possible.
This might not be the best solution, since you would have to add the listener for each of your buttons.

repaint a frame in java

I have written code for an online quiz. I would like to change questions by clicking "next" button, but repaint is not working; only new window is working.
i can't even hide jftMainFrame since it works for 8 windows only.quest is a list containing questions and options ,its accessed from access db.repaint() is not working while i click the button.
i have 4 radiobuttons which displays the label.i want to repaint the label of radiobutton and also question
Please help me.
JFrame jtfMainFrame, jtfMainFrame1;
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Next question..");
j++;
quest = getCurrentQuestion();
createWindow();
validate();
}
});
I would like to change questions by clicking "next" button,
I think that your question is about using CardLayout, rather than create lots of Top-Level Comtainers on runtime
Your question is definitely not clear.
What are you trying to do. If you are simply trying to "repaint/refresh" a panel or a component use paintImmediately();
for example
jMyPanel.paintImmediately(jMyPanel.getVisibleRect());
Hope it helps

Java MouseEvents not working

This may be a stupid question, but I have to ask!
I have the following code snippets that are supposed to run their corresponding methods when the user interacts with objects.
For some reason, "foo" is never printed, but "bar" is.
myJSpinner1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
System.out.println("foo"); //"foo" is not printed
}
});
myJSpinner2.addChangeListener(new java.awt.event.ChangeListener() {
public void stateChanged(java.awt.event.ChangeEvent evt) {
System.out.println("bar"); //"bar" is printed
}
});
I get no exceptions or stack trace. What am I missing in the MouseListener one?
Thanks in advance.
EDIT: MouseEntered works perfectly on a JCheckBox implemented in exactly the same way!
JSpinner is a composite component consisting of a text field and 2 buttons. It's possible to add mouse listeners to all of those by iterating over the results of getComponents() and adding a listener to each.
However, in my experience, when something takes that much work, you're probably going about it the wrong way.
Why do you need the mouse-entered information for a JSpinner?
What do you want to do with this event?
Update:
If you're looking to supply information about all of the controls in your panel, you may want to look at using a glasspane to detect the component under the mouse.
A Well-behaved Glasspane by Alexander Potochkin is a good place to start.
This is a guess but I suspect you need to add a MouseListener to the JSpinner's editor (via a call to getEditor()). I imagine that the editor Component occupies all available space within the JSpinner and is therefore intercepting all MouseEvents.
This worked for me.
JSpinner spinner = new JSpinner();
((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().addMouseListener(
new java.awt.event.MouseAdapter() {
public void mouseClicked(final MouseEvent e) {
// add code here
}
});
I needed this in order to evoke a popup key dialog for added usability due to our software requirements.
Aditional to #Rapier answer...
If you change the Spinner using something like
yourOldSpinner = new JSpinner(new SpinnerModel(...))
you will lost your previosly MouseListener...
If you need to change something of SpinnerModel, Don't create a new, change its parameters instead! (if you do it, you will need to reassign the MouseListener again, because it will be lost when you assign a new SpinnerModel).
an example (I'm talking...):
((SpinnerNumberModel)yourOldSpinner.getModel()).setValue(size/3);
((SpinnerNumberModel)yourOldSpinner.getModel()).setMinimum(0);
((SpinnerNumberModel)yourOldSpinner.getModel()).setMaximum(isize/2);
((SpinnerNumberModel)yourOldSpinner.getModel()).setStepSize(1);

Categories

Resources