Pregunta

what modifiers should I give the variable, label, in this code example below? I am new to Java, but the first thing I wanted to do was break out all the classes I can use in swing like JLabel and make it so I can call them dynamically. I hope I did that below. But yeah I was not sure about private static JLabel label; because ultimately I want to be able to declare all of the swing classes in a master file somewhere. Thanks.

package base;

import java.awt.Component;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class CreateLabel extends JLabel {
    private static final long serialVersionUID = 1L;
    private static JLabel label;

    public Component createLabel(JFrame frame, String text) {
        label = new JLabel(text);
        return frame.getContentPane().add(label);
    }
}
¿Fue útil?

Solución

What I understand is, you want to your createLabel() method to add a JLabel to passed JFrame. What you can do is:

public class LabelCreator /*extends JLabel*/ {
    /*private static final long serialVersionUID = 1L;*/
    /*private static JLabel label;*/

    public Component createLabel(JFrame frame, String text) {
        JLabel label = new JLabel(text);
        return frame/*.getContentPane()*/.add(label);
    }
}

Note the change of class name to respect naming convention.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top