I need to write a program which has a JFrame with a number of JButtons on it. Each of the JButtons has an ActionListener. When any JButton is clicked, I need to somehow be able to use the text of the button that was clicked.
I wrote a short and simple sample to illustrate my issue, although perhaps I'm approaching the problem with a poor solution in general. Perhaps there's a better way to set it up than my array of JButtons? Or something?
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; class SampleProblem implements ActionListener { public static void main(String[] args) { JFrame frame = new JFrame("Sample Program"); frame.setLayout(new GridLayout(5,5)); JButton[] buttonArray = new JButton[25]; for (int i = 0; i < 25; i++) { buttonArray[i] = new JButton("foo"); buttonArray[i].addActionListener(new SampleProblem()); frame.add(buttonArray[i]); } frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { //THIS IS THE ISSUE: //System.out.print(e.getSource().getText()); } }
I tried "System.out.print(e.getSource().getText());" but that doesn't work. I seem to have misunderstood what "getSource" does...
Any assistance is greatly appreciated.