在Java中更改文本的颜色

前端之家收集整理的这篇文章主要介绍了在Java中更改文本的颜色前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在尝试创建一个单独的CustomFont类,其中我可以使用不同的文本属性.所以我创建了一个新的类扩展Font,并在里面创建了一个扩展JComponent的私有类Drawing.我在paintComponent方法中更改了字体和文本的颜色和其他特征.

问题是paintComponent方法没有被调用.我确信我犯了一些错误.

这是代码

  1. import javax.swing.JComponent;
  2. public class CustomFont extends Font {
  3. private String string;
  4. private int FontStyle;
  5. public CustomFont(String text,int style) {
  6. super("Serif",style,15);
  7. FontStyle = style;
  8. string = text;
  9. Drawing draw = new Drawing();
  10. draw.repaint();
  11. }
  12. private class Drawing extends JComponent {
  13. public void paintComponent(Graphics g) {
  14. Font font = new Font("Serif",Font.BOLD,15);
  15. g.setFont(font);
  16. g.setColor(Color.YELLOW);
  17. g.drawString(string,getX(),getY());
  18. }
  19. }
  20. }
最佳答案
@H_301_16@添加到我的评论

1)您不应该通过调用paintComponent(..)方法的super.XXX实现来尊重paint链,它应该是覆盖方法中的第一个调用,否则可能发生异常:

  1. @Override
  2. protected void paintComponent(Graphics g) {
  3. super.paintComponent(g);
  4. Font font = new Font("Serif",15);
  5. g.setFont(font);
  6. g.setColor(Color.YELLOW);
  7. g.drawString(string,0);
  8. }

在上面的代码中注意@Override注释,所以我确信我重写了正确的方法.并且getX()和getY()已被替换为0,因为getX和getY引用了组件位置,但是当我们调用drawString时,我们为它提供了在容器内绘制的位置的参数(并且它必须在当然,边界/大小是容器.

2)你应该在绘制到图形对象时覆盖getPreferredSize并返回适合你的组件绘图/内容的Dimensions,否则在视觉上不会有任何可见的,因为组件大小将是0,0:

  1. private class Drawing extends JComponent {
  2. @Override
  3. public Dimension getPreferredSize() {
  4. return new Dimension(200,200);//you would infact caluclate text size using FontMetrics#getStringWidth(String s)
  5. }
  6. }

正如一个建议使用一些RenderHints和Graphics2D看起来很漂亮的文本:)请看这里更多:

> Displaying Antialiased Text by Using Rendering Hints

猜你在找的Java相关文章