确定调用事件处理程序的对象

时间:2014-06-10 12:27:48

标签: java swing events

我正在用Java编写一个程序,它有一个JButton数组,他们都需要使用相同的事件处理程序。问题是事件处理程序需要对每个按钮进行更改。因此,我需要能够确定调用事件处理程序并对其进行更改的对象。我已经搞砸了一段时间了。我在Google上搜索java get name of object calling event handler,但没有找到任何帮助。

这是我到目前为止所复制的所有额外程序代码的副本。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;
import java.*;

public class MyJavaProgram extends JFrame implements ActionListener
{
    // Buttons
    JButton[] buttonsArray = new JButton[20];

    public MyJavaProgram()
    {   
        // Fonts
        Font arial = new Font("Arial", Font.PLAIN, 25);

        for(int x = 0; x < buttonsArray.length; x++)
        {
            buttonsArray[x] = new JButton(Integer.toString(x + 1));
            buttonsArray[x].setFont(arial);
            buttonsArray[x].addActionListener(this);
        }

        // Get the content pane and set the layout.
        Container jPane = getContentPane();
        jPane.setLayout(new GridLayout(8, 10)); // (rows, columns)

        // JFrame general settings.
        setTitle("My Java Program");
        setSize(700, 500); // width, height
        setVisible(true);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE); // Without this, the program will continue running even if the X is clicked.

        // Add our stuff to the JFrame.
        for(int x = 0; x < buttonsArray.length; x++)
            jPane.add(buttonsArray[x]);
    }

    public void actionPerformed(ActionEvent e)
    {
        System.out.println("Event triggered by one of the 20 buttons.");
    }

    public static void main(String[] args)
    {
        MyJavaProgram programUI = new MyJavaProgram();
    }
}

1 个答案:

答案 0 :(得分:4)

这正是ActionEvent的{​​{3}}所针对的:

public void actionPerformed(ActionEvent e)
{
    JButton button = (JButton) e.getSource();
    System.out.println("Event triggered by " + button.getText());
}