Swaping Panels in a frame?

Hey, I have a frame that has a GridLayout of (1,2) so it can jold 2 Panels of equal size, when I press a button i need the 2 Panels in there to go away so I can put new ones in. This is my code to add Panels:
public void addPanels()
         frame.getContentPane().setLayout(new GridLayout(1,2));
         frame.getContentPane().add(myLeftPanel);
         frame.getContentPane().add(myRightPanel);
     }And I have this one to switch Frames
     public void swapPanels(JPanel leftPanel, JPanel rightPanel)
         myLeftPanel = leftPanel;
         myRightPanel = rightPanel;
         addPanels();
     }I tried the remove(Component comp) meathod and it didn't work and I'v also tried the removeAll() but that didn't work either looks like it removed more then just the Panels because a can't add new ones. Any ideas?

You don't really need to set the content pane's layout each time. Set it once and it is always set. In your addPanels method, you need to call getContentPane().removeAll() then add each panel as you are currently doing then call getConentPane().revalidate().
public void addPanels() {
  Container contentPane = frame.getContentPane();
  contentPane.removeAll();
  contentPane.add(myLeftPanel);
  contentPane.add(myRightPanel);
  contentPane.revalidate();
}

Similar Messages

  • Hello everybody, Problem with Two panel in a Frame

    This is my first mail in this forum.I'm trying to learn java myself & have a problem in adding more than one panel in a JFrame.
    i should be able to add one panel which occupies 3/4 of a frame and another panel occupies the rest.
    Thanx in advance for anyone who helps me in sorting out this problem.

    You can use for example the GridLayout
    In your JFrame constructor, add lines below, it will add 2 colored panel in your frame
    Container container = getContentPane();
    container.setLayout(new GridLayout(1,2)); // 1 row, 2 cols
    JPanel panel1 = new JPanel();
    panel1.setBackground(Color.red);
    container.add(panel1);
    JPanel panel2 = new JPanel();
    panel2.setBackground(Color.green);
    container.add(panel2);

  • Adding a panel to a frame

    Hi! All,
    I'm new to java and i have a little problem here. I have created a frame and i want to put two panels inside it. well, i managed to put the first one, but i'm having problems with the second one. I want this second one to be added when I click on a button.
    The button that I will click is the new JButton i have defined. it is called draw. I really do not know what the problem is. I will apprecite any help. Below is my code.
    // My Code.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.util.*;
    public class Main extends JFrame {
    //all components I'll need
    public JButton draw;
    public JButton addFormula;
    public JButton modelCheck;
    /** Creates a new instance of Main */
    public Main () {
    super("Graphical Model Checker for Knowledge");
    //content pane is the main panel where i'll put everything
    JPanel contentPane = new JPanel();
    draw = new JButton("Draw");
    draw.addActionListener(
    new ActionListener() {         
    public void actionPerformed(ActionEvent event) {
    if(event.getActionComman().equals"Draw")) {               
    JPanel drawing = new JPanel();
    drawing.setBackground(Color.BLUE);
    drawing.setSize(100, 100);
    drawing.setLayout(new FlowLayout
    FlowLayout.CENTER));
    add("North", drawing);
    drawing.setVisible(true);
    contentPane.add(draw);
    addFormula = new JButton("Add Formula");
    contentPane.add(addFormula);
    modelCheck = new JButton("Model Check");
    contentPane.add(modelCheck);
    Canvas canvas = new Canvas();
    canvas.setSize(40, 40);
    canvas.setBackground(Color.white);
    contentPane.add(canvas);
    repaint();
    //add panel to the frame
    add("South", contentPane);
    //colours for window
    contentPane.setBackground(Color.yellow);
    //set layout manager
    contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));
    addWindowListener(new CloseWindow());
    pack();
    setVisible(true);
    String [] fileItems = {"Open", "Save", "Rename"};
    String [] editItems = {"Copy", "Cut", "Paste"};
    //instantiate a menu bar object
    JMenuBar bar = new JMenuBar();
    JMenu file = new JMenu("File");
    for (int index=0; index != fileItems.length; index++)
    file.add(fileItems[index]);
    bar.add(file);
    setJMenuBar(bar);
    JMenu edit = new JMenu("Edit Graph");
    for (int index=0; index != editItems.length; index++)
    edit.add(editItems[index]);
    bar.add(edit);
    setJMenuBar(bar);
    public static void main(String args []) {
    JFrame window = new Main();
    }

    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.
    add("North", drawing); The "North" means nothing when adding a component to a panel using a FlowLayout. You should just be using:
    add( drawing );After you add the component to the container you need to use:
    frame.validate();

  • Display 3 Panels in one frame.....

    Hi
    I need to display 3 different panels in one frame.
    The first panel will contain a JXTreeTable [North]
    The second Panel will contain a Tree [Center]
    The third Panel will contain a JXTreeTable [South]
    I am unable to get this working as the components to be displayed
    are not being placed properly.
    The JXTreeTable is being displayed only at the NORTH.
    Is it better to create 3 different panels or create just one panel with GridLayout(as I have done)
    Have I overlooked something in the code below?
    Thnx
    This is my code:
    public class PositionCostingView {
         public PositionCostingView(){
              initComponents();
         private void initComponents(){
              final JFrame frame = new JFrame("Position Costing");
              frame.setPreferredSize(new Dimension(450, 300));
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // First,testing my model
              TreeTableModel model = new OpTreeTableModel();
              JXTreeTable treeTable = new JXTreeTable(model);
              // Add the TreeTable to a Scroll Pane.
              JScrollPane scrollPane = new JScrollPane(treeTable);
              JPanel players = new JPanel(new GridLayout(3, 0));
              players.add(scrollPane);
              players.add(MyTree);
              players.add(scrollPane);
              JPanel content = new JPanel();
              content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
              content.add(players);
              frame.getContentPane().add(content);
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              new PositionCostingView();

    Please ignore my code on top.I am trying something else.....
    No offence meant please.

  • Sizing two panels in a frame

    Hi,
    i would like to set the size of two panels which are next to each other in a frame.
    The left one should be about 5 times wider than the one on the right.
    splitPane.setPreferredSize(new Dimension(1000,500));This one is not working.
    Thx:
    james

    SplitPane is my right panel in the frame, this should
    be 5x wider than the right panel, It should be 5x wider than itself?
    So it is nothing to do with Splitpane, the problem is
    that 1 add the splitpane and the buttonPanel to
    mainPanel, and these 2 panels are which are added are
    the same wide!You should have posted a Short,Self Contained, Compilable and Executable, Example Program.

  • Make a square Panel inside a Frame (awt)

    Hi all. I have a Frame that contains an panel.
    The Frame has BorderLayout and panel is positioned Center in it, occuping all the space. However I want the Panel to be perfectly square.
    The Panel MUST have LayoutManager(null).
    If I call setSize(100,100) on Frame, the Frame incorporates the height to include the Windowsbar on top, and then the Panel won't be square.
    If I call SetSize(100,100) on Panel, the Frame don't display anything else than the Windowbar.
    How can I solve this? Am I missing something important?

    One more question please noah....
    My applet i dependent on the square panel like I said. However it is important that the applets Frame can be resized, but its panel must still be sqaure.
    My code goes as follows:
    class Spanel extends Frame{
        panel.setBackground(Color.red);
        panel.setLayout(null);
        panel.setSize(200,200);
        add("Center",panel);
        pack();
        show();
    this.addComponentListener(new java.awt.event.ComponentAdapter() {
          public void componentResized(ComponentEvent e) {
            int x = calculateFrameSize(e);
            panel.setSize(x,x);
            pack();
            show();
    calculateFrameSize() {
    // only returns the lowest number of
    //getWidth() and getHeight()
    }This code however will go in an infinite loop, calling
    COmponentResized over and over.
    How can I avoid the loop?

  • Passing data from a panel to a frame / disposing of a frame from in a panel

    Hello, I have recently created a program where all windows are made of seperate frames, now, to make the whole thing a bit more appealing and professional looking, i'd like to make 1 main frame, and load my content panels into this 1 frame. Problem i'm having with this is passing data from the loaded in panel to the main frame, so the main frame can hide one panel to load another with data inserted in the first panel. OR another solution to my problem would be a way to dispose of a frame, but from within the seperate panel class. I have searched the www for a solution, but haven't found one so far, so, any suggestions or references to some info about this kind of issue? Any pointer is greatly appreciated

    kennethdm wrote:
    EDIT: I took a look at the cardlayout, and, although i see its relevance to my question, it still leaves me with the question how exactly i will pass data the user inputs into the first panel, to the second panel. The second panel is built by the info which is provided in the first panel.Stop thinking of them as Panels and start thinking of them as OOP objects that have data that must be shared. It's often a matter of using getters and setters and sometimes requiring a sprinkling of the Observer design pattern.

  • Strange problem loading panels in a Frame

    Hi,
    My Frame has a splitpane which has 2 Jpanels with in it. When I run my application using JWS, the frame and the splitpane show up but with nothing in it. All the class files that I'm using are all in the same package and they are all in the jar file. I do not get any null pointer exceptions too. I looked at couple of examples (Rachel's etc) and theres nothing different that I'm doing. I've been pulling my hair for past couple of days figuring out this stuff, if any one has any clue, please .... let me know. Thank You
    Viplavi

    Does it work as a stand-alone app?
    It may help you to post the code where you add the panels to the splitpane and where you display the gui etc...
    Gavin

  • Changing a panel in a frame at runtime

    I have a frame setup with buttons on the BorderLayout.WEST area. Now for each clicked event those buttons generate I want to add a panel to the SOUTH area depending on which button was pressed.
    I have all the action listeners setup, and when a button is clicked the following code is executed
    getContentPane().add(new buttonPanel(),BorderLayout.SOUTH)
    The code seems to be executing but nothing will show up in my JFrame.....
    The buttonPanel object works and if I add to the SOUTH section during design time it will show up ok. But I need to be able to change this panel to buttonPanel2() whenever the user clicks the appropriate button...

    okay that worked, the correct panels will come up, but when I click on one of the buttons that was just created, one of the previous buttons will come onto the foreground. Do I need to destroy the previous panel?
    and if so, how do i do that generically? So that I can destroy any object in the BorderLayout.SOUTH region.

  • Changing panels on a frame depending on what the user clicks

    I'm making a small application with a JFrame and some JPanels.
    When the application starts a start panel is added to the frame where the user can press two buttons. If he presses a button, then a new panel must be painted on the frame. In the new panel there is a button for going back to the starting panel.
    How can I accomplish this changing of panels? How does one panel give control to another panel? How can I let the frame control everything (if I should do that)?

    I guess just use CardLayout, CardLayout will solve your problem

  • Call function from action panel in second frame

    I am starting to learn Adobe Flash. I'm using Flash CS6.
    I have a file called test.fla and another called bikertest.as
    Bikertest has this code:
    package as3.grey{
    import com.grey.utils.Console;
    //import com.grey.utils.ClickTag;
    import flash.display.MovieClip;
    import com.greensock.TweenNano;
    import com.greensock.easing.*;
    import flash.events.*;
    public class bikertest extends MovieClip {
    private var mc:MC;
    private var console:Console; 
    public function ray():void{
    init();
    trace("hi from here");
    mc=new MC 
    ; addChild(mc);
    I tried:
    import as3.grey.bikertest.as; 
    var t = new bikertest(); 
    t.ray();
    I want to be able to call ray() from the Action Panel in the second frame in test.fla . I hope this is clear. How can I do that? /Thanks!

    assuming your fla is in a super directory of as/grey and everything in bikertest is defined, use:
    import as3.grey.bikertest;
    var t:bikertest=new bikertest();
    t.ray();

  • In the Animation Timeline panel menu "create frames from layers" is not showing.

    I am watching a tutorial on basic animation and when it gets to the point where they say to open the "Animation Timeline Panel Menu" the panel that opens for me is not the same one in the tutorial.  I am supposed to click on "create frames from layers" but that is not an option.  I'm confused as to why my panel is not the same as the one in the tutorial.

    It could be that you are using a different version of photoshop. Some of the older versions were split into two versions a standard version and an extended version, in most of those versions, it was required to have the extended version to use video editing features.
    Perhaps you could tell us what version of photoshop you have and what operating system.

  • Resize panels in a frame

    Hi, I tried searching through the forums, but am obviously using the wrong search words.
    I have a JFrame with a JPanel in it. The JPanel is using the following layout:
    new BoxLayout (parentPanel, BoxLayout.LINE_AXIS)
    Then I added two JPanels to the parentPanel.
    But then I would like to click and drag the separator between the two panels to change the size of the two JPanels.
    Any hints?
    Thanks,
    Novice

    As it turns out I should have been looking at the JSplitPane class.
    Novice

  • Creating multiple panels in one frame

    Greetings,
    As a newbie, I am sure you all have been in my place at one time or another so I will skip right to the meat of what I am trying to do.
    I originally started out with GridBagLayout() and placing all my code in the main function declaration but that has it's limits.
    I am trying to find a way to mount / add multiple panes onto one JPanel using functions in order to break up the code. I don't get an error when I compile, but the screen appears blank which tells me that I am adding one JPanel onto another in the wrong manner.
    class PanelTest extends JFrame
      private JPanel mainPanel;
      private JPanel headerPanel;
      public void PanelTest()
        mainPanel = new JPanel(new BorderLayout());
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        mainPanel.setPreferredSize(new Dimension(400, 100));
        mainPanel.add(topPanel(), BorderLayout.NORTH);
        getContentPane().add(topPanel());
      private JPanel topPanel()
        headerPanel = new JPanel ();
        headerPanel.setPreferredSize(new Dimension (300, 50));
        headerPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("Header Image"),
                BorderFactory.createEmptyBorder(5,5,5,5)));
        JLabel text = new JLabel("TEST");
        headerPanel.add(text);
        return headerPanel;
    }I then use the following code in my main file to call and execute the code
    class BerylMain extends JFrame
      public static void main(String args[])
         PanelTest panelTest = new PanelTest();
         panelTest.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
         panelTest.setSize(500, 400);
         panelTest.setVisible(true);
    }I appreciate any advise on this.

    public void PanelTest()  {
        /* try commenting this.
        mainPanel = new JPanel(new BorderLayout());
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        mainPanel.setPreferredSize(new Dimension(400, 100));
        mainPanel.add(topPanel(), BorderLayout.NORTH);
        getContentPane().add(topPanel());
    }

  • How do i put an array of panels into a frame with a flow layout?

    I just want to have my array of Jpanels displayed in a Jframe with a flow layout, how do i do this?
    thanks

    saru88 wrote:
    The problem is:
    cards.setBackground(Color.red);
    No, the real problem was before that. I saw SD before the stack trace in your original code, but the code 'ignored' that and continued on to the second exception you saw.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MemoryFrame extends JFrame{
         private CardPanel[] cards;
         final int noCards = 24;
         public MemoryFrame(){
              setTitle("Apple");
              Toolkit tk = Toolkit.getDefaultToolkit();
              int screenWidth = tk.getScreenSize().width;
              int screenHeight = tk.getScreenSize().height;
              int halfWidth = screenWidth/2;
              int halfHeight = screenHeight/2;
              setBounds(halfWidth/2,halfHeight/2,halfWidth-45, halfHeight+50);
              Container c = getContentPane();
              c.setLayout(new FlowLayout());
              addWindowListener(new WindowAdapter () {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              // this creates an array for 10 CardPanels, but they all start out as 'null'
              cards = new CardPanel[noCards];
              for(int i=0; i<noCards; i++){
                   try{
                        // this creates each individual CardPanel
                        cards[i] = new CardPanel();
                        cards.setBackground(Color.red);
                        // if there is an exception, it is pointless continuing
                        c.add(cards[i]);     
                   }catch(Exception e){
                        System.out.println("SD");
                        e.printStackTrace();
         public static void main(String[] args) {
              // very hackish
              new MemoryFrame().setVisible(true);
    class CardPanel extends JPanel {

Maybe you are looking for