Reputation: 3820
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.
The thread's run
method:
@Override
public void run() {
while (true) {
frame.repaint(); // This is the JPanel, not the JFrame
}
}
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);
}
}
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:
I am trying to avoid using the clearRect
method, since it clears any styling made to the panel/frame.
Upvotes: 3
Views: 331
Reputation: 347314
The problem is, you've specified the background with a alpha value, new Color(0, 0, 0, 0)
Swing only deals with transparent or non-transparent components which is specified by the opaque
property
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
Instead of setBackground
, use setOpaque(false)
Upvotes: 2