Results 1 to 2 of 2
  1. #1
    alisonchan30 is offline Member
    Join Date
    Apr 2010
    Posts
    1
    Rep Power
    0

    Default Update the JFrame after change the Content Pane

    Dear All, I would like to change the content pane after pressing
    a button by the
    method : frame.setContentPane(newcContentPane);

    However, I find that it doesn't work. The Frame appears to be "Frozen" after
    I pressed the button. Here is my code:

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

    public class Test{
    JFrame main;
    JPanel panel1;
    JPanel panel2;

    public Test(){
    main = new JFrame();
    panel1 = new JPanel();
    panel2 = new JPanel();
    JLabel label1 = new JLabel("hihihihiihhihi");
    panel1.add(label1);

    JLabel label2 = new JLabel("eeeeee");
    panel2.add(label2);

    JButton butt1 = new JButton("Change");
    butt1.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent evt) {
    main.setContentPane(panel2);
    }
    });
    panel1.add(butt1);

    main.setContentPane(panel1);
    main.setBounds(100,100,100,100);
    main.setVisible(true);
    }
    }

    in Main method, just call: new Test();


    Thanks a lot for your help~~

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Don't add a MouseListener to a JButton but rather use an ActionListener. And you'll want to tell the JFrame to re-layout its components (the validate() method I think will help with this) and to repaint itself:
    Java Code:
        JButton butt1 = new JButton("Change");
        // butt1.addMouseListener(new MouseAdapter() {
        // public void mouseClicked(MouseEvent evt) {
        // main.setContentPane(panel2);
        // }
        // });
        butt1.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            main.setContentPane(panel2);
            main.validate();
            main.repaint();
          }
        });

    Myself, I'd use a CardLayout to easily swap components rather than trying to do it manually.

    Also, please read my signature link about using code tags so that any code posted here will keep its formatting.

    Much luck and welcome to the forum!

Similar Threads

  1. Changing content pane of a JFrame?
    By dunafrothint in forum AWT / Swing
    Replies: 1
    Last Post: 03-11-2010, 10:21 PM
  2. Replies: 0
    Last Post: 02-21-2010, 11:51 AM
  3. Printing JFrame + it`s content
    By scana in forum AWT / Swing
    Replies: 1
    Last Post: 01-24-2010, 10:55 PM
  4. Change the shape of JFrame
    By kiki2009 in forum New To Java
    Replies: 4
    Last Post: 07-09-2009, 01:47 PM
  5. Replies: 3
    Last Post: 01-05-2008, 11:13 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •