简体   繁体   中英

how to replace jpanel with anotherjpanel on jframe when button is clicked

I want the JPanel at the center of the frame to be replaced when the corresponding buttons present in the JPanel to the left of the frame are pressed. I am using cardlayout for replacing the panels in the center. here is the sample code that i used for changing panels on button click ,but it doesn't work. can anyone let me know whats wrong in the code.

Library extends JFrame

 Public Library(){
          Container container = getContentPane();
      container.setLayout( new BorderLayout() );
      setExtendedState(JFrame.MAXIMIZED_BOTH);

      banner = new BannerPanel();
      container.add(banner,BorderLayout.NORTH);

      MenuButtons = new MenuButtonPanel();
      container.add(MenuButtons,BorderLayout.WEST);

      SelectedButtonPanel = new SelectedPanel(container);

      setLocationRelativeTo(null);
      setVisible( true );
      init();

      setDefaultCloseOperation(EXIT_ON_CLOSE);
}

MenuButtonPanel extends JPanel and has multiple buttons in it. The inner class of it ButtonHandler implements hte actionListner for the buttons

 //inner class
   class ButtonEventHandler implements ActionListener {     
        public void actionPerformed( ActionEvent event ){

            SelectedPanel selectObj = new SelectedPanel();

            if("about".equals(event.getActionCommand()))
                {
                    selectObj.showReplacePanel("about");

                }
                else if("checkout".equals(event.getActionCommand()))
                {
                    selectObj.showReplacePanel("checkout");
                }
                else if("search".equals(event.getActionCommand()))
                {
                    selectObj.showReplacePanel("search");
                }

The SelectedPanel should display the replaced Jpanel in the center of the frame

    public SelectedPanel() {}

public SelectedPanel(Container framePane)
{
    addSelectedPanel(framePane);
}
public void addSelectedPanel(Container framePane)
{
    cardPanel = new JPanel();
    //set layout of panel
    cardPanel.setLayout(new CardLayout());
    cardPanel.setBorder(null);
    cardPanel.setForeground(new Color(0, 0, 0));
    //this.selObj = selObj;
            aboutPanel = new About();
            checkoutPanel = new Checkout();
            searchPanel = new Search();
                           cardPanel.add(aboutPanel,ABOUTBUTTON);
            cardPanel.add(checkoutPanel,CHECKOUTBUTTON);
            cardPanel.add(searchPanel, SEARCHBUTTON);
                             framePane.add(cardPanel, BorderLayout.CENTER);  }

The selectedPanel class also has method showReplacePanel() which is called in the actionPerformed of the buttonClick.

public void showReplacePanel(String selObj)
{
    System.out.println("cardlayout entered");
    CardLayout cl = (CardLayout)(cardPanel.getLayout());
    System.out.println("cardlayout entered");
    switch(selObj){        
    case "about":

        cl.show(cardPanel,ABOUTBUTTON);
                break;          
    case "search":
        //this.repPanel = searchPanel;
        cl.show(cardPanel,SEARCHBUTTON);
        break;
    case "checkout":
        cl.show(cardPanel,CHECKOUTBUTTON);
        //this.repPanel = checkoutPanel;
        break;

I created an example for you, take a look at the actionPerformed(ActionEvent e) method

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PanelSwap extends JPanel implements ActionListener {

    JPanel firstPanel = new JPanel();
    JPanel secondPanel = new JPanel();

    public PanelSwap() {
        super(new BorderLayout());
        firstPanel.setBackground(Color.RED);

        secondPanel.setBackground(Color.YELLOW);

        JButton swap1 = new JButton("SwapToYellow");
        swap1.addActionListener(this);

        JButton swap2 = new JButton("SwapToRed");
        swap2.addActionListener(this);

        firstPanel.add(swap1);
        secondPanel.add(swap2);

        add(firstPanel);
    }

    /** Listens to the buttons and perfomr the swap. */
    public void actionPerformed(ActionEvent e) {

        for (Component component : getComponents())
            if (firstPanel == component) {
                remove(firstPanel);
                add(secondPanel);

            } else {
                remove(secondPanel);
                add(firstPanel);
            }

        repaint();
        revalidate();
    }

    /**
     * Create the GUI and show it. For thread safety, this method should be
     * invoked from the event-dispatching thread.
     */
    private static void createAndShowGUI() {
        // Create and set up the window.
        JFrame frame = new JFrame("PanelSwap");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create and set up the content pane.
        JComponent newContentPane = new PanelSwap();
        newContentPane.setOpaque(true); // content panes must be opaque
        frame.setContentPane(newContentPane);

        // Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        // Schedule a job for the event-dispatching thread:
        // creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM