【发布时间】:2012-02-10 13:39:41
【问题描述】:
我想要以下布局:
(即jbutton和jlabel放在jpanel上,jbutton居中,jlabel紧随其后。布局应该能够调整大小。编辑:在调整大小期间jbutton和jlabel的大小是恒定的。)
我想到了以下几点:
-
使用适当的布局管理器。我一个都不认识。我可以将 jbutton 和 jlabel 添加到另一个 jpanel 并将这个新 jpanel 添加到大 jpanel 的中心,但在这种情况下 jbutton 不会居中。
编辑:我尝试使用this proposal:(提案已编辑,现在代码正确)
公共类 MainFrame 扩展 JFrame { 公共静态无效主要(字符串[]参数){ 新的 MainFrame(); }
} }public MainFrame() { setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; add(new JPanel(), c); c.gridx = 1; c.weightx = 0; c.anchor = GridBagConstraints.CENTER; add(new JButton("Button"), c); c.gridx = 2; c.weightx = 1; c.anchor = GridBagConstraints.WEST; add(new JLabel("Label"), c); pack(); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE);但它会在按钮不居中的地方产生以下输出:
-
将 jbutton 和 jlabel 添加到 jpanel。将
ComponentListener添加到 jpanel 并覆盖componentResized那里。被覆盖的方法看起来像:public void componentResized(ComponentEvent e) { int x = button.getX() + button.getWidth() + 3; int y = button.getY(); label.setLocation(new Point(x, y)); }布局管理器自动调整大小时将选择JButton的位置,并通过此方法选择jlabel的位置。但是
componentResized只有在调整大小完成后才会被调用。因此,在调整 jlabel 大小的过程中,布局管理器将定义不需要的位置。 - 将 jbutton 添加到内容窗格并将 jlabel 添加到玻璃窗格。但是我在调整大小时会遇到与前一种情况相同的问题。
我怎样才能实现这种布局?
【问题讨论】: