How to change card layout panels from another panel?

泄露秘密 提交于 2019-11-28 05:33:19

It's all about exposing the right methods and constant Strings to the outside world to allow the class to swap views itself. For example, give your first class a private CardLayout field called cardlayout and a private JPanel field called cards (the card holder JPanel), and some public String constants that are used to add your card JPanels to the cards container. Also give it a public method, say called public void swapView(String key) that allows outside classes to swap cards... something like so:

// code corrected
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Registration extends JPanel {
   // use these same constants as button texts later
   private static final Dimension PREF_SIZE = new Dimension(450, 300);
   public static final String USER_AGREEMENT = "User Agreement";
   public static final String USER_INFO = "User Information";
   public static final String ENROLLMENT = "Enrollment";
   // we'll extract them from this array
   public static final String[] KEY_TEXTS = {USER_AGREEMENT, USER_INFO, ENROLLMENT};
   private CardLayout cardlayout = new CardLayout();
   private JPanel cards = new JPanel(cardlayout);

   public Registration() {
      cards.add(createUserAgreePanel(), USER_AGREEMENT);
      cards.add(createUserInfoPanel(), USER_INFO);
      cards.add(createEnrollmentPanel(), ENROLLMENT);
      setLayout(new BorderLayout());
      add(cards, BorderLayout.CENTER);
   }

   @Override
   public Dimension getPreferredSize() {
      return PREF_SIZE;
   }

   private JPanel createEnrollmentPanel() {
      JPanel enrol = new JPanel();
      enrol.add(new JLabel("Enrollment"));
      return enrol;
   }

   private JPanel createUserAgreePanel() {
      JPanel userAgree = new JPanel();
      userAgree.add(new JLabel("User Agreement"));
      return userAgree;
   }

   private JPanel createUserInfoPanel() {
      JPanel userInfo = new JPanel();
      userInfo.add(new JLabel("User Information"));
      return userInfo;
   }

   public void swapView(String key) {
      cardlayout.show(cards, key);
   }

}

Then an outside class can swap views simply by calling the swapView on the visualized instance of this class, passing in the appropriate key String such as in this case CardTest.USER_INFO to show the user info JPanel.

Now you have a problem with this bit of code where I indicate by comment:

    jButtonAgree.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent e) {
            Registration reg = new Registration(); // **** HERE *****
            LayoutManager cards = reg.getCards().getLayout();
            ((CardLayout) cards).show(reg.getCards(),"step1");
        }
    });

On that line you're creating a new Registration object, probably one that is completely unrelated to the one that is visualized on the GUI, and so calling methods on this new object will have absolutely no effect on the currently viewed gui. YOu need instead to get a reference to the viewed Registration object, perhaps by giving this class a getRegistration method, and then call its methods, like so:

class OutsideClass {
   private Registration registration;
   private JButton jButtonAgree = new JButton("Agree");

   public OutsideClass() {
      jButtonAgree.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            // make sure registration reference has been obtained first!
            if (registration != null) { 
               registration.swapView(Registration.USER_AGREEMENT);
            }
         }
      });
   }

   // here I allow the calling class to pass a reference to the visualized
   // Registration instance.
   public void setRegistration(Registration registration) {
      this.registration = registration;
   }
}

For example:

@SuppressWarnings("serial")
class ButtonPanel extends JPanel {
   private Registration registration;

   public ButtonPanel() {
      setLayout(new GridLayout(1, 0, 10, 0));
      // go through String array making buttons
      for (final String keyText : Registration.KEY_TEXTS) {
         JButton btn = new JButton(keyText);
         btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               if (registration != null) {
                  registration.swapView(keyText);
               }
            }
         });
         add(btn);
      }
   }

   public void setRegistration(Registration registration) {
      this.registration = registration;
   }
}

and the MainClass that drives this all

class MainClass extends JPanel {
   public MainClass() {
      Registration registration = new Registration();
      ButtonPanel buttonPanel = new ButtonPanel();
      buttonPanel.setRegistration(registration);

      buttonPanel.setBorder(BorderFactory.createTitledBorder("Button Panel"));
      registration.setBorder(BorderFactory.createTitledBorder("Registration Panel"));

      setLayout(new BorderLayout());
      add(registration, BorderLayout.CENTER);
      add(buttonPanel, BorderLayout.SOUTH);
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("Registration");
      frame.getContentPane().add(new MainClass());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!