同じクラスにリスナーを書くのは OOP 方式ではないと思います。そこで、リスナーを別のファイルに書き込もうとします。
動作するコードは次のとおりです。
class MyPanel extends JPanel{
private String tString = "Test String";
private JLabel tLabel;
public MyPanel(){
tLabel = new JLabel("Label");
JButton tButton = new JButton("Click me");
tButton.addActionListener(new ActionListener(){
public void ActionPerformed(ActionEvent e){
tLabel.setText(tString);
}
});
}
しかし、リスナーを別のファイルに書くと:
public class MyListener implements ActionListener{
copy code here
}
変更する
tButton.addActionListener(new ActionListener(){
に
tButton.addActionListener(new MyListener());
うまくいきません。もちろん、私はさまざまな組み合わせを試しました。
たとえば、"this" をリスナーのコンストラクターに送信し、受信したオブジェクトからリスナーのクラスでメソッドを呼び出します。
エラー:
MyListener: cannot find symbol "tLabel"