Reputation: 5527
I am trying to create a new class JXLabel
which inherits JLabel
. Difference is that this extended class will assign a default font for the label.
If I try this:
public class JXLabel extends JLabel {
Font f = new Font("Segoe UI", Font.PLAIN, 6);
public JXLabel() {
super();
this.setFont(f);
}
public JXLabel(Icon icon) {
super(icon);
this.setFont(f);
}
public JXLabel(Icon icon, int horizontalAlignment) {
super(icon, horizontalAlignment);
this.setFont(f);
}
public JXLabel(String text) {
super(text);
this.setFont(f);
}
public JXLabel(String text, Icon icon, int horizontalAlignment) {
super(text, icon, horizontalAlignment);
this.setFont(f);
}
public JXLabel(String text, int horizontalAlignment) {
super(text, horizontalAlignment);
this.setFont(f);
}
}
I would expect new labels created as JXLabel to have this default font, but they do not.
If I create a regular JLabel and do:
myLabel.setFont(new Font("Segoe UI", Font.PLAIN, 6));
It works. Any tip on what is wrong in the extended class? Thanks.
Upvotes: 0
Views: 373
Reputation: 168845
Here is a MCVE of the above code, testing the assertion that one way it works, while the other it doesn't. Here, it works by either setting the font of a standard JLabel
or by using a JXLabel
.
See if you can:
import java.awt.*;
import javax.swing.*;
public class JXLabelTest {
public static void main(String[] args) {
Runnable r = () -> {
String s = "The quick brown fox jumps over the lazy dog";
JLabel myLabel = new JLabel(s);
myLabel.setFont(new Font("Segoe UI", Font.PLAIN, 6));
JOptionPane.showMessageDialog(null, myLabel);
JOptionPane.showMessageDialog(null, new JXLabel(s));
};
SwingUtilities.invokeLater(r);
}
}
class JXLabel extends JLabel {
Font f = new Font("Segoe UI", Font.PLAIN, 6);
public JXLabel() {
super();
this.setFont(f);
}
public JXLabel(Icon icon) {
super(icon);
this.setFont(f);
}
public JXLabel(Icon icon, int horizontalAlignment) {
super(icon, horizontalAlignment);
this.setFont(f);
}
public JXLabel(String text) {
super(text);
this.setFont(f);
}
public JXLabel(String text, Icon icon, int horizontalAlignment) {
super(text, icon, horizontalAlignment);
this.setFont(f);
}
public JXLabel(String text, int horizontalAlignment) {
super(text, horizontalAlignment);
this.setFont(f);
}
}
Upvotes: 1