I have a JButton array and generate 100 buttons with
for(i=0;i<button.length;i++)
but can’t figure out what to put as the e.getSource() ie if(e.getSource()==????){} what do I put in the ????. In other words, how do I find what a button created in an array is named in the case of 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();
}
}
Use a
List<JButton>rather than aJButton[]to hold your buttons, and useto know the index of the clicked button.
To create and populate the list:
If you want to convert an array of JButtons into a
List<JButton>(but it’s not needed here), just use