在java方法中的特定索引处使用数组
我正在做一个名为Light out的游戏!我想创建一个方法,在某个索引处更改按钮的颜色。为此,我使用了以下代码:在java方法中的特定索引处使用数组,java,arrays,oop,methods,Java,Arrays,Oop,Methods,我正在做一个名为Light out的游戏!我想创建一个方法,在某个索引处更改按钮的颜色。为此,我使用了以下代码: Color bg = _buttons[x][y].getBackground(); if(bg.equals(Color.white)){ _buttons[x][y].setBackground(Color.yellow); } else if (bg.equals(Colo
Color bg = _buttons[x][y].getBackground();
if(bg.equals(Color.white)){
_buttons[x][y].setBackground(Color.yellow);
}
else if (bg.equals(Color.yellow)){
_buttons[x][y].setBackground(Color.white);
x和y是整数,它们是我看到的当前值。
基本上,我想做一个方法,在任何索引,我在采取。我试过了
public void flipIt(JButton _buttons[this] [this]){
Color bg = _buttons[this][this].getBackground();
}
但是java不喜欢这样,有人能告诉我正确的方向吗?在您的调用代码中,您可以这样做:
flipIt(_buttons[x][y]);
你的函数是这样的
`public void flipIt(JButton button){
if(button.getBackground().equals(Color.white)){
button.setBackground(Color.yellow);
} else if (button.getBackground().equals(Color.yellow)){
button.setBackground(Color.white);
}
}'
在呼叫代码中,您可以执行以下操作:
flipIt(_buttons[x][y]);
你的函数是这样的
`public void flipIt(JButton button){
if(button.getBackground().equals(Color.white)){
button.setBackground(Color.yellow);
} else if (button.getBackground().equals(Color.yellow)){
button.setBackground(Color.white);
}
}'
如果事件侦听器拾取的事件是单击有问题的按钮,则不需要遍历x和y:
@Override
public void actionPerformed(ActionEvent e) {
Object eventSource = e.getSource();
if (eventSource instanceof JButton) {
JButton buttonClicked = (JButton) eventSource;
Color bg = buttonClicked.getBackground();
if (bg.equals(Color.white)) {
buttonClicked.setBackground(Color.yellow);
} else if (bg.equals(Color.yellow)) {
buttonClicked.setBackground(Color.white);
}
}
}
如果事件侦听器拾取的事件是单击有问题的按钮,则不需要遍历x和y:
@Override
public void actionPerformed(ActionEvent e) {
Object eventSource = e.getSource();
if (eventSource instanceof JButton) {
JButton buttonClicked = (JButton) eventSource;
Color bg = buttonClicked.getBackground();
if (bg.equals(Color.white)) {
buttonClicked.setBackground(Color.yellow);
} else if (bg.equals(Color.yellow)) {
buttonClicked.setBackground(Color.white);
}
}
}
你能举例说明你打算如何调用这个方法吗?(例如,您是否将按钮实例或
x
和y
整数传递给它)@khelwood对不起,我应该更清楚一些,我想这样做:按钮[x][y]。flipIt();在本例中,x和y是我的动作侦听器的一部分,因此它们会根据我在GUI中按下的按钮而变化。如果要在按钮本身上添加成员函数,则按钮必须是您自己编写的类的实例,该类应提供函数flipIt()
。在该函数中,按钮将是this
,而x
,y
将完全不被引用。Java不喜欢它吗?比如什么?:)你能举例说明你打算如何调用这个方法吗?(例如,您是否将按钮实例或x
和y
整数传递给它)@khelwood对不起,我应该更清楚一些,我想这样做:按钮[x][y]。flipIt();在本例中,x和y是我的动作侦听器的一部分,因此它们会根据我在GUI中按下的按钮而变化。如果要在按钮本身上添加成员函数,则按钮必须是您自己编写的类的实例,该类应提供函数flipIt()
。在该函数中,按钮将是this
,而x
,y
将完全不被引用。Java不喜欢它吗?比如什么?:)