I have a JLayeredPane with two layers. The bottom layer is a canvas with bounds (0, 0, 600, 400) and the top layer is a JButton with bounds (500, 300, 40, 40). The JButton is completely tansparent. So in this JButton area the canvas should be visible. But instead there is a white rectangle. It doesn't matter for the issue what is drawn on the canvas or if it is a canvas at all.
Here is the code:
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private final Canvas canvas;
private final JButton button;
Main() {
super("InvisibleButton");
this.canvas = new Canvas();
this.canvas.setBounds(0, 0, 600, 400);
this.canvas.requestFocus();
this.canvas.setIgnoreRepaint(true);
this.canvas.setVisible(true);
this.button = new JButton();
this.button.setBounds(500, 300, 40, 40);
// Doesn't work
this.button.setOpaque(false);
this.button.setBorderPainted(false);
this.button.setFocusPainted(false);
this.button.setContentAreaFilled(false);
this.button.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
System.out.println("Dragged");
}
});
JLayeredPane jlp = new JLayeredPane();
jlp.setBounds(0, 0, 600, 400);
jlp.add(this.button);
jlp.add(this.canvas);
this.add(jlp);
this.setLayout(null);
this.setSize(600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);
Timer repainter = new Timer();
repainter.schedule(new TimerTask() {
@Override
public void run() {
Graphics2D g2d = (Graphics2D)canvas.getGraphics();
Shape s = new Rectangle.Double(0, 0, 600, 400);
g2d.setColor(Color.BLUE);
g2d.fill(s);
g2d.draw(s);
}
}, 0, 100);
}
public static void main(String[] args) {
new Main();
}
}
The drag event works great. But there is this white rectangle:1