我在GridBagLayout中有14个按钮。问题是按钮从屏幕中间垂直开始,而不是从开始屏幕开始。我想要的也是按钮大小相同,并在两者之间增加一些空间。
这是我的代码:
answer = bool(100 > number > 50)
答案 0 :(得分:1)
如果您希望按钮大小相同,请考虑使用GridLayout,其中一个构造函数可以在组件之间添加空间:
new GridLayout(0, 1, 0, 5); // variable number of rows, 1 column, 5 pixels between
如果绝对必须使用GridBagLayout,请将约束的fill属性设置为GridBagConstraints.HORIZONTAL
或GridBagConstraints.BOTH
,并将anchor属性设置为GridBagConstraints.WEST
有关创建一堆JButton的示例,请将它们放在屏幕左侧的网格中:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;
@SuppressWarnings("serial")
public class ButtonsOnSide extends JPanel {
private static final String[] BTN_TEXTS = {
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October","November", "December" };
private static final int PREF_W = 1000;
private static final int PREF_H = 800;
private static final int GAP = 4;
public ButtonsOnSide() {
JPanel btnPanel = new JPanel(new GridLayout(0, 1, 0, GAP));
for (String btnText : BTN_TEXTS) {
JButton btn = new JButton(btnText);
btn.addActionListener(e -> System.out.println(e.getActionCommand()));
btnPanel.add(btn);
}
// wrapper panel to help center the button panel vertically
JPanel wrapperPanel = new JPanel(new GridBagLayout());
wrapperPanel.add(btnPanel);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout());
add(wrapperPanel, BorderLayout.LINE_START); // add to the left side
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("ButtonsOnSide");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ButtonsOnSide());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}