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

2022-01-24 00:00:00 user-interface java swing jbutton jframe

大家好.我正在尝试制作一个带有按钮和标签的摇摆 GUI.我使用边框布局,标签(在北场)显示得很好,但按钮占据了框架的其余部分(它在中心场).知道如何解决这个问题吗?

Hey everyone. I'm trying to make a swing GUI with a button and a label on it. im using a border layout and the label ( in the north field ) shows up fine, but the button takes up the rest of the frame (it's in the center field). any idea how to fix this?

推荐答案

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

You have to add the button to another panel, and then add that panel to the frame.

原来 BorderLayout 扩展了中间的组件

It turns out the BorderLayout expands what ever component is in the middle

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

Your code should look like this now:

之前

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之后

相关文章