JPanel大小问题

时间:2013-04-26 09:41:19

标签: java swing jpanel

我已使用JPanel将两个JPanel添加到GridBagLayout。现在的问题是:

当主面板加载时,它显示上面板位在它应该是的实际位置上方,当来自db的数据加载到JTextfieldsJComboBox时,面板将变为其实际大小。

示例代码:

public class JPanelIssue extends JPanel {
    public JPanelIssue() {
    JPanel mainPanel = new JPanel(new GridBagLayout());
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    mainPanel.add(panel1, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.6, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
    mainPanel.add(panel2, new GridBagConstraints(0, 1, 1, GridBagConstraints.REMAINDER, 1.0, 0.4,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));

    add(mainPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
    }
}

panel1包含与搜索条件相关的字段,panel2包含JTable不相信的结果。

是否存在AWT事件队列问题或任何其他问题?

提前致谢。

1 个答案:

答案 0 :(得分:2)

仅评论

无法从此代码剪辑中重现,因为您忘记添加有关JTextfields and JComboBox then panel goes to its actual size.

的内容
  

当主面板加载时,显示上面的上面板位   它应该是实际的位置,当数据从db加载到   然后JTextfields和JComboBox面板达到它的实际大小。

GBC基于PreferredSize来自JComponents回到contianer(假设大约JPanel

有两种方式

  1. (proper)JTextFieldJComboBox设置了适当的PreferredSize

  2. (sizing hack)覆盖getPreferredSize JPanel包含JTextFieldJComboBox

  3. 然后所有其他父母/容器应该被通知,而不会覆盖任何setSizesetBoundssetPreferredSize,只有JFrame.pack()