Stranko
Stranko

Reputation: 165

JFrame, removed and created JPanels

I have a JFrame in which I create and remove panels from external classes, problem is, when I move back and forth (delete and create panels several times, I don't want references to all the panels, all the data that should be passed on (frame and boolean [soon to be implemented]) will be in constructor) it moves whole content downwards.

I'm using GridBagLayout, perhaps that has some hidden issues. I don't want to use CardLayout, so please don't recommend it.

Why is it doing so and what should I do to stop it?

Code

deleteContract = new JButton("Usuń kontrakt");
        deleteContract.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {

                ACDeleteContract ACDeleteContract = new ACDeleteContract(frame);
                removeAll();
            add(ACDeleteContract);
            revalidate();
            repaint();
        }
    });
    deleteContract.setPreferredSize(new Dimension(200, 50));
    c.gridy = 2;
    menu.add(deleteContract, c);

    back = new JButton("Powrót");
    back.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
           ACMenu menu = new ACMenu(frame);
           removeAll();
           add(menu);
           revalidate();
           repaint();
       } 
    });

Upvotes: 2

Views: 143

Answers (1)

Stranko
Stranko

Reputation: 165

Well, Andrew Thompson guided me to the good path which I didn't want to take earlier.

For future generations a couple of hints :D.

To do in your frame

CardLayout cards = new CardLayout();
    JPanel cardPanel = new JPanel();
    cardPanel.setLayout(cards);

    ACReadContract ACReadContract = new ACReadContract(cards, cardPanel);
    //your external JPanel classes with arguments such as above
    ACMenu ACMenu = new ACMenu(cards, cardPanel);

    cardPanel.add(ACMenu, "Menu");
    cardPanel.add(ACReadContract, "ReadContract");
    //naming and adding them for easy moving between them

    //adding this to frame
    add(cardPanel);

In external classes (start of constructor, classes should extend JPanel)

private JPanel menu, cardPanel1;
private CardLayout cardLayout1;

public ACMenu(CardLayout cardLayout, JPanel cardPanel) {

    cardLayout1=cardLayout;
    cardPanel1 = cardPanel;

In action listeners in external class

cardLayout1.next(cardPanel1);

or

cardLayout1.show(cardPanel1, "ReadContract");

I hope I've helped a bit those that have similar problem.

Upvotes: 2

Related Questions