Here are my codes for adding the new component:
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (!todoListInput.getText().equals("")) {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.setBackground(new Color(213, 134, 145, 55));
JCheckBox checkBox = new JCheckBox("");
checkBox.setOpaque(false);
checkBox.setForeground(Color.WHITE);
//checkBox.setBorder(line);
panel.add(checkBox);
Border border = new LineBorder(Color.GRAY, 1, true);
Border margin = new EmptyBorder(10,10,10,10);
panel.setBorder(new CompoundBorder(margin, border));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
mainList.add(panel, gbc, 0);
validate();
repaint();
todoListInput.setText("");
}
}
});
My problem is that when I do an "onmouseover" action to the checkbox, part of the the whole jFrame will be appeared behind the checkbox
I found that this only appear when I do checkBox.setOpaque(false) or checkBox.setBackground(new Color(122,122,122,55)).
May I know what is the problem of my code?
panel.setBackground(new Color(213, 134, 145, 55));
The problem is your panel is using a transparent background and you are breaking the painting contract between a component. An opaque component needs to repaint the entire background (with an opaque color), however because of the transparency you are getting painting artifacts.
Check out Background With Transparency for more information and a couple of solutions.
The basic solution is:
JPanel panel = new JPanel()
{
protected void paintComponent(Graphics g)
{
g.setColor( getBackground() );
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
};
panel.setOpaque(false);
panel.setBackground( new Color(255, 0, 0, 20) );
frame.add(panel);
However, the link also provides a reusable solution so you don't need to use custom painting on every component that has a transparent background.