在Java中绘制文本,外观和感觉的问题 [英] Drawing text in java, Look and Feel problems

查看:226
本文介绍了在Java中绘制文本,外观和感觉的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我重写了扩展JToggleButton的paintComponent方法,以便在按钮切换时可以使用TextPaint填充文本。我遇到的问题是,我似乎无法使用相同的字体绘制文本,因为我的外观和感觉正在使用作为默认值。我试过g2d.setFont(this.getFont()); ,this是我正在使用的按钮。字体很接近,但是当我画的时候,比默认文本显得更大胆。有没有更好的方式来绘制文本,使其看起来像默认一样,除了颜色?如果你正在重写paintComponent()方法,那么Graphics对象应该已经被配置为有字体的切换按钮。差异可能是因为反锯齿,这是默认打开。



我发现了一些代码,在我非常有限的测试中工作。在paintComponent()方法中尝试以下内容:

  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();

我在本文中被警告 - - 这不会在所有平台上工作和LAF的。该评论还提供了一个建议的解决方案,如何绘制文本。


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.

这篇关于在Java中绘制文本,外观和感觉的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆