【发布时间】:2014-04-08 07:09:29
【问题描述】:
我正在尝试为游戏中的设置创建一个 GUI 类,它是除 main 之外的自己的类。在 main 中,我实例化了一个设置类的对象,我希望它等到单击它后再继续 main 中的代码。实际上,它实例化对象并在 main 中完成代码,而无需等待输入。我试过 actionListener 但不能让它工作,我猜是因为我的 GUI 与 main 分开。
设置类
public class Settings extends JFrame implements ActionListener
{
private int option;
public Settings()
{
option = 0;
//JFrame
setTitle("Battleship Settings");
setVisible(true);
int xInset = getInsets().left + getInsets().right; //right left window borders
int yInset = getInsets().top + getInsets().bottom; //top bottom window borders
setSize(300 + xInset, 300 + yInset);
setLocationRelativeTo(null); //center window
//Main Panel
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setSize(300, 300);
panel.setBackground(Color.blue);
add(panel);
// Creation of a Panel to contain the Buttons.
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(0, 0);
buttonPanel.setSize(300, 300);
buttonPanel.setBackground(Color.red);
panel.add(buttonPanel);
//Buttons
JButton b1 = new JButton("VS AI");
b1.setSize(180, 30);
int b1CenterX = (int) ((buttonPanel.getSize().getWidth() / 2) - (b1.getSize().getWidth() /2));
b1.setLocation(b1CenterX, 145);
b1.addActionListener(this);
buttonPanel.add(b1);
JButton b2 = new JButton("2 Players");
b2.setSize(180, 30);
int b2CenterX = (int) ((buttonPanel.getSize().getWidth() / 2) - (b2.getSize().getWidth() /2));
b2.setLocation(b2CenterX, 195);
b2.addActionListener(this);
buttonPanel.add(b2);
panel.setOpaque(true);
setDefaultCloseOperation(EXIT_ON_CLOSE); //if you dont exit on close, the program keeps running on the background
}
public int getOption()
{
return option;
}
public void setOption(int optn)
{
option = optn;
}
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().matches("VS AI"))
{
JOptionPane.showMessageDialog(null, "VS AI");
option = 1;
this.dispose();
}
else if (e.getActionCommand().matches("2 Players"))
{
JOptionPane.showMessageDialog(null, "2 Players");
option = 2;
this.dispose();
}
else
JOptionPane.showMessageDialog(null, "Something went wrong");
}
}
这是主要的
public class Main {
public static void main(String[] args)
{
Settings BattleSettings = new Settings();
JOptionPane.showMessageDialog(null, "option # " +BattleSettings.getOption());
}
}
程序在让玩家有机会选择按钮之前在 main 中触发 MessageDialog。我想在创建 GUI 窗口后等待,并在玩家单击按钮后恢复代码。
【问题讨论】:
标签: java jbutton actionlistener