質問

I've overridden the paintComponent method of an extended JToggleButton so that I can use a TexturePaint fill for the text when the button is toggled. The problem I'm running into is that I can't seem to draw the text using the same font as my look and feel is using as a default. I've tried g2d.setFont(this.getFont()); , where "this" is the button I'm working with. The font is close, but appears bolder than the default text when I draw it. Is there a better way to draw text such that it looks the same as the default, save for the color? Thanks in advance!

役に立ちましたか?

解決

If you are overriding the paintComponent() method then the Graphics object should already be configured to have the Font of the toggle button. The difference is probably because of anti aliasing which is not turned on by default.

I have found some code that works for me in very limited testing. Try the following in the paintComponent() method:

Graphics2D g2 = (Graphics2D)g.create();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Map map = (Map)(toolkit.getDesktopProperty("awt.font.desktophints"));

if (map != null)
{
    g2.addRenderingHints(map);
}

g2.drawString(...);
g2.dispose();

I was warned in this posting - How to set text above and below a JButton icon? - that this will not work on all platforms and LAF's. The comment also gives a suggested solution on how to paint the text.

他のヒント

This question is similar and provides an answer: How do I get the default font for Swing JTabbedPane labels?

I'm not quite sure what the key would be, but following that answer you may want to try:

UIManager.getLookAndFeelDefaults().getFont("ToggleButton.font");

EDIT

This is not the snippet from the linked question, but after a small bit of testing it appears to be equivalent to the:

UIManager.getDefaults().getFont("ToggleButton.font");

which is the code given in the linked question.

EDIT 2

I think I've found a solution. The default returned is just a plain font, I got around this in a sample with the line:

this.setFont(UIManager.getDefaults().getFont("ToggleButton.font").deriveFont(this.getFont().getStyle(), this.getFont().getSize()));

My suggestion (to make that not as ugly) is add some private properties for the default Font Style and Size to your class (and you can set them in the constructor):

fontStyle = this.getFont().getStyle();
fontSize = this.getFont().getSize();

And then you could clean up with:

this.setFont(UIManager.getDefaults().getFont("ToggleButton.font").deriveFont(this.fontStyle, this.fontSize));
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top