Reputation: 121
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
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
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
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