Reputation: 43
I place a semi-transparent JCheckBox object on a semi-transparent JPanel. When I move the mouse cursor over the JCheckBox object, it repaints the JCheckBox object on top of the original JCheckBox object a few cells displaced from the original JCheckBox object.
What I want it to do is to look exactly the same after I move my mouse cursor over it.
Before (the mouse cursor is NOT on the JCheckBox object):
After (the mouse cursor is on the JCheckBox object):
Code:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
class TransparentPanel extends JPanel{
public TransparentPanel(){
super();
setOpaque(false);
setBackground(new Color(0, 0, 0, 100));
JCheckBox checkBox=new JCheckBox("Check Box"){
protected void paintComponent(Graphics g){
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
};
checkBox.setFocusable(false);
checkBox.setOpaque(false);
checkBox.setBackground(new Color(200, 200, 200, 50));
add(checkBox);
}
@Override
protected void paintComponent(Graphics g){
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
public static void main(String[] args){
JFrame frame=new JFrame();
frame.setSize(200, 100);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TransparentPanel());
frame.setVisible(true);
}
}
Sorry if this was already asked. I looked all over and I couldn't find someone with the same problem. And sorry again if this post isn't a legitimate SSCCE. It's my first post here.
EDIT 1: Edited the code. The problem still exists.
EDIT 2: The code now works.
Upvotes: 0
Views: 194
Reputation: 324147
See Backgrounds With Transparency for an explanation on how painting works and maybe a solution you can use.
In this case I would guess you would need to add both TransparentPanel and the checkBox to a separate AlphaContainer
.
Upvotes: 2