Search code examples
javaswingjframejlabel

JLabel does not appear in JFrame when implemented in separate classes


I am trying to add a JLabel to my JFrame. I have implemented them in separate classes but when I run the code, I cannot see my label.

It worked well when I implemented both frame and label in the App class.

import javax.swing.JFrame;

public class MyFrame extends JFrame {

    public MyFrame() {
        this.setSize(420, 420); 
        this.setTitle("First Java GUI");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }    
}
import javax.swing.JLabel;

public class MyLabel extends JLabel {
    public MyLabel() {
        JLabel label = new JLabel();
        label.setText("Welcome");
    }
}
public class App {
    public static void main(String[] args) {
        
        MyFrame frame1 = new MyFrame();
        MyLabel label1 = new MyLabel();

        frame1.add(label1);
    }
}

Solution

  • You have a mistake in MyLabel class. If you extend it, just add constructors. But you in your constructor create another label, that is not added to frame. So, correct version is:

    import javax.swing.JLabel;
    
    public class MyLabel extends JLabel {
        
        public MyLabel(String text) {
            super(text);
        }
        
        public MyLabel() {
        }
    }
    

    And after it:

    public class App {
        public static void main(String[] args) {
            
            MyFrame frame1 = new MyFrame();
            MyLabel label1 = new MyLabel("Welcome");
    
            frame1.add(label1);
        }
    }