2016-04-18 65 views
0

我想弄清楚如何在JButton上創建一個JButton的actionListner,這是從JButton的一個arrayList創建的。如何將一個ActionListener放在用Jbuttons的ArrayList創建的JButton上

這裏是按鈕的數組列表:

public static ArrayList<JButton> myTests; 
    public static ArrayList<JButton> selectedTests; 

這裏的邏輯設置起來:

public Devices(String[] testList, String title2) 
    { 
     myTests = createTestList(testList); 
     selectedTests = new ArrayList<JButton>(); 
     checkedSerialNo = new ArrayList(); 
     int numCols = 2; 

     //Create a GridLayout manager with 
     //four rows and one column 
     setLayout(new GridLayout(((myTests.size()/numCols) + 1), numCols)); 

     //Add a border around the panel 
     setBorder(BorderFactory.createTitledBorder(title2)); 
     for(JButton jcb2 : myTests) 
     { 
      this.add(jcb2); 
     } 

    } 

    private ArrayList<JButton> createTestList(String[] testList) 
    { 
     String[] tests = testList; 
     ArrayList<JButton> myTestList = new ArrayList<JButton>(); 
     for(String t : tests) 
     { 
      myTestList.add(new JButton(t)); 
     } 
     for(JButton jcb2 : myTestList) 
     { 
      jcb2.addItemListener(this); 
     } 
     return myTestList; 
    } 

    @Override 
    public void itemStateChanged(ItemEvent ie) 
    { 
     if(((JButton)ie.getSource()).isSelected()) 
     { 
      selectedTests.add((JButton) ie.getSource()); 
     } 

    } 



    public ArrayList<JButton> getSelectedTests() 
    { 
     return selectedTests; 
    } 

什麼我不知道的是如何使對所產生的actionListner或onClickListener數組列表中的按鈕。

任何洞察力和幫助表示讚賞。

謝謝!

ironmantis7x

回答

2

那麼最簡單的方法是創建一個內部的私有類。

private class MyTestListener implements ActionListener { 

    public void actionPerformed(ActionEvent e) { 
    // stuff that should happen 
    } 
} 


private class SelectedTestListener implements ActionListener { 

    public void actionPerformed(ActionEvent e) { 
    // stuff that should happen 
    } 
} 

私有類需要在同一個java文件中(您使用ArrayLists的地方)。 一旦你創建了類,你只需添加動作偵聽器。

MyTestListener handler = new MyTestListener(); 

//Inside the for-each 
button.addActionListener(myListener); 

如果你只需要1監聽器(用於一點鍵式是;喜歡和ItemStateListener)只是定義一個私有類用合適的名字,並將其與上面提到.addActionListener功能添加到按鈕在foreach

祝您有美好的一天

相關問題