【问题标题】:In Java, is there a way to center a group of buttons with variable size(Using Swing)?在 Java 中,有没有办法让一组可变大小的按钮居中(使用 Swing)?
【发布时间】:2017-07-20 11:35:01
【问题描述】:

我一直在尝试制作这样的 GUI:

但是,我遇到的困难是我需要使按钮的文本可变——每个按钮应该呈现一个不同的选项,该选项的文本长度可能会有所不同。虽然这本身并不困难,但我已经尝试了无数不同的东西,但我无法让按钮居中,尽管它们的文本长度。无论我尝试什么,我总是遇到以下问题之一:

  • 按钮不居中(左侧有空间,但超出了右侧的窗口)
  • 由于某种原因,Question 和 Goodratio 会根据按钮大小改变位置

我不知道该怎么做。有没有人对什么是最好的方法有一些有用的直觉?将不胜感激。

编辑:构造函数的代码(未正确居中),我用它来设置组件,按要求:

    public ButtonPannel(Test test)
{
    super();

    op1Button = new JButton("Option 1");
    op2Button = new JButton("Option 2");
    op3Button = new JButton("Option 3");
    questionText = new JLabel("Question");
    rightAndWrongAmount = new JLabel("rightAndWrongAmount");

    GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[]{30, 331, 0};
    gridBagLayout.rowHeights = new int[]{16, 0, 134, 35, 16, 0};
    gridBagLayout.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
    gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0, 0.0, 0.0, Double.MIN_VALUE};
    setLayout(gridBagLayout);

    JPanel panel = new JPanel();
    FlowLayout flowLayout = (FlowLayout) panel.getLayout();

    op1Button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        }
    });

    GridBagConstraints gbc_lblQuestion = new GridBagConstraints();
    gbc_lblQuestion.insets = new Insets(0, 0, 5, 0);
    gbc_lblQuestion.gridx = 1;
    gbc_lblQuestion.gridy = 1;
    add(questionText, gbc_lblQuestion);
    panel.add(op1Button);

    panel.add(op2Button);

    panel.add(op3Button);
    GridBagConstraints gbc_panel = new GridBagConstraints();
    gbc_panel.insets = new Insets(0, 0, 5, 0);
    gbc_panel.gridx = 1;
    gbc_panel.gridy = 3;
    add(panel, gbc_panel);

    GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
    gbc_lblNewLabel_1.gridx = 1;
    gbc_lblNewLabel_1.gridy = 4;

    add(rightAndWrongAmount, gbc_lblNewLabel_1);

    op1Button.addActionListener(new InputHandler(test));
    op1Button.setActionCommand("1");
    op2Button.addActionListener(new InputHandler(test));
    op2Button.setActionCommand("2");
    op3Button.addActionListener(new InputHandler(test));
    op3Button.setActionCommand("3");

}

代码是使用 WindowBuilder 生成的。问题不在于代码,而在于使用哪个 Layout 等。

【问题讨论】:

  • Java 有 大量 的布局管理器;并且肯定有一个支持这样的设置。所以,只需学习相应的教程;当你有一些“几乎”做的事情的真实代码时;随时询问。所以,先到这里docs.oracle.com/javase/tutorial/uiswing/layout/using.htmldocs.oracle.com/javase/tutorial/uiswing/layout/visual.html 来确定哪个经理适合你。
  • @GhostCat 根据要求,添加了代码。把代码放在前面是因为我对执行它所需的工具比对它的实际实现更感兴趣。
  • 好多了;但试着把它变成minimal reproducible example——这样其他人就可以轻松运行了。
  • 按钮的大小应该相等吗?我认为如果它们是(并且在布局和代码上有所不同),它看起来会更“平衡”。

标签: java swing user-interface button layout


【解决方案1】:

布局有点黑魔法和反复试验。单一布局很少能完全达到您想要的效果,因此您经常需要借助复合布局(使用多个容器和布局)来获得您想要的......

所以,基本上,这是由一个面板组成,另一个面板持有按钮(另一个面板充当“伪”内容以增加空间)

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            add(new JLabel("Question"), gbc);
            gbc.fill = GridBagConstraints.BOTH;
            gbc.weightx = 1;
            gbc.weighty = 1;
            // This is just to act as some psudo context
            add(new FillerPane(), gbc);
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            gbc.weighty = 0;
            add(makeButtonPane(), gbc);
            add(new JLabel("Goodratio"), gbc);
        }

        public JPanel makeButtonPane() { 
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1;
            panel.add(new JButton("Short"));
            panel.add(new JButton("Long, long, long and lobng"));
            panel.add(new JButton("In the middle"));
            return panel;
        }

    }

    public class FillerPane extends JPanel {

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}

“但我希望按钮大小相同”我听到你问,当然,改变布局......

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            add(new JLabel("Question"), gbc);
            gbc.fill = GridBagConstraints.BOTH;
            gbc.weightx = 1;
            gbc.weighty = 1;
            // This is just to act as some psudo context
            add(new FillerPane(), gbc);
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            gbc.weighty = 0;
            add(makeButtonPane(), gbc);
            add(new JLabel("Goodratio"), gbc);
        }

        public JPanel makeButtonPane() { 
            JPanel panel = new JPanel(new GridLayout(1, 0));
            panel.add(new JButton("Short"));
            panel.add(new JButton("Long, long, long and lobng"));
            panel.add(new JButton("In the middle"));
            return panel;
        }

    }

    public class FillerPane extends JPanel {

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}

您必须查看布局并考虑每个元素与其他元素的关系,根据您希望它们做什么,然后找到将帮助您实现最终结果的布局管理器并将它们组合在一起

【讨论】:

  • 我:“按钮应该大小相等吗?..” 噗……炫耀!
  • @AndrewThompson 每个人对这个主题都有不同的感受,我敢肯定我已经与设计师和其他开发人员就此类事情展开了一些战争;)
  • 你试过WindowBuilder吗?我总是喜欢使用它,因为它让一切变得更容易(布局明智)
  • @lilienfa 我尝试了许多表单构建器,并且倾向于发现手动构建它的 UI 最终更容易,并且整体上会产生更好/更清晰的结果。我鼓励我所有的初级开发人员学习手工编写他们的 UI,因为它可以让您更好地理解布局如何工作以及如何将需求分解为独立的工作单元,这有助于减少耦合并简化所有解决方案和工作流动。一旦你知道如何手工完成,那么公司编辑器就会成为一种工具,可以使初始过程更快
  • @MadProgrammer 我喜欢你的方法,这是真的:) 只是认为使用它会更容易(?):) 不知道它是否更容易......但是会更快
猜你喜欢
  • 1970-01-01
  • 2022-01-18
  • 2021-09-16
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 2023-04-10
  • 1970-01-01
相关资源
最近更新 更多