2017-03-22 107 views
0

一直在此停留一段時間,並在思考了一下搜索後發現我找不到的東西會詢問是否有人對我的問題有解決方案。目前,我正在研究一個小型拼貼項目,我需要一個包含100個按鈕的面板,但每個按鈕都必須有一個動作偵聽器。選擇此動作偵聽器時,必須在網格中報告其編號並更改按鈕的文本。ArrayList <JButton>使用ArrayList添加Action偵聽器

for (int i = 0; i < 100; ++i) //Sets buttons created 
    { 
     ArrayList<JButton> testButton = new ArrayList<JButton>(); //Button Text 
     PlayerGrid1.add(new JButton(" ? ")); 
    } 

的代碼是我如何添加按鈕到ArrayList,但我遇到的問題是,當我嘗試添加一個動作監聽,它拋出關於抽象的按鈕和其他問題的錯誤。

JPanel PlayerGrid1 = new JPanel(); 
    PlayerGrid1.setBackground(Color.WHITE); 
    PlayerGrid1.setBounds(0, 0, 375, 400); 
    frmBattleships.getContentPane().add(PlayerGrid1); 
    PlayerGrid1.setLayout(new GridLayout(10, 10, 0, 0)); 

這是我存儲按鈕的網格。

如果有人知道如何將偵聽器添加到ArrayList中,或者鏈接到使用與我相同的方法的某個人的帖子,那麼將不勝感激。也只是爲了讓任何人知道,如果這沒有正確或錯誤設置請不要火焰我通常不會問許多堆棧溢出的問題。謝謝。

回答

0

之前定義的地圖,而不是列表循環,如:

Map<String,JButton> buttonMap = new HashMap<String,JButton>(); 

之後,你應該在for循環爲每個按鈕設置獨特的動作命令「我」可以用於這一目的。

for (int i = 0; i < 100; ++i) //Sets buttons created 
{ 
JButton button = new JButton(); 
button.setActionCommand(String.valueOf(i)); 
button.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       buttonMap.get(e.getActionCommand()).setText("Whatever you want!"); 
      } 
     }); 
buttonMap.put(String.valueOf(i), button); 
PlayerGrid1.add(button); 
} 
0

試試這個`

JFrame frmBattleships = new JFrame(); 
    JPanel PlayerGrid1 = new JPanel(); 
    PlayerGrid1.setBackground(Color.WHITE); 
    PlayerGrid1.setBounds(0, 0, 375, 400); 
    frmBattleships.getContentPane().add(PlayerGrid1); 
    PlayerGrid1.setLayout(new GridLayout(10, 10, 0, 0)); 
    for (int i = 0; i < 100; ++i) // Sets buttons created 
    { 
     ArrayList<JButton> testButton = new ArrayList<JButton>(); // Button 
     JButton newButton = new JButton("" + i); // Text 
     newButton.setName("" + i); 
     newButton.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       System.out.println(((JButton) e.getSource()).getName()); 

      } 
     }); 
     PlayerGrid1.add(newButton); 

    } 
    frmBattleships.setVisible(true); 

` 
相關問題