I'm trying to make a little game with java swing. For starters the welcome screen appears tot he user where he has to choose the number of players for the game. I'm trying to find a way so that when the user chooses 1 of the 4 buttons the window will close, the number he chooses will be available in main and then the next window will open (using the number the user chose). This is my code:
Main.java
package projtest1;
public class Main {
public static void main(String[] args)
{
WelcomeScreen ws = new WelcomeScreen();
ws.setVisible(true);
int k = ws.returnChoise();
System.out.println(k);
//MainScreen ms = new MainScreen();
//ms.setVisible(true);
}
}
WelcomeScreen.java
package projtest1;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WelcomeScreen extends JFrame
{
public int choise=0;
private JLabel firstLabel = new JLabel("Welcome fellas!", JLabel.CENTER);
private JLabel secondLabel = new JLabel("Choose number of players", JLabel.CENTER);
JPanel choisePanel = new JPanel();
private JButton button2 = new JButton("2");
private JButton button3 = new JButton("3");
private JButton button4 = new JButton("4");
private JButton button5 = new JButton("5");
public WelcomeScreen()
{
setTitle("Welcome screen");
setSize(400, 400);
setMinimumSize(new Dimension(400,400));
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout gl = new GridLayout(3, 1);
gl.setHgap(1);
gl.setVgap(2);
setLayout(gl);
add(firstLabel);
add(secondLabel);
choisePanel.setLayout(new FlowLayout());
choisePanel.add(button2);
choisePanel.add(button3);
choisePanel.add(button4);
choisePanel.add(button5);
add(choisePanel);
ClickListener clickListener = new ClickListener();
button2.addActionListener(clickListener);
button3.addActionListener(clickListener);
button4.addActionListener(clickListener);
}
public int returnChoise()
{
return choise;
}
private class ClickListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
String text = e.getActionCommand();
if (text.equals("2"))
{
choise = 2;
System.out.println(choise);
dispose();
}
else if (text.equals("3"))
{
choise = 3;
System.out.println(choise);
dispose();
}
else if (text.equals("4"))
{
choise = 4;
System.out.println(choise);
dispose();
}
else
{
choise = 5;
System.out.println(choise);
dispose();
}
}
}
}