Hi there,
Basically got a small problem with my action listener for a button within a JPanel.
I want to call a method from another class within the action listener however it does not work. Calling the function in the same way works outside of the action listener. I have tried instantiating the class containing the method however this still is not working.
Any help would be greatly appreciated, please see code below.
Thanks
SnakesAndLadders Class:
import javax.swing.*; import java.awt.*; import java.awt.image.*; import java.awt.event.*; public class SnakesAndLadders { public static void main(String[] args) { JFrame f=new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(450,450); final SnakesAndLaddersGUI gui=new SnakesAndLaddersGUI(); f.getContentPane().add(gui); f.setVisible(true); final Play play = new Play(); gui.setNumberOfPlayers(1); final int[]pos=new int[1]; for(int i=0;i<1;i++) { pos[i]=1; gui.setPosition(i,0); } try { Thread.sleep(1500); } catch(Exception e){e.printStackTrace();} JFrame frame = new JFrame("Network"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton roll = new JButton("Roll"); roll.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Play play = new Play(); System.out.println("Button Pressed"); play.roll(pos,gui); } }); frame.getContentPane().add(roll); frame.pack(); frame.setVisible(true); } }
Play Class:
public class Play { public int roll(int pos[], SnakesAndLaddersGUI gui) { try { int dice; Thread.sleep(500); for(int i=0;i<1;i++) { dice=(int)(Math.random()*6); while(dice>0) { gui.setPosition(i,pos[i]++); dice--; Thread.sleep(100); } } } catch(Exception e){e.printStackTrace();} return 0; } }