javaintellij-ideapanels

new panel but same window?


I am currently building a GUI that would give people the option to buy/sell(send/receive basically). What i am trying to achieve is to have the user click on the buy/sell and when they do click on that button it shows new information.

For example. The user clicks on buy, it will bring them to a new panel with a new label new button and etc. I dont want a new window but to have the current window replaced.

public class GuiTest {
    private JButton btnpurchase;
    private JPanel panelMain;
    private JButton btnrefund;

    public GuiTest() {
        btnpurchase.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog(null,"Buying stuff.");
                purchasecontent();
            }
        });
        btnrefund.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog(null,"Refunding stuff.");
                refundcontent();
            }
        });
    }
    public static void purchasecontent(){
        //enter the amount of the purchase

    }
    public static void refundcontent(){

    }
    public static void main(String[] args){
        JFrame frame = new JFrame("GuiTest");
        frame.setContentPane(new GuiTest().panelMain);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setSize(480,320);
        frame.setVisible(true);
    }
}

As you can see in the purchasecontent() function i am trying to have it execute but within the same window.

I am currently using the IntelliJ IDE and is using the form designer.


Solution

  • First, you must avoid to call static methods from your listeners :) It's a bad practice.

    In order to implement things easily, your GuiTest has to inherit from JPanel, consider it as your main panel.

    To replace the content, get the frame using :

    JFrame frame = (JFrame) SwingUtilities.getRoot(component);
    

    and set the new content, for example :

     btnrefund.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e) {
                  JFrame frame = (JFrame) SwingUtilities.getRoot(component);
                  frame.setContentPane(new RefundPanel());
                }
            });
    

    RefundPanel is supposed to be the panel you want to set in your frame...