[英]Button actionlistener calls another action listener in the same class
I have a submit button (and an action listener) which checks if the number inserted into a Futoshiki puzzle is legal (checking a 2D array for duplications etc) 我有一个提交按钮(和一个动作侦听器),用于检查插入到Futoshiki拼图中的数字是否合法(检查2D数组是否重复等)
In another method I have the actual grid with an action listener that gets the numbers and inserts them into the 2D array. 在另一种方法中,我有一个带有操作监听器的实际网格,该监听器获取数字并将其插入2D数组。
JButton acction listener JButton acction侦听器
JButton isRight = new JButton("Check My Answer");
isRight.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!(puzzle.isLegal())) {
JOptionPane.showMessageDialog(FutoshikiFrame.this,
puzzle.getProblems(),
"You made a mistake!",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(FutoshikiFrame.this,
"YOU WIN!",
"YES THATS FINE",
JOptionPane.INFORMATION_MESSAGE);
}
puzzle.printProblems.clear();
}
});
Grid action listener 网格动作监听器
public void keyReleased(KeyEvent e) {
String getInsertedValue = Emptysquare.getText();
int getInsertedIntValue = Integer.parseInt(getInsertedValue);
setSquareValue(r, c, getInsertedIntValue);
System.out.print(getSquareValue(r, c));
}
Is there a way I can access the keyReleased action listener from the JButton so it basically "submits" the contents of the grid and then checks if its legal? 有没有一种方法可以从JButton访问keyReleased动作侦听器,以便它基本上“提交”网格的内容,然后检查其合法性?
当然,只需保留对该动作侦听器的引用并使用null
值调用keyReleased
方法,或者将keyReleased
的内容重构为自己的方法,然后从两个侦听器中调用此方法。
Although 2 other methods were given, here is an additional way you could go about it, but I'm not sure which would be best to use. 尽管给出了其他两种方法,但是这是您可以采用的另一种方法,但是我不确定哪种方法最好。
public class YourClass {
JButton isRight;
public YourClass() {
this.isRight = new JButton();
this.isRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
YourClass.this.isRight.getKeyListeners()[0].keyReleased(null);
//Other action related code
}
});
isRight.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
//Key related code
}
//Other required key listener methods
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.