【发布时间】:2012-12-26 17:38:30
【问题描述】:
我在具有空布局的 JPanel 顶部有一个带有垂直 BoxLayout 的 JPanel。
我希望带有 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 “盒子”随着我添加更多组件(垂直添加)而动态增加。
提前:我需要“框”的位置正好在 100,200,所以请不要建议我不要使用空布局。我必须使用空布局。 “total”的空布局不应该影响我的问题的答案,它侧重于“box”面板。
【问题讨论】:
-
添加组件时会发生什么?我认为在某些事件中您需要添加组件和 repaint()。
-
您发布的代码不可运行。没有主要方法。
-
那是main方法的代码……把它扔到main方法里就行了。 (好像我需要告诉你……)
-
因为您选择丢弃 (恕我直言) Swing 必须提供的最强大的 API 资产之一,您未能履行它负责的工作......设置子组件的大小。
-
一个简单的 LayoutManager 接管 sizing 同时让您控制 locating 是Rob's DragLayout
标签: java swing jpanel absolutelayout boxlayout