【发布时间】: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.html 或docs.oracle.com/javase/tutorial/uiswing/layout/visual.html 来确定哪个经理适合你。
-
@GhostCat 根据要求,添加了代码。把代码放在前面是因为我对执行它所需的工具比对它的实际实现更感兴趣。
-
好多了;但试着把它变成minimal reproducible example——这样其他人就可以轻松运行了。
-
按钮的大小应该相等吗?我认为如果它们是(并且在布局和代码上有所不同),它看起来会更“平衡”。
标签: java swing user-interface button layout