[英]Using getSource for actions on components of unknown types
我想跟蹤按特定順序單擊的特定組件。
我正在使用getSource和像這樣的標志:
public void actionPerformed(ActionEvent e) {
JButton q = (JButton)e.getSource();
JRadioButton w = (JRadioButton)e.getSource();
if (q.equals(mybutton)) {
if (flag == false) {
System.out.print("test");
flag = true;
}
}
這對於JButtons完美地起作用,問題在於也將它用於JRadioButtons。 如果我在兩者上都使用getSource,請單擊一個按鈕,這將導致強制轉換異常錯誤,因為該按鈕無法強制轉換為Radiobutton。
我該如何解決此問題?
您可以使用==
比較引用,因為引用不會更改。
if(e.getSource() == radBtn1){
// do something
}
我過去曾經使用過它,對我來說它就像是一種魅力。
至於類強制轉換問題,您需要使用instanceof
檢查事件源屬於哪個類。 如果原因是JButton
而您盲目地將其JRadioButton
為JRadioButton
,則將導致異常。 你需要這個:
Object source = e.getSource();
if (source instanceof JButton){
JButton btn = (JButton) source;
} else if (source instanceof JRadioButton){
JRadioButton btn = (JRadioButton) source;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.