Java Swing - JPanel 和 GridLayout 边距/填充

发布于 2024-10-05 18:01:09 字数 1750 浏览 0 评论 0原文

我正在用 Java 构建一个国际象棋游戏,目前在使用 Swing 获得完全符合我想要的 GUI 时遇到了一些麻烦。我正在使用 GridLayout 来组织 8x8 ChessButton 的网格(它覆盖 JButton 以便我可以在其中存储额外的信息)例如坐标)。最初,除非我将鼠标悬停在 ChessButton 上,否则它们不会出现,但我通过将每个 ChessButton 放置在单独的 JPanel 中并解决了该问题将每个按钮的 setPreferredSize() 设置为设定的高度和宽度。

现在,我的问题是每个按钮上方(和/或下方?)似乎有一个小边距或填充。我已经确保为 GridLayout 设置了 setHgap(0)setVgap(0),所以我很确定神秘的边距来自按钮或 JPanel。但是,我似乎无法摆脱它们,而且每当我将鼠标放在它们上时,它们似乎都会导致每个 ChessButton 向上/向下移动一点。

我意识到问题的描述可能有点难以可视化,因此我截取了屏幕截图(使用 JButton 而不是 ChessButton,因此间隙稍微容易一些识别): http://img3.imageshack.us/img3/6656/jbuttonmargins.png

这是我用来初始化每个 ChessButton 的代码:

    chessBoard = new JPanel(new GridLayout(8, 8, 0, 0));
    chessBoard.setBorder(BorderFactory.createEmptyBorder());

    for (int i = 0; i <= 65; i++) {
            //Create a new ChessButton
            ChessButton button = new ChessButton("hi");
            button.setBorder(BorderFactory.createEmptyBorder());
            button.setPreferredSize(new Dimension(75, 75));
            button.setMargin(new Insets(0, 0, 0, 0));

            //Create a new JPanel that the ChessButton will go into
            JPanel buttonPanel = new JPanel();
            buttonPanel.setPreferredSize(new Dimension(75, 75));
            buttonPanel.setBorder(BorderFactory.createEmptyBorder());
            buttonPanel.add(button);

            //Add the buttonPanel to the grid
            chessBoard.add(buttonPanel);
    }

那么,如何消除按钮之间的这些垂直空间呢?我对 Swing 比较陌生,所以如果答案非常明显,我很抱歉,但我会感谢任何人可能提供的任何帮助!提前致谢!

I'm working on building a chess game in Java, and I'm currently having a bit of trouble getting the GUI exactly the way I want it with Swing. I'm using a GridLayout to organize a grid of 8x8 ChessButtons (which override the JButton so that I can store extra information inside of them such as coordinates). Originally, the ChessButtons wouldn't appear unless I moused over them, but I solved that problem by placing each ChessButton inside a separate JPanel and setting each button's setPreferredSize() to a set height and width.

Now, my problem is that there seems to be a small margin or padding above (and/or below?) each button. I've made sure to set setHgap(0) and setVgap(0) for the GridLayout, so I'm pretty sure the mysterious margin is coming from either the buttons or the JPanels. But, I can't seem to get rid of them, and they seem to be causing each ChessButton to shift a little bit up/down whenever I mouse of them.

I realize this description of the problem might be a little hard to visualize, so I've taken a screenshot (using JButtons rather than ChessButtons so the gaps are slightly easier to recognize): http://img3.imageshack.us/img3/6656/jbuttonmargins.png

Here is the code I used to initialize each ChessButton:

    chessBoard = new JPanel(new GridLayout(8, 8, 0, 0));
    chessBoard.setBorder(BorderFactory.createEmptyBorder());

    for (int i = 0; i <= 65; i++) {
            //Create a new ChessButton
            ChessButton button = new ChessButton("hi");
            button.setBorder(BorderFactory.createEmptyBorder());
            button.setPreferredSize(new Dimension(75, 75));
            button.setMargin(new Insets(0, 0, 0, 0));

            //Create a new JPanel that the ChessButton will go into
            JPanel buttonPanel = new JPanel();
            buttonPanel.setPreferredSize(new Dimension(75, 75));
            buttonPanel.setBorder(BorderFactory.createEmptyBorder());
            buttonPanel.add(button);

            //Add the buttonPanel to the grid
            chessBoard.add(buttonPanel);
    }

So, how can I get rid of these vertical spaces between buttons? I'm relatively new to Swing, so I'm sorry if the answer is extremely obvious, but I'd appreciate any help anyone might have to offer! Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

耳钉梦 2024-10-12 18:01:10

尝试添加 chessBoard.setPreferredSize(600, 600) 为棋盘创建一个 JPanel,该棋盘只有空间容纳按钮(每路 8 个按钮 * 按钮上每路 75 个尺寸)。

Try adding chessBoard.setPreferredSize(600, 600) to create a JPanel for the board that only has room to fit the buttons (8 buttons each way * 75 size each way on the buttons).

小苏打饼 2024-10-12 18:01:09

不要添加空边框;请使用 setBorderPainted(假)

附录:正如 @camickr 所指出的,面板的布局可能包括默认间隙。下面的示例相应地使用了无间隙 GridLayout

替代文本

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see http://stackoverflow.com/questions/4331699 */
public class ButtonBorder extends JPanel {

    private static final int N = 8;
    private static final int SIZE = 75;

    public ButtonBorder() {
        super(new GridLayout(N, N));
        this.setPreferredSize(new Dimension(N * SIZE, N * SIZE));
        for (int i = 0; i < N * N; i++) {
            this.add(new ChessButton(i));
        }
    }

    private static class ChessButton extends JButton {

        public ChessButton(int i) {
            super(i / N + "," + i % N);
            this.setOpaque(true);
            this.setBorderPainted(false);
            if ((i / N + i % N) % 2 == 1) {
                this.setBackground(Color.gray);
            }
        }
    }

    private void display() {
        JFrame f = new JFrame("ButtonBorder");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ButtonBorder().display();
            }
        });
    }
}

Don't add an empty border; do use setBorderPainted(false).

Addendum: As @camickr notes, the panel's layout may include default gaps. The example below uses no-gap GridLayout accordingly.

alt text

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see http://stackoverflow.com/questions/4331699 */
public class ButtonBorder extends JPanel {

    private static final int N = 8;
    private static final int SIZE = 75;

    public ButtonBorder() {
        super(new GridLayout(N, N));
        this.setPreferredSize(new Dimension(N * SIZE, N * SIZE));
        for (int i = 0; i < N * N; i++) {
            this.add(new ChessButton(i));
        }
    }

    private static class ChessButton extends JButton {

        public ChessButton(int i) {
            super(i / N + "," + i % N);
            this.setOpaque(true);
            this.setBorderPainted(false);
            if ((i / N + i % N) % 2 == 1) {
                this.setBackground(Color.gray);
            }
        }
    }

    private void display() {
        JFrame f = new JFrame("ButtonBorder");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ButtonBorder().display();
            }
        });
    }
}
风吹短裙飘 2024-10-12 18:01:09

最初,除非我将鼠标悬停在 ChessButton 上,否则它们不会出现,但我通过将每个 ChessButton 放置在单独的 JPanel 中并将每个按钮的 setPreferredSize() 设置为设定的高度和宽度来解决该问题

,这不是正确的解决方案。没有理由使用 JPanel 来控制按钮。事实上,这很可能就是问题的原因。当您将按钮添加到 GridLayout 时,它们应该会显示。如果它们没有显示,可能是因为您在使 GUI 可见后将按钮添加到 GUI 中。组件应在 GUI 可见之前添加到 GUI 中。

现在,我的问题是每个按钮上方(和/或下方?)似乎有一个小边距或填充

我不明白为什么也没有水平间隙。当您创建 JPanel 时,默认情况下它使用 FlowLayout,其中还包含 5 像素的水平/垂直间隙。所以我明白为什么垂直间隙可能为 10 像素。我不明白为什么没有水平间隙。

如果您需要更多帮助,请发布您的 SSCCE 来演示问题。 SSCCE 应该使用常规 JButton。在开始使用自定义组件之前,请先了解使用标准组件的基础知识。这样您就知道问题是否出在您的自定义代码上。

Originally, the ChessButtons wouldn't appear unless I moused over them, but I solved that problem by placing each ChessButton inside a separate JPanel and setting each button's setPreferredSize() to a set height and width

That is not the proper solution. There is no reason to use a JPanel to hold the buttons. In fact, this is probably the cause of the problem. The buttons should show up when you add them to a GridLayout. If they don't show up its probably because you added the buttons to the GUI after making the GUI visible. Components should be added to the GUI BEFORE it is made visible.

Now, my problem is that there seems to be a small margin or padding above (and/or below?) each button

I don't understand why there also isn't a horizontal gap. When you create a JPanel, by default it uses a FlowLayout which also contains a horizontal/vertical gap of 5 pixels. So I understand why you might have the vertical gap of 10 pixels. I don't understand why there is no horizontal gap.

If you need more help post your SSCCE demonstrating the problem. And the SSCCE should use regular JButtons. Get the basics working with standard components before you start playing with custom components. That way you know if the problem is with your custom code or not.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文