如何在Swing界面中创建一个切换图片按钮?我有两张图片,imageon.jpg和imageoff.jpg,基本上我想要一个可点击的元素来切换图片并触发事件。
更新:有没有一种方法可以覆盖图像周围通常的“chrome”?我更喜欢简单的图像而不是内部带有图像的按钮。
使用ImageIcon
加载图像。创建一个JToggleButton
。然后使用AbstractButton.setIcon/setPressedIcon/setSelectedIcon
应用图标。通过AbstractButton.setBorderPainted(false)
移除边框。
JToggleButton
?您可以对其进行子类化并覆盖paint()
方法,以根据是否选择绘制正确的图像。
另一种方法是对JPanel
进行子类化并捕获鼠标点击事件,重写paintComponent()
方法来绘制正确的图像。这样,唯一绘制的内容就是实际图像(与JToggleButton
选项不同)。
我曾经遇到过JButtons的同样问题。尝试以下方法:
result = new JButton( icon );
result.setBorderPainted( false );
result.setContentAreaFilled( false );
width = icon.getIconWidth();
height = icon.getIconHeight();
result.setPreferredSize( new Dimension( width, height ) );
为了消除按钮周围的额外空间,有必要设置首选大小。这对我在Windows 7和Mac OS X 10.6上都起作用。
MyButton() {
setBorder(null);
setBackground(null);
}