[英]How can I change the value of a variable from inside an ActionListener in Java?
[英]Change Variable from the inside of a ActionListener
是否可以從ActionListener
內部更改變量?
我的意思是這樣的:
boolean test = false;
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
test = true;
}
});
我想在有人按下按鈕時將test
更改為true。
我不確定這是否對您有幫助,但是如果您使用動作偵聽器,我想您正在使用Java Swing API。 在這種情況下,您可能要擴展一個像JFrame
類的類或類似的東西,因此您可以使用以下代碼:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyFrame extends JFrame {
private boolean booleanToChange = false;
private JButton exampleButton;
public MyFrame() {
exampleButton = new JButton();
exampleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
//Access a member in anonymous class
MyFrame.this.booleanToChange = true;
}
});
}
}
而在這里為什么它必須是最終:)解釋希望這有助於有點
這可能就是您想要的??
private boolean booly = true;
private class WinkAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (booly){
booly = false;
}else {
booly = true;
repaint( );
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.