java - 如何使用 Swing 创建自定义面板布局?

标签 java swing layout-manager

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;

public class BattleShipsMain {
    public static void main(String[] args) {

        // JButton arrays to hold buttons
        JButton[] userButtons = new JButton[100];
        JButton[] compButtons = new JButton[100];

        // Text for ships label
        String shipsText = "Ships      Size (Squares)" + "Carrier          5"
                + "Battleship       4" + "Destroyer        3"
                + "Patrol Boat      2";

        // Draw main window and set layout
        JFrame window = new JFrame("Battle Ships");
        window.setSize(1200, 1900);
        window.getContentPane().setLayout(new BorderLayout());
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Draw top game panel
        JPanel gridPanTop = new JPanel();
        gridPanTop.setLayout(new BorderLayout());
        gridPanTop.setPreferredSize(new Dimension(1300, 400));
        gridPanTop.setBackground(Color.GRAY);

        // Top panel text
        JLabel ships = new JLabel();
        ships.setText(shipsText);

        // Bottom panel buttons
        JButton submit = new JButton("Submit");
        Dimension submitSize = new Dimension(20, 20);
        submit.setSize(submitSize);

        // Draw bottom game panel
        JPanel panBottom = new JPanel();
        panBottom.setBackground(Color.WHITE);
        panBottom.setLayout(new BorderLayout());
        panBottom.setPreferredSize(new Dimension(200, 200));
        panBottom.add(submit);

        // Set position of game panels
        window.getContentPane().add(gridPanTop, BorderLayout.PAGE_START);
        window.getContentPane().add(panBottom, BorderLayout.CENTER);

        // Set border for grid buttons
        Border border = new LineBorder(Color.gray);

        // Draw panel for grids
        JPanel user = new JPanel();
        JPanel comp = new JPanel();
        user.setBackground(Color.gray);
        comp.setBackground(Color.gray);
        user.setBorder(border);
        comp.setBorder(border);

        // Set layout for grid panels
        user.setLayout(new GridLayout(10, 10));
        comp.setLayout(new GridLayout(10, 10));

        int x = userButtons.length;

        // Set user buttons as JButtons, set size and add to grid
        for (int i = 0; i < x; i++) {
            userButtons[i] = new JButton();
            userButtons[i].setPreferredSize(new Dimension(40, 40));
            user.add(userButtons[i]);
        }

        // Set computer buttons as JButtons, set size and add to grid
        for (int i = 0; i < x; i++) {
            compButtons[i] = new JButton();
            compButtons[i].setPreferredSize(new Dimension(40, 40));
            comp.add(compButtons[i]);
        }

        // Add panels to main frame and set visible
        window.pack();
        window.add(gridPanTop);
        window.add(panBottom);
        gridPanTop.add(user, BorderLayout.WEST);
        gridPanTop.add(comp, BorderLayout.EAST);
        gridPanTop.setVisible(true);
        panBottom.setVisible(true);
        window.setVisible(true);
        user.setVisible(true);
        comp.setVisible(true);

        // Start main game
        MainGame start = new MainGame();

    }
}

我有一项作业,但在 Java Swing 中创建以下面板布局时遇到了很多麻烦。我没有运气使用任何布局。

有人可以帮助我完成这个布局吗?

目前代码显示以下输出:

output of the above

你可能会看出我是一个初学者,所以请原谅菜鸟错误。我目前拥有的面板布局看起来像我附加的理想布局,但显然不是我想要的正确布局。

最佳答案

您可以使用不同的布局和复合布局(使用子面板)来实现此目的。我会使用 GridBagLayout ,这绝对是最通用的布局之一。

示例代码

public class TestLayout extends JFrame {

    private static final long serialVersionUID = -7619921429181915663L;

    public TestLayout(){
        super("TestLayout");
        super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        init();
    }

    private void init() {
        this.getContentPane().setLayout(new GridBagLayout());

        //Setup some test panel with labels
        JPanel panel1 = new JPanel(new BorderLayout());
        panel1.setBorder(BorderFactory.createEtchedBorder());
        JLabel label1 =  new JLabel("Panel 1");
        label1.setHorizontalAlignment(SwingConstants.CENTER);
        panel1.add(label1,BorderLayout.CENTER);

        JPanel panel2 = new JPanel(new BorderLayout());
        panel2.setBorder(BorderFactory.createEtchedBorder());
        JLabel label2 =  new JLabel("Panel 2");
        label2.setHorizontalAlignment(SwingConstants.CENTER);
        panel2.add(label2,BorderLayout.CENTER);

        JPanel panel3 = new JPanel(new BorderLayout());
        panel3.setBorder(BorderFactory.createEtchedBorder());
        JLabel label3 =  new JLabel("Panel 3");
        label3.setHorizontalAlignment(SwingConstants.CENTER);
        panel3.add(label3,BorderLayout.CENTER);

        JPanel panel4 = new JPanel(new BorderLayout());
        panel4.setBorder(BorderFactory.createEtchedBorder());
        JLabel label4 =  new JLabel("Panel 4");
        label4.setHorizontalAlignment(SwingConstants.CENTER);
        panel4.add(label4,BorderLayout.CENTER);

        //Here goes the interesting code
        this.getContentPane().add(panel1,  new GridBagConstraints(0, 0, 1, 1, 1.0, 0.6, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(2, 2,
                2, 2), 0, 0));
        this.getContentPane().add(panel2,  new GridBagConstraints(1, 0, 1, 1, 1.0, 0.6, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(2, 2,
                2, 2), 0, 0));
        this.getContentPane().add(panel3,  new GridBagConstraints(2, 0, 1, 1, 1.0, 0.6, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(2, 2,
                2, 2), 0, 0));
        //next row
        this.getContentPane().add(panel4,  new GridBagConstraints(0, 1, 3, 1, 1.0, 0.4, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(2, 2,
                2, 2), 0, 0));

        this.setPreferredSize(new Dimension(400, 200));
        this.pack();
    }

    public static void main(String[] args) {
        TestLayout frame = new TestLayout();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

生成的输出

Output

GridBagLayout 的关键部分是 GridBagConstraints

new GridBagConstraints(columnNumber, rowNumber, columnSpan, rowSpan, columnWeigth, rowWeigth, alignment, fillType, insets, padX, pady)

在示例中查看如何将第一行的 rowWeigth 设置为 0.6,将第二行设置为 0.4,以便第一行占用更多空间(60%)。根据需要调整它们(如果您喜欢相同的空间,只需将两者设置为 0.5)。

关于java - 如何使用 Swing 创建自定义面板布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35698645/

相关文章:

java - Swing框架中适合加载大文件的组件是什么

java - swing - 如何设置为选项卡式 Pane 分配选项卡按钮?

java - CardLayout 使用 JMenu 发送错误信息

java - 将两个面板彼此相邻对齐

java - 对齐 GridBagLayout 单元格

java - 如何在 java 方法 atZone(Zone_ID) 中定义 IST 区域 ID;

java - 通过Java读取excel文件

java - 列出所有可用的 ResourceBundle 文件

java - 为二维数组创建 hashMap

java - JLabel 不显示另一个类的值