使用Swing JToolbarButtonJToggleButton
中所示的按下。
在您的用例中,未选择的绿色图像将只是完全透明的图像,或者是所需 BG 颜色的图像。
更具体的例子:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
class ToggleImage {
public static JToggleButton getButton(
Image selected,
Image unselected) {
JToggleButton b = new JToggleButton();
b.setSelectedIcon(new ImageIcon(selected));
b.setIcon(new ImageIcon(unselected));
b.setBorderPainted(false);
b.setContentAreaFilled(false);
b.setFocusPainted(false);
b.setMargin(new Insets(0,0,0,0));
return b;
}
public static Image getImage(boolean hasSquare) {
int size = 60;
BufferedImage bi = new BufferedImage(
size,size,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
if (hasSquare) {
g.setColor(Color.RED);
g.fillRect(1,1,size-2,size-2);
}
g.dispose();
return bi;
}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
Image selected = getImage(true);
Image unselected = getImage(false);
int row = 2;
int col = 5;
JPanel p = new JPanel(new GridLayout(row,col));
for (int ii=0; ii<row*col; ii++) {
p.add( getButton(selected, unselected) );
}
JOptionPane.showMessageDialog(null, p);
}
});
}
}
请注意,按钮将对鼠标和键盘输入做出反应,而(默认情况下)标签不会。