drawString() 方法覆盖之前的绘图(paintComponent 不清除) [英] drawString() method overwrites previous drawings (paintComponent does not clear)

查看:40
本文介绍了drawString() 方法覆盖之前的绘图(paintComponent 不清除)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以根据布尔方法的结果(CSGOBot#isRecording())绘制特定的字符串(和特定的颜色).我使用 JPanel#paintComponent(Graphics) 方法绘制字符串,并使用另一个线程重新绘制.

I have this code to draw a specific String (and a specific Color), depending on the result of a boolean method (CSGOBot#isRecording()). I use the JPanel#paintComponent(Graphics) method to paint the String, and I use another thread to repaint.

线程的run方法:

@Override
public void run() {
    while (true) {
        frame.repaint(); // This is the JPanel, not the JFrame
    }
}

JPanel 扩展类:

The JPanel-extended class:

public class FrameDisplay extends JPanel {
    public FrameDisplay() throws HeadlessException {
        this.setSize(300, 100);
        this.setBackground(new Color(0, 0, 0, 0));
        this.setVisible(true);
    }

    @Override
    public void paintComponent(Graphics g1) {
        super.paintComponent(g1);
        Graphics2D g = (Graphics2D)g1;
        g.setColor(CSGOBot.isRecording() ? Color.RED : Color.GREEN);
        g.setFont(g.getFont().deriveFont(14f).deriveFont(Font.BOLD));
        g.drawString(CSGOBot.isRecording() ? "RECORDING (Alt+R to Stop)" : "Record on hold (Alt+R to Start)", 5, 10);
    }
}

然而,paintComponent 方法不会清除自身,当布尔值改变时,字符串会覆盖自身.这是结果的截图:

However, the paintComponent method does not clear itself, and the Strings paint over themselves when the boolean value is changed. This is a screenshot of the result:

我试图避免使用 clearRect 方法,因为它会清除对面板/框架所做的任何样式.

I am trying to avoid using the clearRect method, since it clears any styling made to the panel/frame.

推荐答案

问题是,你已经用 alpha 值指定了背景,new Color(0, 0, 0, 0)

The problem is, you've specified the background with a alpha value, new Color(0, 0, 0, 0)

Swing 只处理由 opaque 属性指定的透明或非透明组件

Swing only deals with transparent or non-transparent components which is specified by the opaque property

基本上,使用基于 alpha 的颜色意味着当组件尝试填充其背景时,它什么都不使用,但更重要的是,Swing 不知道它应该在组件下绘制,从而导致更多绘制问题

Basically, using a alpha based color means that when he component tries to fill its background, it's using nothing, but, more importantly, Swing doesn't know that it should paint under the component, causing more painting issues

代替setBackground,使用setOpaque(false)

这篇关于drawString() 方法覆盖之前的绘图(paintComponent 不清除)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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