2017-03-22 111 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); 

` 
相关问题