我想用java swing做一个小游戏。首先,在欢迎屏幕上,用户必须选择游戏的玩家数量。我试图找到一种方法,当用户选择4个按钮中的一个时,窗口将关闭,他选择的数字将在主窗口中可用,然后下一个窗口将打开(使用用户选择的数字)。这是我的代码。
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();
}
}
}
}
不要使用多个 JFrame
而不是使用 CardLayout
是为同一目的而设计的。你可以在不同的视图(面板)之间切换。
CardLayout类管理两个或更多的组件(通常是JPanel实例),这些组件共享了 同一显示空间.
见 秋千教程 关于 如何使用CardLayout 并发现 例子 也是。
更多信息请阅读 使用多个JFrames,好的坏的做法?