Colors 我不知道';当按下按钮时,我不想改变按钮的颜色

Colors 我不知道';当按下按钮时,我不想改变按钮的颜色,colors,jbutton,pressed,Colors,Jbutton,Pressed,当按下时,它会改变颜色。我怎样才能不让它变色呢。我有多个按钮,所以如果有一行或两行的解决方案,请帮助我,记住我是初学者,编写一些大型类对我没有帮助,因为我有多个不同名称的按钮会受到影响 编辑:一行中的解决方案是: Color newColor = new Color(197,222,90); JButton newButton; newButton = new JButton(icon); newButton.setBacgroundColor(newColor); 但它改变了所有按钮的颜色,

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

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

Color newColor = new Color(197,222,90);
JButton newButton;
newButton = new JButton(icon);
newButton.setBacgroundColor(newColor);
但它改变了所有按钮的颜色,但我需要另一个有不同的颜色


编辑2:经过一些研究,我发现并没有简单的解决办法(但应该是,它只是一个按钮)。我怎么看,我有2个解决方案,1。是将按钮拆分为单独的类并为它们设置UIManager,第二个是制作自定义按钮。对于按钮来说,这是太多的工作了(ffs它只是一个按钮)。

我没有发现任何东西可以改变正常JButton上的特定行为。问题是,无论您在actionlistener中为按钮编写什么,都将在您放开鼠标按钮之后发生,而不是“在单击时”

不过,还有一些变通办法

我的首选方法是,删除按钮上的所有图形,然后将自己的图像添加到按钮的常规和按下状态。您可以截取GUI的屏幕截图,删除按钮,然后将该图像设置为两种状态

 UIManager.put("Button.select", newColor);
显然,有许多方法可以保留和加载图像,但由于这不是这里的问题,我将不使用其他方法

不过,没有必要经历无数次。编写JButton类的自定义实现应该很容易,在这个类中,自定义构造函数接受一个参数,即BuffereImage,然后构造函数相应地设置它(更改图标)。然后,当您创建一个新的JButton时,您所要做的就是使用您自己的类,并向它传递一个映像:

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));
你也可以很容易地处理很少的图像。您所需要的只是一个包含所有图像的HashMap,其中包含一个字符串作为键。假设您需要4个OK按钮。你制作一个按钮的图像,上面写着“OK”。然后将该图像放入HashMap,如下所示:

JButton btn = new MyCustomJButton(myImage);
然后,您可以在创建按钮时执行此操作,如果您想要更多,请反复执行:

myMap.put("OK", myImage);
或者:
实现这一点的另一种方法非常复杂,但可能被认为是“正确的方法”,即使用ButtonUI,如

中所示。如果OP指的是在按下鼠标时带有图标的按钮上背景颜色的临时变化,则以下语句起到了作用:

按钮。setContentAreaFilled(假)

如果您希望有一个透明按钮,例如仅图标按钮,则应将其设置为false


我花了很长时间才弄明白。这似乎是一种鲜为人知的技术,也许是因为它的名字对它的效果没有什么线索。

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

JButton btn = new MyCustomJButton(myMap.get("OK"));
如果你不想穿灰色的衣服,你就在他下面再扣一个钮扣

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

panelname.add(按钮2,-5,-5)\(-5,-5表示面板下有5个点)

这是我一直在寻找的简单而好的解决方案。
panelname.add(button1,+5,+5); \\(first not clicable, not visible button, notice +5)