繁体   English   中英

在Java中更改文本的颜色

[英]Changing Color of text in Java

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

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

这是代码:

import javax.swing.JComponent;

public class CustomFont extends Font {
    private String string;
    private int FontStyle;

    public CustomFont(String text, int style) {
        super("Serif", style, 15);
        FontStyle = style;
        string = text;  

        Drawing draw = new Drawing();
        draw.repaint();
    }

    private class Drawing extends JComponent {
        public void paintComponent(Graphics g) {
            Font font = new Font("Serif", Font.BOLD, 15);
            g.setFont(font);
            g.setColor(Color.YELLOW);
            g.drawString(string, getX(), getY());
        }
    }
}

添加到我的评论:

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

@Override 
protected void paintComponent(Graphics g) {
      super.paintComponent(g);

      Font font = new Font("Serif", Font.BOLD, 15);
      g.setFont(font);
      g.setColor(Color.YELLOW);
      g.drawString(string, 0, 0);
}

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

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

private class Drawing extends JComponent {

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);//you would infact caluclate text size using FontMetrics#getStringWidth(String s)
    }
}

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

这个CustomFont类中有很多东西没有任何意义。 首先,缺少任何与Font实际相关的事情,另一个事实是你并没有真正使用其中的任何代码。 以下似乎更符合您的要求。

public class Drawing extends JComponent {
    String text;
    Font myFont;
    Color myTextColor;

    public Drawing(String textArg, Font f, Color textColor) {
        myFont = f;
        myTextColor = textColor;
        text = textArg;
    }

    public void paintComponent(Graphics g) {
        g.setFont(myFont);
        g.setColor(myTextColor);
        g.drawString(text, 0, getHeight() / 2);
    }
}

如下图所示使用......

public class Test {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Font font = new Font("Serif", Font.BOLD, 15);
        String text = "blah blah blah";
        Color textColor = Color.YELLOW;
        Drawing d = new Drawing(text, font, textColor);

        frame.add(d);
        frame.setSize(100,100);
        frame.setVisible(true);
    }
}

绘图使用Font ,Font不使用Drawing Font定义Drawing是没有意义的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM