我有一个JLabel,它有关键字绑定的操作。我已经为一些Actions定义了一些代码但是,唉,还有其他JLabel,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);
答案 0 :(得分:2)
您可以将每个操作声明为子类(这会开始分离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'));
答案 1 :(得分:0)
将您希望在行为中看到的其他组件声明为final
。这将使行动看到它们。
更多信息here
答案 2 :(得分:0)
你应该能够像这样传递它们:
// note that the JLabel is now final
final JLabel cursorlbl = new JLabel("", cursor, JLabel.CENTER);
Action goRight = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println(cursorlbl.getText()); // has access to JLabel because it's scoped to the method/class
}
};
请注意,执行此操作可能会导致一些维护问题,您应该尝试记录未来开发人员可能不清楚的事情(以及从现在开始两周后您自己!)