user3404696
user3404696

Reputation: 121

How do I display JButtons and JLabels in a JFrame?

I tried to use this code to display a labeled window, but it only displays a blank window.

    JFrame window = new JFrame("My Window");
    window.setVisible(true);
    window.setResizable(true);
    window.setSize(680,420);
    window.setContentPane(new Container());
    window.getContentPane().setLayout(new FlowLayout());
    JPanel panel = new JPanel();
    JLabel label = new JLabel("LABEL");
    label.setBackground(Color.BLACK);
    panel.add(label);
    window.add(panel);

Upvotes: 2

Views: 196

Answers (3)

Stunner
Stunner

Reputation: 1131

(as you are calling setvisible() method at starting).. You can also use update() method so that the components on the jframe will be updated or repainted..

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347314

Try calling setVisible last

JFrame window = new JFrame("My Window");
//window.setVisible(true);
//window.setResizable(true);
//window.setSize(680,420);
//window.setContentPane(new Container());
window.setLayout(new FlowLayout());
JPanel panel = new JPanel();
JLabel label = new JLabel("LABEL");
label.setBackground(Color.BLACK);
panel.add(label);
window.add(panel);

window.setResizable(true);
// Pack will size the window to fit the content, 
// tacking into account the preferred size of the
// content...
window.pack();
window.setVisible(true);

Also note, JLabel is transparent by default, so setting it's background color will have no effect unless you change it's opaque property to true

Upvotes: 3

Rahul
Rahul

Reputation: 3509

After adding all component, set the visibility of frame.

    JFrame window = new JFrame("My Window");
    window.setResizable(true);
    window.setSize(680,420);
    window.setContentPane(new Container());
    window.getContentPane().setLayout(new FlowLayout());
    JPanel panel = new JPanel();
    JLabel label = new JLabel("LABEL");
    label.setBackground(Color.BLACK);
    panel.add(label);
    window.add(panel);     
    window.setVisible(true);

Upvotes: 1

Related Questions