我有一个 JLabel,上面有按键绑定(bind)操作。我已经为某些操作定义了一些代码,但是,唉,方法中还有其他 JLabels、JPanel 和其他东西(这是在 main() 中),我希望我的操作能够愚弄它们。
我尝试将操作更改为接受参数,但没有成功,如何让我的操作接受参数进行操作?有什么办法吗?我已经查看过,但这非常具体,而且我没有看到几个好的例子。
这是我的代码的一个很好的部分:
/*Bunch of stuff I want my actions to interact with above - another JLabel, a JPanel*/
ImageIcon cursor = new ImageIcon("cursor.gif");
JLabel cursorlbl = new JLabel("", cursor, JLabel.CENTER);
Action goRight = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("lol");
}
};
Action goLeft = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("lol2");
}
};
Action goUp = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
}
};
Action goDown = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("lol2");
}
};
cursorlbl.setFocusable(true);
cursorlbl.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"),
"pressed right");
cursorlbl.getInputMap().put(KeyStroke.getKeyStroke("LEFT"),
"pressed left");
cursorlbl.getActionMap().put("pressed right", goRight);
cursorlbl.getActionMap().put("pressed left", goLeft);
最佳答案
您可以将每个操作声明为子类(无论如何,这都会开始分离 MVC),并且您想要操作父类中的字段的每个项目。示例:
// Parent Class
public class ParentClass{
//Field you want to mess with in your action
JLabel cursorlbl = new JLabel("");
// Action that does things
public class MoveAction extends AbstractAction{
char direction;
//Constructor for action
public MoveAction(char direction){
this.direction = direction;
}
@Override
public void actionPerformed(ActionEvent arg0) {
int change = 0;
// Figure out how you'll be changing the variable
if(direction == 'u' || direction == 'r'){
change = 1;
} else{
change = -1;
}
// Apply the change to the correct variable
if(direction == 'u' || direction =='d'){
cursy += change;
} else{
cursx += change;
}
//Example how you can access the parent class's fields
cursorlbl.setLocation(cursx, cursy);
}
}
}
然后要设置您的操作,您只需创建子类的实例:
contentArea.getActionMap().put("pressed right", new MoveAction('r'));
contentArea.getActionMap().put("pressed left", new MoveAction('l'));
关于java - 获取我的操作以查看我的其他对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11457404/