Java: using actionlistener to call a function in another class for an object from this class

Basically, what I want to do is launch the start button to launch a method running in another class and act on another object.

My code for the listener:

button1a.addActionListener(new ActionListener() {
    public void actionPerformed (ActionEvent event) {
        // Figure out how to make this work
        //sim.runCastleCrash(); 
    }
} );

My code for another class:

public static void main(String[] args) {
    CastleCrash sim;
    sim = new CastleCrash();
}

and

public void runCastleCrash() {
    System.out.println("Castle Crash is beginning...");
    //Other method parts here to be added
}

I feel it may not be too hard, but I am missing a piece.

+5
source share
4 answers

One way to reference things in an anonymous class is with a keyword final:

  public static void main(String[] args) {
    final Object thingIWantToUse = "Hello";

    JButton button = new JButton("Click");
    button.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        System.out.println(thingIWantToUse);
      }
    });

    JFrame frame = new JFrame();
    frame.setLayout(new FlowLayout());
    frame.add(button);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }

Alternatively, you can access elements (variables or methods) of the closing type:

public class ActionListenerDemo2 {
  private final JFrame frame = new JFrame();
  private Object thingIWantToUse = "Hello";

  public ActionListenerDemo2() {
    JButton button = new JButton("Click");
    button.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        thingIWantToUse = "Goodbye";
        System.out.println(thingIWantToUse);
      }
    });
    frame.setLayout(new FlowLayout());
    frame.add(button);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    new ActionListenerDemo2().frame.setVisible(true);
  }
}
+3
source

, , .

( CastleCrash sim = new CastleCrash();), , - setter :

:

button1a.addActionListener(new ActionListener()
{

    public void actionPerformed (ActionEvent event)
    {
    //How to make this work ?
    //Like this:
    runCC();
    }
});

public void runCC()
{
    CastleCrash sim = new CastleCrash();
    sim.runCastleCrash();
}

:

public void runCastleCrash()
{   
    System.out.println("Castle Crash is beginning...");
    //Other method parts here to be added
}

, , !:)

+2

McDowell , ( ). , Sun Swing, , .

+1

- CastleCrash, ActionListener.

, JFrame -, JButton, , CastleCrash, Actionlistener.

- , , , GUI ( ). , , , , .

. http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html, SwingWorker, , .

0
source

All Articles