Kahn Kah
Kahn Kah

Reputation: 1453

BorderLayout in Swing Java not working correctly

I have created a password generator in Java which works perfectly. My functionality is working (after a lot of tears, sweat and blood :) ), but the only problem that remains is the layout of my GUI.

My approach was the following:

This is the result

enter image description here

as you can see this is not how I wanted it. But if I look at my code, it should be placed nicely from top to bottom.

Where did it go wrong?

My code:

The constructor (extends from JFrame)

public PasswordGenerator(){
    this.setContentPane(ContentPane());
    this.setSize(500,270);
    this.setResizable(true);
    this.setVisible(true);
}

The panes:

private JPanel ContentPane()
{
    JPanel ContentPane = new JPanel();
    ContentPane.add(getTopPane(), BorderLayout.NORTH);
    ContentPane.add(getCenterPane(),BorderLayout.CENTER);
    ContentPane.add(getSouthPane(),BorderLayout.EAST);
    return ContentPane;
}

private JPanel getTopPane(){
    JPanel TopPane = new JPanel();
    JLabel intro = new JLabel("Password generator V1.0");
    intro.setFont(new Font("TimesRoman",Font.BOLD,20));
    TopPane.setLayout(new GridLayout(1,1));
    TopPane.add(intro);
    return TopPane;
}

private JPanel getCenterPane(){
    JPanel CenterPane = new JPanel();

    CenterPane.add(aantalChars);
    CenterPane.setLayout(new GridLayout(6,3));
    //8,2
    hidden.setVisible(false);
    hiddenL.setVisible(false);
    CenterPane.add(aantalCharsLabel);
    CenterPane.add(hidden);
    CenterPane.add(hidden);
    CenterPane.add(hiddenL);
    CenterPane.add(lowerCase);
    CenterPane.add(lowerCaseLabel);
    CenterPane.add(upperCase);
    CenterPane.add(upperCaseLabel);
    CenterPane.add(numberCase);
    CenterPane.add(numberCaseLabel);
    CenterPane.add(symbolCase);
    CenterPane.add(symbolCaseLabel);


    return CenterPane;
}

Upvotes: 0

Views: 201

Answers (2)

c0der
c0der

Reputation: 18792

The default layout manager for JPanel is FlowLayout manager. To use BorederLayout you need to set it specifically :

private JPanel ContentPane()
        {
            JPanel ContentPane = new JPanel();
            //////////////////////////////////////////////
            ContentPane.setLayout(new BorderLayout());
            ////////////////////////////////////////////
            ContentPane.add(getTopPane(), BorderLayout.NORTH);
            ContentPane.add(getCenterPane(),BorderLayout.CENTER);
            ContentPane.add(getSouthPane(),BorderLayout.SOUTH);
            return ContentPane;
        }

Upvotes: 2

Vampire
Vampire

Reputation: 38639

You forgot to set the BorderLayout as LayoutManager on your ContentPane. Just using the right constraints is not enough. You can use ContentPane.setLayoutManager() for this, or you can give the LayoutManager directly in the constructor of JPanel.

Upvotes: 3

Related Questions