DrawString () method overwrites previous drawings (paintComponent does not clear)
I have this code to draw a specific line (and a specific color), depending on the result of a boolean ( CSGOBot#isRecording()
) method . I am using a method JPanel#paintComponent(Graphics)
to draw a String and I am using a different thread to redraw.
Stream method run
:
@Override
public void run() {
while (true) {
frame.repaint(); // This is the JPanel, not the JFrame
}
}
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 Lines paint on their own when the boolean changes. This is a screenshot of the result:
I am trying to avoid using the method clearRect
as it clears up any styling done on the panel / frame.
source to share
The problem is that you specified a background with an alpha value, new Color(0, 0, 0, 0)
Swing only uses transparent or opaque components specified by property opaque
Basically, using an alpha-based color means that when a component tries to fill its background, it doesn't use anything, but more importantly, Swing doesn't know what it should draw under the component, causing drawing problems
setBackground
Use insteadsetOpaque(false)
source to share