这可以作为解决方案吗?
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class PanelCheckBox {
private JPanel panel = new JPanel();
private JCheckBox checkBox = new JCheckBox();
private JLabel icon = new JLabel(new SquareIcon());
private void showGui() {
final JFrame frame = setupGui();
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
frame.setVisible(true);
}
});
}
private JFrame setupGui() {
panel.add(icon);
panel.add(checkBox);
panel.setOpaque(true);
JFrame frame = new JFrame("Hello");
frame.add(panel, BorderLayout.CENTER);
setupListeners();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
return frame;
}
private void setupListeners() {
panel.addMouseListener(new MouseAdapter() {
Color origColor = null;
Color hoverColor = new Color(200, 180, 180);
@Override public void mouseEntered(MouseEvent me) {
if (origColor == null) {
origColor = panel.getBackground();
}
panel.setBackground(hoverColor);
}
@Override public void mouseExited(MouseEvent me) {
Point location = me.getPoint();
if (!panel.contains(location)) {
panel.setBackground(origColor);
}
}
@Override public void mouseClicked(MouseEvent me) {
checkBox.doClick();
}
});
}
public static void main(String[] args) {
PanelCheckBox thing = new PanelCheckBox();
thing.showGui();
}
static class SquareIcon implements Icon {
@Override
public void paintIcon(Component cmpnt, Graphics grphcs,
int i, int i1) {
Color origColor = grphcs.getColor();
grphcs.setColor(Color.BLUE);
grphcs.fillRect(0, 0, 25, 25);
grphcs.setColor(origColor);
}
@Override public int getIconWidth() { return 25; }
@Override public int getIconHeight() { return 25; }
}
}