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它只是一个按钮)。
我发现没有什么可以改变一个正常的JButton特定的行为。 当你已经让mousebutton的去,而不是“同时单击”将出现的问题是,无论是在你的ActionListener的按钮写。
有解决方法,但是。
我首选的选择是,从键删除所有的图形,然后添加自己的图像,按钮的定期和压制的状态。 你可以把你的图形用户界面的屏幕截图,切出的按钮,并设置该图像是这两个州。
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);
你也可以很容易地用很少的图像相处。 所有你需要的是保持所有的图像,用String作为键一个HashMap。 想象一下,你需要4 OK-按钮。 你让一个按钮的单个图像,上面写有文字“OK”。 然后,你把图像到HashMap中,就像这样:
myMap.put("OK", myImage);
然后创建一个按钮时,一遍又一遍,如果你想了解更多,你可以这样做:
JButton btn = new MyCustomJButton(myMap.get("OK"));
或者:实现这一目标,这是非常复杂的,但很可能被认为是“正确的方式”,另一种方法是使用ButtonUI,在提出这个答案另一职务。
如果OP指的是背景色与在按下鼠标的那一刻图标的按钮临时变化,下面的语句做的伎俩:
button.setContentAreaFilled(假);
“如果你希望有一个透明的按钮,比如一个图标唯一的按钮,例如,那么你应该设置为false。”
这花了我很长的时间来弄清楚。 这似乎是一个鲜为人知的技术,也许是因为它的名字给人一点线索其效果。
由于只有第一道,我们仍然可以看到它被点击。 您需要结合这两个:
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分)