I’m trying to learn how to do the GUI stuff in java with coding style
and this is what I’ve written :
import java.awt.Container;
import java.awt.Panel;
import javax.swing.*;
public class Class1 extends JFrame {
public void createGUI()
{
JpanelMock jm = new JpanelMock();
setTitle("Frame1");
setSize(320,200);
this.add(jm.drawGUI());
}
public static void main(String [] arg)
{
Class1 cls = new Class1();
cls.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cls.setVisible(true);
cls.createGUI();
}
}
//----------------------------JpanelMock.java
import javax.swing.*;
import java.awt.*;
public class JpanelMock extends JPanel {
public JpanelMock() {
}
public Component drawGUI()
{
super.setBackground(Color.YELLOW);
JButton b = new JButton("button 1");
JLabel l = new JLabel("label 1");
JTextField tf = new JTextField("text 1");
this.add(b);
this.add(l);
this.add(tf);
return this;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//drawGUI();
}
}
but when I start the program if I don’t do anything related to redrawing event I can’t see my yellow jpanel with a text + button in it.
why is this happening?
Whenever I see a question such as yours, I don’t have to look at the code. You’re calling
setVisible(true)on the JFrame before adding components to it. Change the order of this: callsetVisible(true)on your JFrame only after all components have been added.e.g.,