如何使用动态大小将JPanel居中 [英] How to center JPanel with dynamic size

查看:178
本文介绍了如何使用动态大小将JPanel居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要展示棋盘.我有一个扩展JPanel的BoardPanel类和一个包含BoardPanel的GamePanel(也扩展了JPanel)类. GamePanel填充了所有应用程序框架.

I need to display chessboard. I have a BoardPanel class which extends JPanel and a GamePanel (also extending JPanel) class containing BoardPanel. GamePanel fills all the application frame.

我希望BoardPanel始终是一个正方形,其大小等于GamePanel的宽度和高度的最小值(如果GamePanel的宽度大于高度,则左右应留有空白,如果较小,则应留有空白顶部和底部).将BoardPanel显示在父面板的中心也很重要.

I want BoardPanel to always be a square with size equal to the minimum of GamePanel's width and height (if GamePanel's width is greater than height there should be empty space on the left and right, if it's smaller there should be empty space on top and bottom). It's also important that BoardPanel should be displayed in the center of parent panel.

我这样写:

public GamePanel() {
    setLayout(new BorderLayout(0, 0));
    boardPanel = new BoardPanel(...);
    this.add(boardPanel, BorderLayout.CENTER);
    ...
}

和在BoardPanel中:

and in BoardPanel:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    int size = Math.min(this.getParent().getHeight(), this.getParent().getWidth());
    this.setSize(size, size);
    ...
}

它的大小可以调整,但是棋盘总是显示在GamePanel的左上角(所有空白区域显示在bot或右边),我不知道如何解决.

It resizes well, but chessboard is always displayed in top left corner of GamePanel (all the empty space is displayed on bot or right) and I don't know how to fix it.

有帮助吗?预先感谢!

推荐答案

使用GridBagLayout将其居中.

import java.awt.*;
import javax.swing.*;

public class CenteredPanel {

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JPanel gui = new JPanel(new GridBagLayout());
                JPanel square = new SquarePanel();
                square.setBackground(Color.RED);
                gui.add(square);

                JFrame f = new JFrame("SquareBoard");
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);
                f.add(gui);
                f.setMinimumSize(new Dimension(400,100));
                f.pack();
                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

class SquarePanel extends JPanel {
    @Override
    public Dimension getPreferredSize() {
        Container c = this.getParent();
        int size = Math.min(c.getHeight(), c.getWidth());
        Dimension d = new Dimension(size,size);
        return d;
    }
}

这篇关于如何使用动态大小将JPanel居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆