按下按钮的名称是什么?

时间:2011-12-04 13:16:17

标签: java swing jbutton actionlistener

我有一个JButton数组并使用

生成100个按钮
 for(i=0;i<button.length;i++)

但无法弄清楚要放入什么作为e.getSource(),即if(e.getSource()== ????){}我将什么放入????。换句话说,如何在e.getSource的情况下找到在数组中创建的按钮的名称。

 import javax.swing.*;  
 import javax.swing.border.Border;
 import java.awt.Color;
 import java.awt.Font;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.util.ArrayList;
 import java.awt.*;
 import java.awt.event.*;

 public class map {
     static int i;
     JFrame frame = new JFrame("D&D");
     public map() {
        int a=0,b=50;
        JFrame.setDefaultLookAndFeelDecorated(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(100,0,1000,600);
        frame.getContentPane().setLayout(null);      
        frame.setVisible(true);
        frame.setBackground(Color.black);
        frame.setResizable(false);
        for(i=0;i<button.length;i++){
            a=a+50;
            if(a>549) {
                b=b+50;
                a=50;
            }
            button[i]= new JButton(SD);
            frame.getContentPane().add(button[i]);
            button[i].setBounds(a, b, 50,50);
            button[i].setFont(new Font("Blackmoor Let", Font.BOLD, 30));
            button[i].setForeground(Color.red);
            button[i].setBorder(border);
            button[i].addActionListener(boardListener);
      }
    }

    ActionListener boardListener = new ActionListener (){
        public void actionPerformed(ActionEvent e){
            System.out.print("\n" +e.getSource());            
            if (e.getSource()==button[i]){              
                System.out.println("hi");
            }
        }
    };

    public static void main(String[]args){
         new map();
    }
}

3 个答案:

答案 0 :(得分:2)

循环遍历Button数组:

for (int i = 0; i < button.length; ++i) {
    if (e.getSource()==button[i]);{
        System.out.println("Button " + i + " pressed");
    }
}

答案 1 :(得分:2)

使用List<JButton>而非JButton[]按住按钮,然后使用

 int index = listOfButtons.indexOf(e.getSource())

知道点击按钮的索引。

创建并填充列表:

List<JButton> listOfButtons = new ArrayList<JButton>(100);
for (int i = 0; i < 100; i++) {
    JButton button = ...;        
    listOfButtons.add(button);
}

如果你想将一个JButton数组转换为List<JButton>(但这里不需要),只需使用

List<JButton> listOfButtons = Arrays.asList(buttons);

答案 2 :(得分:1)

创建按钮时,请尝试以下操作:

button[i].setActionCommand(i);

当你得到ActionEven时,请尝试:

e.getActionCommand();

getActionCommand()方法将您的i作为字符串返回,因此您必须将其解析为int。