簡體   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