[英]Invoke method from ActionListener
我想要一個按鈕,當按下該按鈕時,將調用一個方法。 這是一些代碼
public class Tester extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
g.fillRect(10, 10, 10, 10);
}
//The method which I wand invoke but can't, I don't know why.
void setWidth(){
//width -= 10 ;
repaint();
}
public static void main(String[] args) {
//Here some JFrame...
Tester paint = new Tester();
frame.add(paint);
JButton click = new JButton("Click");
click.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
paint.setWidth();//Here I Want invoke that method
}
});
}
}
我希望ActionListener
會調用方法setWidth()
,但不會。 不知道為什么。
paint變量不在匿名ActionListener類的范圍內,請嘗試更改paint類以使其實現ActionListener接口,並使其實例成為“ Click”按鈕的動作偵聽器,還應將該按鈕附加到面板實例上,如下所示:
public class Tester extends JPanel implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
setWidth();
}
public static void main(String[] args) {
//Here some JFrame...
Tester paint = new Tester();
frame.add(paint);
JButton click = new JButton("Click");
paint.add(click);
click.addActionListener(paint);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.