1

我有一个创建 JButtons 的程序,然后将其添加到带有 BoxLayout 的 JPanel 中,该 BoxLayout 设置为垂直放置它们。有时第一个按钮会被有意从 JPanel 中删除。最初,按钮正确居中,按钮也成功删除。问题是剩下的按钮会分开来填充空间。这不是我想要的,相反,我希望它们沿 y 轴重新居中而不分开。

我有一个扩展 JPanel 的类。在构造函数中创建了 BoxLayout。

setPreferredSize(new Dimension(150, 500));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setAlignmentY(CENTER_ALIGNMENT);

创建按钮当前是此类中的一种方法:

createButtons(int numButtons){
for (int i=0;i<numButtons;i++) {
    add(new JButton());
}

而移除是另一种方法:

removeButton(){
    if(getComponentCount()>1){
        remove(0);
        validate();
        repaint();
    }
}

有谁知道如何使按钮保持沿 y 轴居中而不分散开来填充包含面板?

4

3 回答 3

1

您是否听说过 BoxLayouts 中的胶水,它使用不可见组件作为填充物(胶水),我认为这应该有助于保持按钮居中,请参阅以下 2 个链接:BoxLayout docsBoxLayout - Filler这个网站也有一些关于 Boxlayout 的很棒的教程用胶水:BoxLayout Glue这个

于 2012-07-02T13:08:12.480 回答
1

我不明白你的问题。也许我错过了一步,但在下面的代码片段中,所有组件都水平居中并在顶部对齐。每当移除一个组件时,下面的按钮就会自动堆叠在顶部。也许从这个片段开始向我们展示您的问题是什么:

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestButtons {

    protected void createAndShowGUI() {
        JFrame frame = new JFrame("Test buttons/BoxLayout");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createLineBorder(Color.RED));
        // panel.setPreferredSize(new Dimension(150, 500));
        BoxLayout mgr = new BoxLayout(panel, BoxLayout.Y_AXIS);
        panel.setLayout(mgr);
        for (int i = 0; i < 5; i++) {
            final JButton button = new JButton("Remove Hello World " + (i + 1));
            button.setAlignmentX(Component.CENTER_ALIGNMENT);
            button.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    panel.remove(button);
                    panel.revalidate();
                    panel.repaint();
                }
            });
            panel.add(button);
        }
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestButtons().createAndShowGUI();
            }
        });
    }

}
于 2012-07-02T14:09:50.297 回答
0

我认为这是使用 BOX Layout 的问题。这些按钮确实保持居中,但“填充”到它们添加到的窗格的边缘。我相信正确的方法(如果您知道要创建的按钮数量)是使用带有 setPreferedSize 方法的网格布局。

JButton btn = new JButton(String.valueOf(i));
btn.setPreferredSize(new Dimension(40, 40));
panel.add(btn);
于 2012-07-02T13:03:15.447 回答