Issue
Ok so im working on a game and right now i have an image and im trying to place buttons under the image in specific places so when the user clicks that part of the screen the image changes. I am having trouble trying to figure out how to format my program for the action listener.
public class TestJFrame{
private static JFrame frame = new JFrame();
private static JLabel label = new JLabel();
private static JButton buttons[] = new JButton[4];
private static int[][] location = new int[3][4];
public static void main(String args[]){
frame.getInsets().set(20, 5, 5, 5);
frame.setLayout(null);
frame.setPreferredSize(new Dimension(507, 528));
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Test");
buttons[0] = new JButton("jbZero");
buttons[1] = new JButton("jbOne");
buttons[2] = new JButton("jbTwo");
buttons[3] = new JButton("jbThree");
frame.add(buttons[0]);
frame.add(buttons[1]);
frame.add(buttons[2]);
frame.add(buttons[3]);
setButtons();
frame.setVisible(true);
buttons[0].setLocation(100, 100);
}
private static void setButtons(){
for (int i=0;i<=3;i++){
buttons[i].setSize(10, 10);
buttons[i].setLocation(0, 0);
buttons[i].setVisible(true);
}
}
public void intializeListener(){
buttons[0].addActionListener((ActionListener) this);
}
public void buttonsZeroActionPreformed(java.awt.event.ActionEvent e){
System.out.println("button zero works");
}
}
So any help would be greatly appreciated.
Solution
Depends what do you want to implement in the listener:
If they do the same action you implement the listener inside
setButtons
function:private static void setButtons(){ for (int i=0;i<=3;i++){ buttons[i].setSize(10, 10); buttons[i].setLocation(0, 0); buttons[i].setVisible(true); buttons[i].addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // listener implement btn 0 } }); } }
If each button need unique implementation I think that better implementation will be in a new function
setBtnListeners
and call it from your main after usingsetButtons();
:private static void setBtnListeners() { buttons[0].addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // listener implement btn 0 } }); }
Update: Sorry i'd just noticed you have four buttons... you can just add another one :)
Answered By - Ami Hollander
Answer Checked By - Cary Denson (JavaFixing Admin)