[問題] 物件陣列的某個物件當參數傳入事件後,怎麼讀到它的index?

看板java作者 (丁丁)時間15年前 (2009/05/02 22:35), 編輯推噓5(502)
留言7則, 6人參與, 最新討論串1/1
標題可能說得有點拗口 我宣告一個JButton的陣列,bb[0],bb[1],bb[2]... 全部都new完之後, 註冊bb[0] 即 bb[0].addActionListener(new bbHandler()); 按下bb[0]這個Button後,就會傳一個物件給e public class bbHandler implements ActionListener { public void actionPerformed(ActionEvent e) { //請問怎麼由e這個物件,去執行bb[0].setBackground(Color.red);呢 } } 查資料只查到用e.getSource().getClass(), 這樣會傳回「class javax.swing.JButton」。請問該怎麼使用到JButton裡的函數呢? (API上的getMethod()看不懂@@) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 124.6.13.94

05/02 22:44, , 1F
e.getSource() 去跟陣列作比對.. 不用 .getClass()
05/02 22:44, 1F

05/02 23:43, , 2F
我的習慣是額外setName, 在getName比較@@
05/02 23:43, 2F

05/03 01:51, , 3F
在new每個button時,利用setActionCommand()把陣列位置存入
05/03 01:51, 3F

05/03 01:53, , 4F
這樣e.getActionCommand()時就可知是誰被觸發了,給你參考
05/03 01:53, 4F

05/03 15:03, , 5F
e.getSource() 得到的就是被 click 的 JButton 物件
05/03 15:03, 5F

05/04 14:46, , 6F
((JButton)(e.getSource())).setBackground(Color.RED)
05/04 14:46, 6F

05/08 17:47, , 7F
謝謝你們
05/08 17:47, 7F
文章代碼(AID): #19_5eNm_ (java)