[英]Java, problems with Action Listener
我在互聯網上看了一下,在理解動作聽眾方面找不到任何幫助。 我剛剛開始學習Java,我還沒有找到一個很好的教程來幫助我理解如何使用動作監聽器。 有人可以查看我的代碼或者指出一個有用的教程解釋如何使用動作偵聽器嗎?
public static void go implements ActionListener(){
JFrame j = new JFrame();
j.setDefaultCloseOperation(EXIT_ON_CLOSE);
j.setSize(640,480);
final Screen screen = new Screen();
j.add(BorderLayout.CENTER, screen);
JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener(){
public void ActionPerformed(Event e){
screen.repaint();
}
});
j.add(BorderLayout.NORTH, button);
j.setVisible(true);
}
其他方式和更好的方法是使用Anonymous類。 您不需要實現ActionListener
public static void go(){ // no need to implement actionListener
JFrame j = new JFrame();
j.setDefaultCloseOperation(EXIT_ON_CLOSE);
j.setSize(640,480);
final Screen screen = new Screen();
j.add(BorderLayout.CENTER, screen);
JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener(){ // change are made here
@Override
public void actionPerformed(ActionEvent e) { //& here
screen.repaint();
}
});
j.add(BorderLayout.NORTH, button);
j.setVisible(true);
}
actionPerformed
是一個接口方法,它不是一個類。
因此,使用actionPerformed的ActionPerformed,並使用注釋@Ovveride來移動actionPerformed以提供自己的定義。
@Override
public void actionPerformed(ActionEvent e) {
screen.repaint();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.