Java: Используя actionlistener для вызывания функции в другом классе на объекте от того класса

Я отправил бы все в одном большом блоке как нижележащие слои в osi модель . Для этого Вы не должны волноваться о том, как большие блоки, которые Вы отправляете как слои, разделят их как necisarry.

6
задан APerson 28 June 2014 в 21:12
поделиться

3 ответа

One way to reference things in an anonymous class is using the final keyword:

  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 members (variables or methods) of an enclosing 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);
  }
}
4
ответ дан 11 December 2019 в 00:41
поделиться

Макдауэлл уже практически отвечает хорошими примерами того, как получить доступ к переменным из слушателей событий (или анонимных внутренних классов в целом). Однако существует более общий ресурс Sun по прослушивателям событий в Swing , который является каноническим и дает хороший обзор всех предостережений, которые следует учитывать при их написании.

1
ответ дан 11 December 2019 в 00:41
поделиться

Somehow you need a reference to your CastleCrash object available to call from your actionListener.

You probably want to subclass JFrame, or whatever is containing your JButton such that it has your both your main method and a CastleCrash property that can then be referenced from your anonymous inner class Actionlistener.

BUT - be careful, you look like you are calling what will be a long running method from within the GUI event thread (where the action listener will called). This is generally a bad idea, you will case your GUI to become unresponsive.

See http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html especially the bit on SwingWorker class for ideas on how to avoid that problem.

0
ответ дан 11 December 2019 в 00:41
поделиться
Другие вопросы по тегам:

Похожие вопросы: