user3344370
user3344370

Reputation:

Java Jbutton link to another JPanel. removeAll() jamming window

When I do this code the window seems to jam. I have 2 methods. A viewOne method which contains a button. When this is pressed I want to go to the viewAll method. They both have different JPanes. I know the link works by putting in a print line. However the

canvas.removeAll(); 

seems to jam the window. No buttons can be pressed and nothing happens. Without this line though, both Jpanes (viewOne and viewAll) appear side by side. I'm wanting to close the viewOne JPane and open the viewAll JPane when the button is pressed. Please see below for the code. (Please note, the indents are correct in code, have moved when copying here.)

public class Contacts extends JFrame
{
    public static Contacts cont;
    public static JFrame canvas;

public static void main(String[] args)
{
    cont = new Contacts();

    canvas = new JFrame("Contacts");
    canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    canvas.show();
    canvas.getContentPane().add(cont.viewOne());
    canvas.pack();
}

private JPanel viewOne()
{       
    JPanel viewOnePanel = new JPanel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    viewOnePanel.setPreferredSize(new Dimension(500,500));
    viewOnePanel.setBackground(Color.white);
    c.fill = GridBagConstraints.HORIZONTAL;
//button for back
    JButton back = new JButton("BACK");
    back.setForeground(Color.black);
    c.gridx = 0;
    c.gridy = 1;
    viewOnePanel.add(back, c);
    back.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        canvas.getContentPane().add(cont.viewAll());

        }});
    return viewOnePanel;
}



private JPanel viewAll()
{
    canvas.removeAll()
    JPanel viewAllPanel = new JPanel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    viewAllPanel.setPreferredSize(new Dimension(500,500));
    viewAllPanel.setBackground(Color.white);
    c.fill = GridBagConstraints.HORIZONTAL;

Therefore how can I fix this problem? Any help much appreciated. Thanks

Upvotes: 0

Views: 514

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

It looks like you're creating kludgy code, including code that needlessly re-creates components that already exist, that can be fixed easily and simply by just using a CardLayout. This will allow you to swap JPanels easily and cleanly, without muss or fuss.

The CardLayout Tutorial

Upvotes: 3

Related Questions