1
Color newColor = new Color(197,222,90);
JButton newButton;
newButton = new JButton(icon);
newButton.setBacgroundColor(newColor);

当它被按下时,它会改变颜色。我怎样才能让它不变色。我有多个按钮,所以如果有一两行有解决方案,请帮助我,并记住我是初学者,编写一些大型课程对我没有帮助,因为我有多个不同名称的按钮会受到影响.

编辑:一行的解决方案是:

 UIManager.put("Button.select", newColor);

但它改变了所有按钮的颜色,但我需要另一个有不同的颜色。

EDIT2:经过一些研究,我发现没有简单的解决方案(但它应该是,ffs 它只是一个按钮)。我如何看待它,我有 2 个解决方案,1. 是打破按钮以分隔类并为它们设置 UIManager,其次是制作自定义按钮。按钮的工作量太大(ffs它只是一个按钮)。

4

3 回答 3

2

我没有发现任何东西可以改变普通 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,这种方法非常精细,但可能被认为是“正确的方法”,如对另一篇文章的回答中所述。

于 2013-12-06T16:53:46.997 回答
1

如果 OP 指的是按下鼠标时带有图标的按钮上的背景颜色的临时更改,则以下语句可以解决问题:

button.setContentAreaFilled(false);

“如果您希望有一个透明按钮,例如仅图标按钮,那么您应该将其设置为 false。”

这花了我很长时间才弄清楚。这似乎是一种鲜为人知的技术,也许是因为它的名字几乎没有提供关于其效果的线索。

于 2018-04-23T20:32:27.600 回答
0

只有第一条车道我们仍然可以看到它被点击了。您需要将这两者结合起来:

button1.setContentAreaFilled(false);
button1.setEnabled(false);

如果你不想用灰色,你可以在他下面放另一个按钮。

panelname.add(button1,+5,+5); \\(first not clicable, not visible button, notice +5) 

panelname.add(button2,-5,-5); \(-5,-5 表示面板下有 5 个点)

于 2018-08-15T15:44:06.590 回答