我正在尝试使用Java GUI组件像Lite-Bright一样使游戏。我被困在动作发生时如何获得按钮的背景颜色?在Java API中,有JButton.getBackground()
等方法。
在我的程序中单击按钮时,我想要该单击按钮的背景颜色,我想在特定位置绘制该颜色的椭圆形。
这是我的代码
/**
* Action Listener for Buttons
*/
class ButtonAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
setColor(getBackground()); // here i want to get background color as light blue.
}
}
b1 = new JButton("o");
Color c1 = new Color(100,255,255);// this is light blue color
b1.setBackground(c1);
ActionListener listener = new ButtonAction();
b1.addActionListener(listener);
/**
* this method will set vakue of the color and that color will use to draw oval
* filled with that color.
*/
public void setColor(Color C) {
this.c = C;
}
您需要通过在ActionListener的ActionEvent参数上调用.getSource()
来按下按钮:
class ButtonAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
// get the button that was pressed
AbstractButton button = (AbstractButton) e.getSource();
// get its background Color
Color color = button.getBackground();
// TODO: do what you want with the color
}
}
setColor(getBackground());
中的GetBackground指的是您正在实现代码的类this.getBackground()
。这是一个具有GetBackground的Jframe或其他对象,但不是您的按钮B1。
您想获得事件源组件(即单击的jbutton)并获得其背景颜色(((JComponent)e.getSource()).getBackground()
)。