Reputation: 1
I have this code bellow that is suppose to display some text but it don't and I can't find the reason why.
public class TestMLD extends JPanel{
TestMLD(){
init();
}
private void init() {
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
Font font = new Font(Font.MONOSPACED, Font.ITALIC, 100);
JLabel helloLabel = new JLabel("Hello World !");
helloLabel.setFont(font);
helloLabel.setForeground(Color.BLUE);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new TestMLD());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
new TestMLD();
}
}
Thanks in advance
Upvotes: 0
Views: 32
Reputation: 2486
The issue here is that you never actually add the JLabel helloLabel
to your JPanel
/ TestMLD
.
To do so, add this line of code at the end of your init()
method:
add(helloLabel);
You also never actually set the layout you created to your panel
setLayout(flow);
Also, the second time you create a new TestMLD()
object is redundant. You can omit that.
All together, the updated code should look something like this:
public class TestMLD extends JPanel {
TestMLD() {
init();
}
private void init() {
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
setLayout(flow);
Font font = new Font(Font.MONOSPACED, Font.ITALIC, 100);
JLabel helloLabel = new JLabel("Hello World !");
helloLabel.setFont(font);
helloLabel.setForeground(Color.BLUE);
add(helloLabel);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new TestMLD());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Upvotes: 2