繁体   English   中英

Jawa Swing 一帧多布局

[英]Jawa Swing multiple layouts in one frame

我正在尝试创建如下图所示的 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);
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM