I have question on how to detect an action invoked by a component in some class by the other class.

Say:

public class C1 extends JPanel {
  JButton button;
  C1() {
    button = new JButton();
    add(button);

    C1Action h = new C1Action()
    button.addActionHandler(h);
  }

  public void doSomething() {
    // code here
  }

private class C1Action implements ActionListener {
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == button) {
      doSomething();
    }
  }
}

while i have another class using the class above:

public class C2 extends JFrame {
  private C1 c1;
  public C2() {
    c1 = new C1();
    add(c1);
  }

  // this should be called when i clicked the button
  public evaluate() {
    // some more code here
  }
}

My question is, how can C2 detect invocation of button in C1Action in class C1 , via JPanel ?

I was thinking of sending C2 to C1 , but is it appropriate?

Recommended Answers

All 2 Replies

via additional ActionListener

public C2() {
        c1 = new C1();
        add(c1);
        c1.addMyListener(new MyAction());
    }

    private class MyAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            evaluate();
            System.out.println("MyAction " + e);
        }
    }

class C1:

public void addMyListener(ActionListener myAction) {
        // TODO add ....  listener
    }

via additional ActionListener

Got the idea. Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.