Zargontapel
Zargontapel

Reputation: 298

Java button actions in multiple classes

Working in Java: I have a JFrame class, and separate classes for my two JPanels that are added to the JFrame. One of the JPanel classes has some buttons in it, which can interact with each other(when I click on one button, it can disable another button). However, I can't figure out how to get the button to call a method in the other JPanel (written in a separate class).

So, my program look like this:

JFrame

Any tips appreciated, thanks!

Upvotes: 3

Views: 2349

Answers (1)

Catchwa
Catchwa

Reputation: 5855

One way to do this is to pass an instance of (to use your terminology) Jpanel1 into Jpanel2. This doesn't have to be done in the constructor, you can have a setConnectedPanel(JPanel) method, for example.

Here's some code that demonstrates what you want to do:

MyFrame.java

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class MyFrame extends JFrame {

  public MyFrame() {
    ReactionPanel rp = new ReactionPanel();
    ActionPanel ap = new ActionPanel(rp);
    setLayout(new GridLayout(2, 1));
    add(ap);
    add(rp);
    pack();
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        new MyFrame();
      }
    });
  }
}

ActionPanel.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;

public class ActionPanel extends JPanel implements ActionListener {
  private ReactionPanel rp;
  private JButton button;

  public ActionPanel(ReactionPanel rp) {
    this.rp = rp;
    button = new JButton("Click");
    button.addActionListener(this);
    this.add(button);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if(e.getSource().equals(button)) {
      rp.react();
    }
  }
}

ReactionPanel.java

import javax.swing.JLabel;
import javax.swing.JPanel;

public class ReactionPanel extends JPanel {
  private JLabel label;

  public ReactionPanel() {
    label = new JLabel("PING");
    this.add(label);
  }

  public void react() {
    if(label.getText().equals("PING")) {
      label.setText("PONG");
    } else {
      label.setText("PING");
    }
  }
}

As you can see, I tend to override all of my JFrames/JPanels when I write Swing GUIs as I find it easier and more flexible but YMMV.

Upvotes: 6

Related Questions