我是编程的新手,我一直在尝试编写一个非常简单的菜单,以允许用户按下JRadioButton选择石头,纸张,剪刀的模式(1个播放器或2个播放器)。我当前的代码侦听选择了哪个按钮,然后将int设置为1或2。然后它使用该数字并使用它来确定在main方法中打开哪个窗口,但是我不知道该怎么做,因为我可以不要将非静态字段引用为静态方法。
我的这段代码将设置模式,然后根据该int确定要打开哪个窗口。
public void actionPerformed(ActionEvent e)
{
if(p1.isSelected())
mode = 1;
else if(p2.isSelected())
mode = 2;
}
public static void main(String args[])
{
RPSMenu window = new RPSMenu();
window.setBounds(300, 300, 400, 100);
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setVisible(true);
if(mode == 1)
{
Rps window1 = new Rps();
window1.setBounds(300, 300, 400, 160);
window1.setDefaultCloseOperation(EXIT_ON_CLOSE);
window1.setVisible(true);
window.setVisible(false);
}
else if(mode == 2)
{
P2RPS window2 = new P2RPS();
window2.setBounds(300, 300, 400, 150);
window2.setDefaultCloseOperation(EXIT_ON_CLOSE);
window2.setVisible(true);
window.setVisible(false);
}
}
如果看到我的完整代码有帮助,就是这样:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RPSMenu extends JFrame
implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
JRadioButton p1, p2;
int mode;
public RPSMenu()
{
p1 = new JRadioButton(" 1 Player ");
p2 = new JRadioButton(" 2 Player ");
ButtonGroup menu = new ButtonGroup();
menu.add(p1);
menu.add(p2);
JButton go = new JButton(" Go! ");
go.addActionListener(this);
Container m = getContentPane();
m.setLayout( new FlowLayout());
m.add(go);
m.add(p1);
m.add(p2);
}
public void actionPerformed(ActionEvent e)
{
if(p1.isSelected())
mode = 1;
else if(p2.isSelected())
mode = 2;
}
public static void main(String args[])
{
RPSMenu window = new RPSMenu();
window.setBounds(300, 300, 400, 100);
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setVisible(true);
if(mode == 1)
{
Rps window1 = new Rps();
window1.setBounds(300, 300, 400, 160);
window1.setDefaultCloseOperation(EXIT_ON_CLOSE);
window1.setVisible(true);
window.setVisible(false);
}
else if(mode == 2)
{
P2RPS window2 = new P2RPS();
window2.setBounds(300, 300, 400, 150);
window2.setDefaultCloseOperation(EXIT_ON_CLOSE);
window2.setVisible(true);
window.setVisible(false);
}
}
}
最佳答案
您的问题是您试图从静态main方法调用非静态代码。解决方案不是这样做,仅使用main方法来设置程序并运行它,而是在类的代码本身中调用其所有其他东西,无论是在其构造函数中还是在init方法中。
例如,main可能看起来像:
public static void main(String[] args) {
// to begin a Swing application in thread-safe mannter
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Create your GUI class;
MyGui myGui = new MyGui();
myGui.init(); // initialize its fields, call your if blocks
// etc...
}
});
}
然后,在您的
init()
方法中,您可以显示一个对话框,该对话框可让用户选择播放器的数量,并以非静态方式初始化和显示GUI。请注意,我不会像您那样交换窗口,而是创建并显示一个JFrame,然后使用CardLayout交换视图(此处将为JPanels)。