JButton expanding to take up entire frame/containe

2020-04-04 06:55发布

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?

3条回答
家丑人穷心不美
2楼-- · 2020-04-04 07:27

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

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

Your code should look like this now:

Before

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 );
    ....

}

Change it to something like this:

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);
    ....

}

Before/After

Before http://img372.imageshack.us/img372/2860/beforedl1.png After http://img508.imageshack.us/img508/341/aftergq7.png

查看更多
狗以群分
3楼-- · 2020-04-04 07:28

Again :)


    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);

        }
    }
查看更多
\"骚年 ilove
4楼-- · 2020-04-04 07:31

Or just use Absolute layout. It's on the Layouts Pallet.

Or enable it with :

frame = new JFrame();
... //your code here

// to set absolute layout.
frame.getContentPane().setLayout(null);

This way, you can freely place the control anywhere you like.

查看更多
登录 后发表回答