JButton扩展到占据整个框架/容器

嘿大家。 我正在尝试使用按钮和标签制作一个swing GUI。 即时通讯使用边框布局和标签(在北方字段中)显示正常,但按钮占据框架的其余部分(它在中心字段中)。 任何想法如何解决这个问题?

您必须将按钮添加到另一个面板,然后将该面板添加到框架。

事实certificate,BorderLayout扩展了组件中间的东西

您的代码现在应该如下所示:

之前

public static void main( String [] args ) { JLabel label = new JLabel("Some info"); JButton button = new JButton("Ok"); JFrame frame = ... frame.add( label, BorderLayout.NORTH ); frame.add( button , BorderLayout.CENTER ); .... } 

将其更改为以下内容:

 public static void main( String [] args ) { JLabel label = new JLabel("Some info"); JButton button = new JButton("Ok"); JPanel panel = new JPanel(); panel.add( button ); JFrame frame = ... frame.add( label, BorderLayout.NORTH ); frame.add( panel , BorderLayout.CENTER); .... } 

前/后

之前http://img372.imageshack.us/img372/2860/beforedl1.png 之后http://img508.imageshack.us/img508/341/aftergq7.png

或者只使用绝对布局。 它位于Layouts托盘上。

或者启用它:

 frame = new JFrame(); ... //your code here // to set absolute layout. frame.getContentPane().setLayout(null); 

这样,您可以随意将控件放在任何您喜欢的位置。

再次:)

 import javax.swing.*; public class TestFrame extends JFrame { public TestFrame() { JLabel label = new JLabel("Some info"); JButton button = new JButton("Ok"); Box b = new Box(BoxLayout.Y_AXIS); b.add(label); b.add(button); getContentPane().add(b); } public static void main(String[] args) { JFrame f = new TestFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLocationRelativeTo(null); f.setVisible(true); } }