Switching jPanels in Java from external class

2019-07-25 03:27发布

问题:

I have jFrame class MainForm which contains main(), placePanel(panel) and drop down menu. From the items in drop down menu I call on placePanel(panel) method to place a specific panel in the jFrame container. This works fine.

But, I don't know how to switch panels when I click on a button which is inside a jPanel class. When I try to call jFrame's MainForm.placePanel(panel) from any jPanel which is loaded into jFrame's container, I get the error: cannot reference non-static content etc. I also tried Mainform.getContainer().add(panel), but it doesn't work too.

I can't figure out how to access MainForm's container from another class, or how to switch panels with a method from another panel.

Thanks

回答1:

If you want to call a method on an object from within another object, you're going to need a reference to the first object so you can call the method on the active object itself and not on the class (as you're currently trying to do). One way to solve this is to pass a reference to the class that holds the JPanels to the class that has the button's action listener code, perhaps in the latter's constructor. In other words you'll want to pass a reference to the current active and visualized MainForm object into the class that has the ActionListener for the button.

By the way, are you swapping JPanels with a CardLayout? If not, I suggest you look into it as it's usually the easiest way to do this.

Edit:

For example, say you have a class called MainForm that has a public method called swapJPanels that allows it to swap views, and another class MyPanel that has your JButton that wants to call a method from the MainForm class, then you could give MyPanel a constructor that takes a MainForm parameter and allows you to pass a reference from the current MainForm object (this inside of the class), into the MyPanel object:

MainForm:

class MainForm extends JFrame { 

   public MainForm() {
      MyPanel myPanel = new MyPanel(this); // pass "this" or the current MainForm reference to MyPanel
   }

   public void swapJPanels(int panelNumber) {

   }
}

MyPanel:

class MyPanel extends JPanel {
   private MainForm myMainForm; // holds the reference to the current MainForm object

   public MyPanel(MainForm myMainForm) {
      this.myMainForm = myMainForm; // set the reference

      JButton swapPanelBtn = new JButton("Swap Panel");
      swapPanelBtn.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            swapPanelBtnActionPerformed();
         }
      });
   }

   private void swapPanelBtnActionPerformed() {
      myMainForm.swapJPanels(0); // calling a method on the reference to the current MainForm object
   }
}