[問題] 按下button後讀取textfiled裡面的資料

看板java作者 (where are you?)時間16年前 (2009/12/18 10:57), 編輯推噓3(301)
留言4則, 3人參與, 最新討論串1/1
請問各為前輩 小弟我現在想要實現一個功能 就是按下某個button後 程式去讀取寫在textfield裡的內容 程式碼如下 void String test; JTextField field = new JTextField(); JButton button = new JButton("good"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { test = field.getText(); } }); compiler出線的錯誤是 Cannot refer to a non-final variable field inside an inner class defined in a different method 我查了些資料發現 匿名inner class中使用某個方法中的變數 必須宣告為final 想請問大家之前碰到這問題是都怎麼解決的 謝謝 ============================================================================= 剛剛有人指點 叫我用另一個class 去 implement aciontListener 不要用匿名inner class 概念如下 public class pushButton implements actionListener { String test; JTextField field; public pushButton(JTextField field, String test){ this.field = field; this.test = test; } public void actionPerformed(ActionEvent e){ test = field.getText(); field.setText(null); System.out.println(this.test); } } 主程式 void String test; JTextField field = new JTextField(); JButton button = new JButton("good"); pushButton a = new pushButton(field,test); button.addActionListener(a); 最後謝謝java版熱心的大家 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.228.168.251

12/18 11:26, , 1F
經過高手指點 已解決
12/18 11:26, 1F

12/18 11:27, , 2F
==.==== 阿你到底還想問什麼? 我不太懂......
12/18 11:27, 2F
※ 編輯: Flyingheart 來自: 61.228.168.251 (12/18 11:39)

12/18 12:06, , 3F
可以換寫作inner class AL impl. A.L.{}想想,而不是不用
12/18 12:06, 3F

12/18 12:22, , 4F
某種程度算是迴避問題,不算是正視那個錯誤訊息....
12/18 12:22, 4F
文章代碼(AID): #1BAk-tCG (java)