I am new to Swing so this might seem like a very naive question.
I have a JFrame which displays an initial statement and two radiobuttons. RadioButton1 is Accept and RadioButton2 is Reject. If the user chooses Accept, the program proceeds. So I have created an ActionListener for Accept so that the rest of my code is within this ActionListener. However, as soon as the user presses Accept, the GUI freezes. Pressing Reject just exists out of the program.
public void game() throws Exception
{
jTextArea1.setLineWrap(true);
jTextArea1.setWrapStyleWord(true);
jTextArea1.setText("Please choose Accept or Reject");
jRadioButton1.setVisible(true);
jRadioButton2.setVisible(true);
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1.setVisible(false);
jRadioButton2.setVisible(false);
repaint();
//more code
});
}
After this I make connections to the server which works fine since when I use System.out.println(), all the outputs are fine, just the GUI is frozen.
Is there a better way to continue when the user presses Accept?
You can look at using the SwingWorker class.
Basically, Java Swing applications are single threaded and if there are any process intensive tasks which you perform, the control transfers to that section of code and the UI hangs, waiting for control to be handed back.
Edit: You can also look into the SwingUtilities class.
Edit: Basic info on using the SwingWorker class:
You can create a new class which extends SwingWorker and implement the public String doInBackground() {
/*Do Stuff here*/
}
method. And in your ActionListener event, create an instance of the SwingWorker and call the swingWorkerObject.execute()
method to start the doInBackground method execution.
More details here: http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html