Drawing text in java, Look and Feel problems

大兔子大兔子 提交于 2019-12-01 19:59:58
camickr

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.

Brandon Buck

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));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!