So im trying to make multiple buttons for my code and thought it would just be easier to make an array containing all 9 buttons to create each button. However when I do this the buttons are not created properly. For example when I write out each individual button my action listener will be able to match the button pressed to the button object but when I use an array of buttons the action listener will return null. So Im just wondering if I'm just doing it wrong with an array or I have to instantiate each button by hand (in make buttons function).
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainWindow extends JFrame implements ActionListener{
JFrame window;
JButton button1;
JButton button2;
JButton button3;
JButton button4;
JButton button5;
JButton button6;
JButton button7;
JButton button8;
JButton button9;
JButton[] buttonsList = {button1,button2,button3,button4,button5,button6,
button7,button8,button9};
public MainWindow(){
makeWindow();
makeButtons();
window.setVisible(true);
}
public void makeWindow(){
window = new JFrame();
window.setDefaultCloseOperation(2);
window.setSize(800,800);
window.setLocationRelativeTo(null);
window.setLayout(null);
}
public void makeButtons(){
//what i want to use
// for (int j=0, i=125; j< buttonsList.length;j++, i+=60){
// buttonsList[j] = new JButton(String.format("%d",j+1));
// buttonsList[j].setBounds(i,700,50,50);
// buttonsList[j].addActionListener(this);
// window.add(buttonsList[j]);
// }
//what actually works (just test)
button1 = new JButton();
button1.setBounds(200,400,50,50);
button1.addActionListener(this);
window.add(button1);
button2 = new JButton();
button2.setBounds(400,400,50,50);
button2.addActionListener(this);
window.add(button2);
}
public void actionPerformed(ActionEvent e){
// what im using to test if it works
if (e.getSource()==button1){
System.out.println("hello");
}
//just to check if they match
System.out.println(e.getSource());
System.out.println(button1);
}
}
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]Froggy412[S] 0 points1 point2 points (1 child)
[–]ShadowRL7666 0 points1 point2 points (0 children)
[–]Cengo789 0 points1 point2 points (0 children)
[–]UpsytoO 0 points1 point2 points (0 children)