Tag: absolutelayout

使用BoxLayout动态增长JPanel(在空布局上)

我有一个JPanel,在JPanel的顶部有一个垂直BoxLayout,其布局为null。 我希望带有BoxLayout的JPanel随着组件的添加而增长。 看到这段代码: public static void main (String[] args) { JFrame f = new JFrame(); f.setSize(500,500); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel total = new JPanel(); total.setLayout(null); total.setSize(f.getWidth(),f.getHeight()); total.setBackground(Color.green); JPanel box = new JPanel(); box.setLocation(100,200); box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS)); box.add(new JButton(“test”)); box.add(new JLabel(“hey”)); total.add(box); f.add(total); f.setVisible(true); } 您会注意到没有任何组件出现。 如何添加更多组件(垂直添加)时,如何使JPanel“框”大小动态增加。 提前:我需要“box”的位置正好是100,200所以请不要建议我不使用null布局。 我必须使用null布局。 “total”的null布局不应影响我的问题的答案,该问题集中在“box”面板上。