我正在尝试创建 Connect 4 游戏,如下图所示: 我已经能够创建一个包含 42 个按钮的网格布局,现在我需要添加“重置”按钮。我相信我需要将 2 个布局合并到一个框架中,但我不知道如何做到这一点,并且在任何地方都找不到任何答案。 感谢您的帮助和时间。
public class ApplicationRunner {
public static void main(String[] args) {
new ConnectFour();
}
}
import javax.swing.*;
import java.awt.*;
public class ConnectFour extends JFrame {
private String buttonLbl = "X";
HashMap<String, JButton> buttons;
public ConnectFour() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 600);
setTitle("Connect Four");
setLocationRelativeTo(null);
JButton resetButton = new JButton();
resetButton.setName("reset button");
resetButton.setText("Reset");
for (int i = 6; i > 0; i--) {
for (char c = 'A'; c <= 'G'; c++) {
String cell = "" + c + i;
JButton cellButton = new JButton(" ");
cellButton.setBackground(Color.LIGHT_GRAY);
cellButton.setName("Button" + cell);
add(cellButton);
}
}
GridLayout gl = new GridLayout(6, 7, 0, 0);
setLayout(gl);
setVisible(true);
}
}
一种解决方案是使用两个 JPanel 实例(每个实例都有自己的 LayoutManager)。
然后将这两个 JPanel 实例添加到 JFrame 中。
示例:
public class MyApplication extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyApplication app = new MyApplication();
app.setVisible(true);
}
});
}
private MyApplication() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 600);
setTitle("Connect Four");
setLocationRelativeTo(null);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
JButton resetButton = new JButton();
resetButton.setName("reset button");
resetButton.setText("Reset");
resetButton.setAlignmentX(Component.RIGHT_ALIGNMENT);
buttonPanel.add(resetButton);
// add buttonPanel to JFrame
add(buttonPanel, BorderLayout.SOUTH);
JPanel mainPanel = new JPanel(new GridLayout(6, 7, 0, 0));
for (int i = 6; i > 0; i--) {
for (char c = 'A'; c <= 'G'; c++) {
String cell = "" + c + i;
JButton cellButton = new JButton(" ");
cellButton.setBackground(Color.LIGHT_GRAY);
cellButton.setName("Button" + cell);
mainPanel.add(cellButton);
}
}
// add mainPanel to JFrame
add(mainPanel, BorderLayout.CENTER);
setVisible(true);
}
}