G S
G S

Reputation: 7

Adding JComponents to JPanel and add the JPanel to JFrame is not working

I have a JFrame and I want to add a JPanel with a JButton. But all the guides in the internet seem to be wrong. If I follow these instructions my buttons will not be shown.

I know that there are questions similar to mine, but these posts have too much code instead of the problem in an isolated code. So I cannot figure out from it what their solution is.

public class MainClass {
    public static void main (String[]args) {
        Frame frame = new Frame();
    } 
}

public class Frame extends JFrame {

    private JButton btn;
    private JPanel pnl = new JPanel();

    Frame () {
        setSize(400,400);
        setLayout(new FlowLayout());
        setVisible(true);
        setButtons();
        add(pnl);
    }

    private void setButtons() {
        btn = new JButton();
        pnl.add(btn);
    }
}

Upvotes: 0

Views: 57

Answers (1)

camickr
camickr

Reputation: 324108

    setVisible(true);
    setButtons();
    add(pnl);

Your components have a size of (0, 0) so there is nothing to paint.

The solution is to make the frame visible AFTER all the components have been added to the frame:

    setButtons();
    add(pnl);
    setVisible(true);

When you make the frame visible, or use the pack(), method the layout manager is invoked so know the components will have a size/location.

but these posts have too much code instead of the problem in an isolated code.

I suggest you start with the code example from the Swing Tutorial for Swing basics. Download an example and use it as a starting point for a better structured class. For example all Swing components should be create on the Event Dispatch Thread (EDT).

Upvotes: 1

Related Questions