我有GridBagLayout,我在其中添加 JLabel
, JTextfield
和两个 JButtons
和图像,图像为25x25像素 . 每当我显示或隐藏按钮时,整个布局都会移动 . 我试着 setSize()
, setMinimumSize()
, setPreferredSize()
和 setMaximumSize()
但它只会忽略调整 JLabel
和 JTextField
的大小 . 如何为这两个组件设置修复大小,或者只是使GridBagLayout中的所有单元格大小相同 .
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;
panel.add(new JLabel("Auftrag Nummer:"), c);
JTextField orderNumberField = new JTextField();
c.gridx = 1;
c.gridy = 0;
panel.add(orderNumberField, c);
JButton searchButton = DefaultLayouts.imageButton("SEARCH");
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(10, 0, 0, 0);
panel.add(searchButton, c);
JButton checkButton = DefaultLayouts.imageButton("CHECK");
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(10, 0, 0, 0);
panel.add(checkButton, c);
DefautlLayouts.imageButton
获取路径和工具提示并设置一些默认值
public static JButton imageButton(String propertiesName) {
JButton button = DefaultLayouts.button();
button.setIcon(new ImageIcon(imagesProperties.getProperty(propertiesName + "_PATH")));
button.setToolTipText(imagesProperties.getProperty(propertiesName + "_TOOLTIP"));
button.setContentAreaFilled(false);
button.setFocusPainted(false);
button.setBorder(BorderFactory.createEmptyBorder());
return button;
}
3 回答
你有一个选择是,你可以用一个具有恒定大小的JPanel封装buttton,然后如果你隐藏按钮,JPanel仍然会在那里占据空间 .
除了在具有指定尺寸的JPanel上设置要保持静态尺寸的组件外,如果布局是框架上的主要尺寸,请尝试使用
frame.setResizable(false);
.我用一个25x25像素的空png解决了这个问题,它与显示和隐藏的按钮处于同一位置 .
将来会通过更好的解决方案对此进行更新 .
Edit
我用DesigneGridLayout来解决这个问题 .