Home > Software engineering >  JLabel does not appear in JFrame when implemented in separate classes
JLabel does not appear in JFrame when implemented in separate classes

Time:06-09

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);
    }
}

CodePudding user response:

import javax.swing.JLabel;

public class MyLabel extends JLabel {
    public MyLabel() {
        super();
        setText("Welcome");
    }
}

is what you need. You hide your code inside another JLabel which is not your subclass. It sort of begs the question though: why are you creating a subclass? Why not just use a JLabel right off?

CodePudding user response:

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);
    }
}
  • Related