Reputation: 19
I want to make Java Swing components with standard font size, so I customized the components to "HAHA components" by making subclasses extended from the swing component class.
However, the customized JTextfield
cannot be typed and setText
. The customized Button shows no text. (I sure I did not write other codes that could change the properties of the customized components).
After debugging, I found that if I delete the setFont
statement in HAHATextField
, that text field object can be typed and setText
. And further if I setFont
through the HAHATextField
instance, it works properly.
Why did this not work properly? And what is the proper way to do?
The codes are below.
class HAHAButton extends JButton
{
HAHAButton(String haha)
{
super(haha);
this.setFont(new Font("haha",Font.BOLD,fontsize));
}
}
class HAHALabel extends JLabel
{
HAHALabel(String haha)
{
super(haha);
this.setFont(new Font("haha",Font.BOLD,fontsize));
}
}
class HAHATextField extends JTextField
{
HAHATextField(int haha)
{
super(haha);
this.setFont(new Font("haha",Font.BOLD,fontsize));
this.setText("haha");
}
}
Upvotes: 0
Views: 184
Reputation: 324207
I have no idea what the "haha" font is. Whenever you test something new, test the logic with system classes and objects.
Also we have no idea what the fontsize is or if it even has a value.
So you would do something like:
//this.setFont(new Font("haha", Font.BOLD, fontsize));
setFont( getFont().deriveFont( 24.0f ) );
If this works then you can try a different font family:
setFont(new Font("monospaced", Font.BOLD, 16));
If this works then you try your custom font.
This will help isolate where the problem occurs.
And what is the proper way to do?
If you want to change this for ALL the components then sometimes you can take advantage of the UIManager. At the start of your class BEFORE you create an components you can do:
UIManager.put("TextField.font", new FontUIResource( yourFontHere ));
Now this will be the default font used when the component is created.
Again, start with a standard system Font for a simple test. And then try the "haha" Font.
You would need to do this for the other components as well.
Check out UIManager Default for more information. Don't go crazy trying to change these defaults as it is not guaranteed that each LAF will use these properties.
Upvotes: 1