我没有发现任何东西可以改变普通 JButton 上的特定行为。问题是,无论您在按钮的动作侦听器中写什么,都会在您放开鼠标按钮之后发生,而不是“在单击时”。
但是,有一些解决方法。
我的首选是从按钮中删除所有图形,然后将您自己的图像添加到按钮的常规和按下状态。您可以截取 GUI 的屏幕截图,剪下按钮,然后将该图像设置为两种状态。
JButton myButton = new JButton();
// Sets button x, y, width, height. Make the size match the image.
myButton.setBounds(5, 30, 100, 30);
// Remove border-graphics.
myButton.setBorder(null);
// Remove default graphics from the button
myButton.setContentAreaFilled(false);
// Remove the focus-indicating dotted square when focused (optional)
myButton.setFocusPainted(false);
// Here, myImage is a simple BufferedImage object.
// You can set one like this, provided you have an "images" package,
// next to your main class (ex: com.somecompany.someprogram.images),
// that contains an image:
BufferedImage myImage = ImageIO.read(getClass().getResource("images/myImage.png"));
// Then we simply apply our image to both states for the button, and we're done.
myButton.setIcon(new ImageIcon(myImage));
myButton.setPressedIcon(new ImageIcon(myImage));
显然有很多方法可以保留和加载图像,但由于这不是这里的问题,所以我将不再使用其他方法。
不过,没有必要经历无数次。编写自己的 JButton 类的自定义实现应该很容易,其中自定义构造函数采用单个参数,即 BufferedImage,然后构造函数相应地对其进行设置(更改图标)。然后,当您创建一个新的 JButton 时,您所要做的就是使用您自己的类,并将图像传递给它:
JButton btn = new MyCustomJButton(myImage);
您也可以轻松地与很少的图像相处。您所需要的只是一个包含所有图像的 HashMap,并以字符串为键。想象一下,您需要 4 个确定按钮。您制作一个按钮的单个图像,上面写有“OK”文本。然后将该图像放入 HashMap 中,如下所示:
myMap.put("OK", myImage);
然后,您可以在创建按钮时反复执行此操作,如果您想要更多:
JButton btn = new MyCustomJButton(myMap.get("OK"));
或者:
实现此目的的另一种方法是使用 ButtonUI,这种方法非常精细,但可能被认为是“正确的方法”,如对另一篇文章的回答中所述。