java - 如何识别单击哪个按钮并更改图片?

时间:2018-03-15 21:16:35

标签: java swing jbutton actionlistener

我有一个按钮数组,我需要将数据文件加载到该数组中,我已经这样做了,但是我需要确定单击了哪个按钮并更改了按钮的图片。例如,如果按钮上的文本是C或B,则将图像设置为A.png,如果为*,则将其设置为B.png 这就是我所拥有的:

JButton[][] button = new JButton[10][10];
public static void main(String[] args) {
     for (int i = 0; i < 10; i++) {
          for (int j = 0; j < 10; j++) {
               button[i][j] = new JButton("");
               button[i][j].setActionCommand("" + cpuBoard[i][j].getText());
               button[i][j].addActionListener(new game());
          }
     }
} 
// load a file of text into each button - already done so 

private static class game implements ActionListener {
     public void actionPerformed(ActionEvent event) {
           String action = event.getActionCommand();
           if (action.equals("C") || action.equals("B")) {
                event.setIcon(new ImageIcon("A.png"));
           } else (action.equals("*")) {
                event.setIcon(new ImageIcon("B.png"))
    }
}

1 个答案:

答案 0 :(得分:1)

ActionEvent存储事件发生的组件(事件的源)。在这种情况下,事件存储被单击的JButton。您可以使用getSource

来检索此信息
public void actionPerformed(ActionEvent event) {
    JButton clickedButton = (JButton) event.getSource();

然后在JButton实例上调用setIcon