Drawing text in java, Look and Feel problems

I overridden the extended JToggleButton paintComponent method so that I can use the TexturePaint fill for text when the button is switched. The problem I am facing is that I cannot draw text using the same font as my default appearance. I tried g2d.setFont (this.getFont ()); where "this" is the button I'm working with. The font is close, but when drawing it looks bolder than the default text. Is there a better way to draw text so that it looks the same as the default, except for color? Thanks in advance!

+4
source share
2 answers

If you override the paintComponent () method, then the Graphics object must be set to have the font of the toggle button. The difference is probably related to antialiasing, which is not enabled by default.

I found 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 post - How to set text above and below the JButton icon? - that this will not work on all platforms and in LAF. The comment also suggests a suggested solution on how to draw text.

+4
source

This question is similar and gives the answer: How to get the default font for Swing JTabbedPane shortcuts?

I'm not quite sure what the key would be, but after this answer you can try:

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

EDIT

This is not a snippet of a related question, but after a little testing, it seems equivalent:

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

which is the code provided in the related question.

EDIT 2

I think I found a solution. The default return value is just the regular font I got in the line example:

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

My suggestion (to make this not so ugly) adds some private properties for the standard style and default font size for your class (and you can set them in the constructor):

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

And then you can clear:

 this.setFont(UIManager.getDefaults().getFont("ToggleButton.font").deriveFont(this.fontStyle, this.fontSize)); 
+3
source

Source: https://habr.com/ru/post/1381543/


All Articles