[JAVA][Swing]如何實作ActionListener
當使用者按下button會發出action event,通知ActionListener。
如何實作ActionListener有三步驟:
Step 1:
宣告事件(event handler)類別時,必須指定實作ActionListener介面或繼承已實作ActionListener介面類別。例如:
Step 2:
將事件類別登錄為一或多個元件的ActionListener。例如:
Step 3:
實作ActionListener介面所定義的methods。例如:
...//code that reacts to the action...
}
測試實作helloworld:
private JButton btn = new JButton("I'm a button");;
private TextField text = new TextField(20);
private int numClicks = 0;
public static void main(String[] args){
helloworld hw = new helloworld("Hello World App");
hw.setSize(200, 150);
hw.setLocation(250, 250);
hw.setVisible(true);
}
public helloworld(String pTitle){
super(pTitle);
setLayout(null);//不使用版面配置
btn.setBounds(20,40,140,20);
text.setBounds(20,60,140,20);
btn.addActionListener(this);
add(btn);
add(text);
}
public void actionPerformed(ActionEvent e) {
numClicks++;
text.setText("Button Clicked " + numClicks + " times");
}
}
測試結果:
參考資料:http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
新手發文請多多指教 ^_____^