I'm trying to repaint a JPanel
over a transparent JFrame
but it lets the mark of the previous repaint:
previous repaint keeps showing
I know this is a known problem and there's a similar question already posted, but the answers only explain why it doesn't work and they don't give a solution.
Can anyone please make a change in the code or add some, so it gives the desired effect? (a cross that follows the mouse over a transparent background)
I don't want to take a picture of the desktop and draw it in the JPanel
.
The code is the following
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
final class Transparency extends JFrame{
private NewPanel np;
Transparency(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setUndecorated(true);
setLocation(200,200);
setBackground(new Color(0,0,0,0));
np = new NewPanel();
setContentPane(np);
pack();
setVisible(true);
}
public static void main(String []args){
Transparency li = new Transparency();
}
}
final class NewPanel extends JPanel{
private Point p = new Point(0,0);
private final int length = 25;
NewPanel(){
setPreferredSize(new Dimension(400,400));
setOpaque(false);
addMouseMotionListener(new MouseAdapter(){
public void mouseMoved(MouseEvent e){
p = e.getPoint();
repaint();
}
});
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.GREEN);
g.drawLine(p.x-length,p.y,p.x+length,p.y);
g.drawLine(p.x,p.y-length,p.x,p.y+length);
g.setColor(Color.WHITE);
g.drawRect(0,0,399,399);
}
}
Since there is no heavyweight top level component, you will need to manage the background yourself.
Add this to your paintComponent method, right after super.paintComponent:
g.clearRect(0, 0, getWidth(), getHeight());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.