我正在尝试创建一个运行围棋游戏的程序。我想要一个屏幕,可以询问您所讨论的围棋棋盘的大小,一个可以实际玩游戏的屏幕,一个可以让您决定是否再次玩的屏幕。使用 Swing 实现此目的最有效的方法是什么?我看到人们在其他问题上谈论使用 CardLayout,但我的理解是用户可以根据需要在这些屏幕之间切换,这不是我想要的。
如果 Eclipse 中的 native GUI 构建器工作得更好,我也会使用 Eclipse,但我从未弄清楚如何使其工作。
最佳答案
一种稍微不那么模态的方法将允许用户选择并玩几种常见游戏之一。使用这个基于按钮的内存game举个例子,
枚举支持的游戏功能。
将
enum
值的实例添加到JComboBox
。使用
remove()
、validate()
和repaint()
处理更改以更新游戏板。
在此示例中,JLabel
用作游戏的占位符。或者,保留您的游戏 View ,更新您可观察的游戏模型,如 here 中所述。 ,并安排监听 View 根据需要进行响应。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* @see https://stackoverflow.com/a/36714997/230513
*/
public class Go {
private Game game = Game.Easy;
private final JComboBox gameCombo = new JComboBox();
enum Game {
Easy(9), Fast(13), Classic(17), Full(19);
private int size;
private String name;
private Game(int size) {
this.size = size;
this.name = this.name() + ": " + size + "\u00d7" + size;
}
public int size() {
return this.size;
}
@Override
public String toString() {
return this.name;
}
}
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel board = new JPanel() {
@Override
public Color getBackground() {
return Color.cyan.darker();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
};
board.add(new JLabel(game.toString()));
f.add(board);
JPanel p = new JPanel();
for (Game g : Game.values()) {
gameCombo.addItem(g);
}
gameCombo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
game = (Game) gameCombo.getSelectedItem();
board.removeAll();
board.add(new JLabel(game.toString()));
board.validate();
board.repaint();
}
});
p.add(new JButton("Start"));
p.add(gameCombo, BorderLayout.SOUTH);
f.add(p, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Go()::display);
}
}
关于java - swing中需要在不同屏幕之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36711574/