JButton expanding to take up entire frame/container

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?

Answers


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


Need Your Help

Display twig variable incude in php string in twig template

php symfony2 twig

I'm working on an apps with Symfony2 that create letters. The user write the contains. I want to give the user the possibility to insert dynamic variables from database such as the title, name from...

Create, populate and return 2D String array from native code (JNI/NDK)

java string multidimensional-array jni

I'm finding this particular bit of code quite difficult (Not least of which because I only started playing with C a week ago).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.