首页 文章

使用JTextField和JButton的GridbagLayout,在JButton可见时重新格式化

提问于
浏览
0

我有GridBagLayout,我在其中添加 JLabelJTextfield 和两个 JButtons 和图像,图像为25x25像素 . 每当我显示或隐藏按钮时,整个布局都会移动 . 我试着 setSize()setMinimumSize()setPreferredSize()setMaximumSize() 但它只会忽略调整 JLabelJTextField 的大小 . 如何为这两个组件设置修复大小,或者只是使GridBagLayout中的所有单元格大小相同 .

Demo

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 回答

  • 1

    你有一个选择是,你可以用一个具有恒定大小的JPanel封装buttton,然后如果你隐藏按钮,JPanel仍然会在那里占据空间 .

  • 0

    除了在具有指定尺寸的JPanel上设置要保持静态尺寸的组件外,如果布局是框架上的主要尺寸,请尝试使用 frame.setResizable(false); .

  • 0

    我用一个25x25像素的空png解决了这个问题,它与显示和隐藏的按钮处于同一位置 .

    将来会通过更好的解决方案对此进行更新 .

    Edit

    我用DesigneGridLayout来解决这个问题 .

    JPanel panel = DefaultLayouts.panel();
    DesignGridLayout layout = new DesignGridLayout(panel);
    
    JTextField orderNumberField = new JTextField();
    JButton searchButton = DefaultLayouts.imageButton("SEARCH");
    JButton checkButton = DefaultLayouts.imageButton("CHECK");
    
    layout.row().grid().add(new JLabel("Auftrag Nummer:")).add(orderNumberField);
    layout.emptyRow();
    layout.row().grid().add(searchButton).add(checkButton);
    

相关问题