Amit
Amit

Reputation: 34735

Java Swing - How to access a JComponent of one JPanel from other JPanel, both added to the JFrame?

I am developing a Java Desktop Application with GUI implemented in SWING.

I hava a JFrame. I have added three JPanels on that. One JPanel panel1 has a Start Button. Now I want to disable various componets on other JPanels when a user presses the start button on the panel1.

Now how can I access the components of those other panels from panel1.

I know that one approach is to first get the container of panel1

panel1.getParent();

Then get the components of the container

container.getComponents();

and use them as per need.

Q1. Is there any other way by which I can perform the same task? (I think this is the only way)

Q2. After getting the components list of the container, how to differentiate one container with other?

Upvotes: 1

Views: 3158

Answers (4)

Marcus Adams
Marcus Adams

Reputation: 53830

You can make instance variables that reference the panels when you create them, and use those variables to reference the panels.

public class myFrame extends JFrame {
   public static JPanel buttonPanel;
   public static JPanel statusPanel;

   public static void main(String[] args) {
      buttonPanel = new JPanel();   
   }
}

Upvotes: 1

ZeissS
ZeissS

Reputation: 12135

I would add an ActionListener from outside to the Start Button:

StartPanel panel1 = ...
JPanel panel2 = ....

panel1.getStartButton().addActionListener(new ActionListener() { 
  public void actionPerformed(ActionEvent e) {
    setEnabledTree(panel2, false); 
  }
}

Upvotes: 1

Jim Kiley
Jim Kiley

Reputation: 3652

I'd probably have a separate layer of the application -- one that holds references to the various panels and the start button -- handle this action. So, when the start button is clicked, it calls a method on some kind of Controller object; the Controller object, which has references to the other JPanels, disables the other components.

Upvotes: 1

dominic
dominic

Reputation: 468

I'd pass references to the other panels into the panel with the start button. Or simply have a method in the container which does exactly what you want and make a call to it.

Upvotes: 0

Related Questions