Swapping JPanels?

I have a question regarding JPanels in a JFrame. What I'm wondering if the source of the JPanel can be changed on an action event. For example say I have two instances of a JPanel, is it possible to switch between the two in the same JFrame on a button event?
Thanks for your time.

Uhm...consider that when dealing with something like a JFrame, the contentPane is the second top-most layer (sits below the glassPane). So simply doing JFrame.add() will not be enough. You can however, call JFrame.getContentPane() and then issue an add() method to the container returned; for example JFrame.getContentPane().add(your panel);However you wind up with an extra layer since what you have is a container (the content pane) that contains a panel (panel1). In reality, panel1 is meant to hold the actual content, so setting it as the contentPane reduces the number of layers. It also removes the need to remember to remove(oldPanel) before calling add(newPanel).
So rather than having to replace via myFrame.getContentPane().remove(panel1);
myFrame.getContentPane.add(panel2);You'd simply do it viamyFrame.setContentPane(panel2);//the previous contentPane is de-referrenced

Similar Messages

  • Expand/Collapse (or Maximize/Minimize) JPanel

    Hi,
    We have a JFrame that has many components like JComboBox, JTextArea etc. It also has a JPanel that contains a graph.
    Now my requirement is to have expand/collapse button. When user clicks on expand, this JPanel with the graph should occupy the whole screen. At this point, the expand button would be replace with collapse button.
    When user clicks on collapse, the JPanel should resume its original place and all other components should re-appear with correct state.
    Can anyone help me with some pointers/resources?
    Thanks in advance,
    Regards,
    Manu
    Edited by: Manupriya on Apr 7, 2009 2:05 PM

    One way to solve this would be to create a model / view set of classes for your JPanel with the graph. When the expand button is pressed I'd create a new JPanel that uses the same model (displays the same graph), place it in a JDialog, and show it in a size to fill the screen. Other options include having the JFrame's contentPane use a CardLayout and swap JPanels as desired.

  • Multipule Jpanels question

    hello all,
    I'm createing an applet, and I'm using multipile jpanels. I want the panels to come up one after an other. The Jpanels will do the following. One will be the start frame I'll call it startPanel() it basically will ask the user names for two players, and to select a type of game. The next pane will have the panel of the selected game. The final panel will display the score for the game, and ask the user either to select an other game or quit. So as you see the panels need to wait for each other and the last panel will have to have a loop in that calls either board.
    I'm not sure if I am on the right track, but i think it may use something like this:
    /* I tried this and it doesn't work I really didnt get it(Start is its own class I don't think this one needs an invokeAndWait anyways becuse it is up first but just to try it out....
        try {
            javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
                 add (new Start());
        } catch (Exception e) {
            System.err.println("createGUI didn't successfully complete");
        }I think i may use an setLayeredPane or something to change the JPanels. To make it easier for everyone the other classes for the Jpanels are called game1, game2, and endGame. the panels will go something like this start then when the "go" button is clicked in start it will then goto either game1 or game2 depending one what one is selected(I found an fourm that may help me with returning values from Jframes so there will be different variables carried over to each panel) Then when the game is finished the endGame panel comes up displays some stats about the game and asks the user what type of game they want and either play the games or exit. Thanks

    I'm not 100% sure if this is what you need, but have you had a look at the CardLayout? It lets you swap JPanels as if they were in a deck of cards with one panel of your choosing always showing. I've used it several times, and it's not that hard to use. If this sounds close to what you need, check out the Sun tutorial on this:
    http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html

  • Beginner question about NetBeans

    I am new to java, which is why I am posting on this forum. I have been messing around with the NetBeans IDE and have made a couple GUI's now. First question is how do I have the window change. For example, if the application opened up and it showed a menu with a couple different buttons you could click to do different things, how would I make it so when you clicked a button the window changed into what was supposed to be on the screen next. Say one of the options was "Calculator", how would I make the window become a calculator after it was clicked? Do I make a new JFrame with the all the calculator stuff? If so, how do I "connect" the two of them? I want it to appear in the same window, not open a new one. My second question was how do I make it so my applications can be run from the desktop without having to build from within NetBeans?
    It was a little difficult to explain what I was asking, but any help is appreciated. I am assuming that what I'm trying to do is pretty basic, sorry I'm newbie.

    mdewaddict11 wrote:
    I am new to java, which is why I am posting on this forum. Let me try to be the first to welcome you to our little corner of the Java world.
    I have been messing around with the NetBeans IDE and have made a couple GUI's now. First question is how do I have the window change. For example, if the application opened up and it showed a menu with a couple different buttons you could click to do different things, how would I make it so when you clicked a button the window changed into what was supposed to be on the screen next. Say one of the options was "Calculator", how would I make the window become a calculator after it was clicked? Do I make a new JFrame with the all the calculator stuff? If so, how do I "connect" the two of them? I want it to appear in the same window, not open a new one. My second question was how do I make it so my applications can be run from the desktop without having to build from within NetBeans?I have a feeling that you are searching for a way to change your GUI "view" on some action, and if so, there are many solutions to do this. Probably one of the more common ways is to use a CardLayout to swap JPanels, but other options including popping up a JDialog, using JTabbedPanes, hiding a JFrame and showing another, ... exist.
    It was a little difficult to explain what I was asking, but any help is appreciated. I am assuming that what I'm trying to do is pretty basic, sorry I'm newbie.You're doing fine, relax.
    Now I need to get on my soap box and discuss another issue that you've not asked about. First off, Java is not like Visual Basic, C#, or other .NET languages (assuming you may be familiar with the MS Visual Studio) in that our programs are not first and foremost GUI's with code tacked on. There's a lot to learn when starting to code in Java, enough that adding Java GUI coding may be a bit overwhelming at the start. I'm going to recommend that you put the GUI stuff to the side for a bit, study the basics of Java, and then later when you're comfortable with the rudiments of Java, start learning Swing coding but without NetBeans code generation. If you learn it through the Sun tutorials, Swing will make a whole lot more sense and even using NetBeans to generate some Swing code will be easier for you. Regardless what you do, best of luck!
    Edited by: Encephalopathic on Jul 7, 2010 2:15 PM

  • Switching JFrame's contentPane

    Hi folks,
    I've had a problem trying to switch the contentPane of a JFrame. Basically, I'd created a class to manage my application, that at construction time sets up the application's main window ( JFrame mainWindow ), and then have a method to switch the contentPane
    public void switchContentPane( JPanel newContent )  throws Exception {
      newContent.setOpaque( true );
      mainWindow.setContentPane( newContent );
    }The problem was that every time the switchContentPane() were invoked, the GUI would be updated only if the window were resized. I've tried many things to solve this problem:
    - call mainWindow.repaint() after setContentPane();
    - call mainWindow.revalidate() after setContentPane();
    - invoke switchContentPane using SwingUtilities.invokeLater();
    None of this worked for me. The same behavior was ocurring. What worked for me was to invoke mainWindow.getRootPane().updateUI() after mainWindow.setContentPane(). This solution was just a guessing. I don't have the minor idea of why this works, adn would like to know if someone could explain this. I would really appreciate it.
    Thanks,
    Alexandre

    I've tried many things to solve this problem:
    - call mainWindow.repaint() after setContentPane();
    - call mainWindow.revalidate() after setContentPane();
    - invoke switchContentPane using SwingUtilities.invokeLater();
    The solution is to call validate() and then repaint(), as with any time when you modify an on-screen component hierarchy. The code below works perfectly.
    JFrame doesn't even have a revalidate() method so I'm not sure how you managed to try that one.
    I haven't tried this, and I'm no Swing expert, but I haven't seen content panes being switched like that before.
    It's a perfectly decent way of doing it, and I would suggest a better way - why have an arbitrarily-configured panel sitting there doing nothing except ruining the semantics of placing your content into a frame?
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class TestCP implements Runnable
         private JFrame frame = null;
         private int swaps = 0;
         public static void main(String[] args)
              SwingUtilities.invokeLater(new TestCP());
         public void run()
              this.frame = new JFrame();
              updateContent();
              this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.frame.pack();
              this.frame.setLocationRelativeTo(null);
              this.frame.setVisible(true);
         private void updateContent()
              JLabel l = new JLabel("Swaps: " + this.swaps, JLabel.CENTER);
              JButton b = new JButton(new Swap());
              JPanel p = new JPanel(new BorderLayout());
              p.add(l, BorderLayout.CENTER);
              p.add(b, BorderLayout.SOUTH);
              this.frame.setContentPane(p);
              this.frame.validate();
              this.frame.repaint();
         private class Swap extends AbstractAction
              private Swap()
                   putValue(NAME, "Swap");
              public void actionPerformed(ActionEvent e)
                   swaps ++;
                   updateContent();
    }

  • Poker game experiencing lag problems

    I've recently written a semi-functional Poker game however I'm experiencing problems with the game slowing down drastically as game play continues. I only have some basic high school programming knowledge so please forgive me for my extremely poor coding practice. Included are are the source files and jar. Any help would be appreciated. Thanks

    Ducky24 wrote:
    Upon using the Net Beans profiler I am finding myself quite shocked. The results show that invoke my formatJButton some 181000 times however I have no idea why it is invoked such.You have your swingComponent() method being called from inside of your paintComponent() method, and that seems like a bad idea to me. Every time your screen redraws, it will call this method, and it seems to me that it should be the other way around -- Your swingComponent should be involved with changing things and then call revalidate() and repaint() to relayout and redraw things.
    Again, I can't force myself to look at all of your code, but I wonder if you should be using a CardLayout here to swap JPanels rather than removing and repositioning and such.

  • How do i make the program hold after it has created a JFrame

    I have created a JFrame with which the user shall login to a server. I call this JFrame from my main method (the JFrame-class is in a separate file). My problem is that after the login-window is created and set visible, my main method continues, i would like it to wait until the user have logged in before running the rest of the code.
    this i my main method:
    new LoginWindow();
    System.out.println("Logged in: "+Session.isLoggedin()+
                    "\nUsername: "+Session.getUsername());Session.isLoggedin() returns a boolean, true if user is logged in and otherwise false. class LoginWindow extends JFrame.
    i have tried to use a while-loop to solve my problem:
    while(!Session.isLoggedin()) { }and also
    whiel(true){
        if(Session.isLoggedin())
            break;
    }these while-loops never breaks, i have waited for about 3 min after successful login.It isn't because Session.isLoggedin() returns false, it does return true after a successful login (i've checked).
    the funny thing however is if i print something in the while-loop i does break when login is finished
    example:
    whiel(true){
        System.out.println(Session.isLoggedin());
        if(Session.isLoggedin())
            break;
    }this code makes the program wait until the login-phase is complete but i don't want it to print "text" a few thousand times while the user is logging in. (i've used "hej" as output aswell)
    Since i have no idea how long it will take for a user to log in i can't use the System.sleep(value) method.
    I would really appreciate any help
    Thanks in advance
    //Oscar

    SnuShogge wrote:
    I am still curious about why the while-loop only breaks if i print something using System.out.println(""), i didn't think that would make a difference since the break-statement remains the same.In general you should avoid trying to use while (true) or its variants in a Swing GUI as it often messes with the EDT, the main thread that renders the GUI graphics and interacts with the user.
    My problem i however partially solved by using a JDialog instead of a JFrame. I am planning on using JFrame later in the program so the problem might come back to haunt me if it isn't solved.This may not be a great idea. Usually an application has one single JFrame. Most other distinct windows a dialogs of one sort or another and should be JDialogs, not JFrames. Often better still is to use a CardLayout to swap JPanels or other components.

  • Simple GUI

    Hi, I'm trying to create a very straightforward GUI and would like it to have the following:
    -Main menu screen with buttons that can be clicked to open new frames.
    -When a new frame opens, I want it to hide or close the original menu frame (or replace its contents, keeping the same frame size if possible).
    If you've ever played a simple Nintendo DS game where there is a main menu with buttons that open a new window or "frame" you know what I'm talking about.
    Right now, I've began experimenting with the gui builder in NetBeans 5.5 and have a single frame all set up with simple textfield inputs and buttons to enter the input. I also made a button to open a new blank frame but the original remains open and if I close the blank frame, both frames close and end the program.
    So what I'm asking is:
    Is there a simple way to make such a gui? I've googled and searched the forums but see no basic guide for making this type of application.

    Tja123 wrote:
    I was thinking of using CardLayout but that would leave the original frame accessible,This really shouldn't be a problem, since one app often just has one JFrame. In my mind, I think of a JFrame as sort of like an empty picture frame, in that its main function is to frame JComponents, usually JPanels. So keep one JFrame, and swap JPanels that have been decorated any way you like.
    I also realized that using the generated code is probably a bad shortcut for a beginner and am also learning to do everything manually, but I'm making a simple program for someone for fun.That's ok, as long as you don't expect to learn much serious Swing yet.

  • Turning a "page"

    I'm still very new to java and to GUI ...
    Say I have a JFrame, and I draw a square on it. How can I have the square replaced, at the click of a Button, with a circle? And then perhaps replace the circle with triangle, and subsequently the triangle with some text? (And so on, multiple times.)
    I'm trying to program something like an illustrated book, where clicking a Button would be a turn of a page. I worked in a really simplistic programming language once where there was a 'clear screen' function. Is there anything like that available in java?
    Also, recommendations for efficiency in an endeavor like this would be appreciated.
    Edited by: alsuff on Jun 15, 2008 7:44 AM

    My recommendation: check out the CardLayout. This will allow you to swap JPanels (or other components) as if you were turning a page or dealing out cards.

  • Interconnecting JFrames

    Hi, let me explain my problem with an example.
    --> We run the program, a login screen appears.
    --> We enter login info and another screen appears, let's say student info screen.
    --> And we click the button "See my Grades" in the Student info screen, then we're directed to another frame. The former screen disappears of course.
    The whole process is similar. We see a screen, click a button, and are directed to another screen, and so on. I want to use a central class, let's say GUIManager, to open and close all frames. Every class has actionPerformed methods, if I click on a button, the related frame will show up, but I dont want to create this frame using blabla = new JFrame(...) etc. I want to use GUIManager to do this job. By the way, my GUIManager is a singleton class.
    My idea is to use a function like GUIManager.getInstance().createBlaBlaFrame(); (getInstance method returns the singleton object) in actionPerformed method of each class.
    I'm not a pro OOP programmer.
    Please, I need some ideas, any recommendations are welcome.

    signore wrote:
    "Singleton -- sounds like a very bad idea to me"... why do u think so? In the project, there will be only one instance of this class, managing all the GUI interconnections. Which disadvantages did u think of ?Google: Singleton anti-pattern.
    Then read articles such as this one: [http://accu.org/index.php/journals/337]
    "Hopping JFrames -- sounds like a bad idea to me" Do u mean managing the process with one frame but multiple panels?Yes, most programs you use, be they word processors or games use one main panel and often show different views in this panel with an occasional dialog (separate dialog window). You should strive to emulate the programs you currently use.
    "Why not swap JPanels with a CardLayout or JTabbedPane?" JTabbedPane is not what I want. I need buttons directing to another screens, just like menus. In tabbed mode, we see all the panels together. Also, I looked at http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html tutorial and cardLayout chooses panels from a drop-down menu, just another way of JTabbedPane's job. I dont need that :(I'm not getting you here. CardLayout has nothing to do with "drop-down menus". You may wish to re-read the tutorial, either that or clarify exactly what objections you have to it.

  • Swap Component in JPanel

    Hi there,
    I have a JPanel that holds several Components (ThumbnailPanel ... own Class for Displaying Thumbs and Infos of a Pic). I want to have a function to sort this Panel. That means I have Arrow Buttons and can shift a ThumbPanel one to the left or to the right. I try to show you here (its better to understand if you see this):
    http://www.rebelman.de/images/tpscreenshot.jpg
    the arrows to sort are the small buttons in the upper right corner.
    Logically the Components (ThumbnailPanels) are stored in a Vector and they are displayed in a JPanel with GridBagLayout. To shift a Component to the right, I have to swap it with its right neighbour. In the Vector its no problem
         public void sortToRight() {
              if(selIndex<currList.getImageCount()-2) {
                   //Vector swap
                   ImageData startImage     = currList.getImage(selIndex);
                   ImageData swappedImage     = currList.getImage(selIndex+1);
                   currList.setImage(selIndex, swappedImage);
                   currList.setImage(selIndex+1, startImage);
         }But I cant swap the Components in the JPanel where they are displayed. I can get the reference to the component (panelName.getComponent(index)) ... but I cant set the reference e.g. panelName.setComponent(index, Component).
    Any working idea? (I just think of swapping the constraint value of gridX ... but how? and does this work? The value for selIndex could point to the wrong component then and selection could run into trouble).
    - Frankie
    Edit: As mentioned in the last lines, I tried to swap the gridx Value:
    Component startComponent = thumbScrollPanel.getComponent(selIndex);
    Component swappedComponent = thumbScrollPanel.getComponent(selIndex+1);
    GridBagConstraints startConstraints = panelLayout.getConstraints(startComponent);
    GridBagConstraints swappedConstraints = panelLayout.getConstraints(swappedComponent);
    int startX = startConstraints.gridx;
    int swappedX = swappedConstraints.gridx;
    startConstraints.gridx = swappedX;
    swappedConstraints.gridx = startX;
    thumbScrollPanel.validate();This does not work. The order, both Components are displayed is not changing.
    Edited by: rebelman on Dec 13, 2007 1:14 AM

    Maybe use a GridLayout so you don't have to worry about constraints.
    Either way as mentioned above the key is to revalidate() the parent container after you add or remove a component from it. (Sometimes the repaint() is also necessary).

  • Swapping 2 JPanels - layout dosent repaint

    To make long story short... i havve 2 JPanels :
    JPanel 1 :
    public class ImagePanel extends JPanel {
         private BufferedImage image;
         public ImagePanel() {
              super();
    @Override
         public void paintComponent(Graphics g) {
              g.drawImage(this.image, 0, 0, this.getWidth(),this.getHeight(), null);
         public BufferedImage getImage() {
              return image;
         public void setImage(BufferedImage image) {
              this.image = image;
         public void destroy() {
              this.image = null;     
    }And the 2nd one :
    public class EndSlidePanel extends JPanel {
         private int outerLineMargin = 20;
         private int innerLineMargin = 30;
         private String txt = "Koniec prezentacji";
         public EndSlidePanel() {
              super();
         @Override
         public void paintComponent(Graphics g) {
              g.setColor(Color.red);
              Graphics2D g2d = (Graphics2D) g;
              /* Zewnetrzny prostokat */
              g2d.drawRect(this.outerLineMargin, this.outerLineMargin, this
                        .getWidth()
                        - 2 * this.outerLineMargin, this.getHeight() - 2
                        * this.outerLineMargin);
              /* wewnetrzny prostokat */
              g2d.drawRect(this.innerLineMargin, this.innerLineMargin, this
                        .getWidth()
                        - 2 * this.innerLineMargin, this.getHeight() - 2
                        * this.innerLineMargin);
              /* pogrubienie wewnetrznego prostokata */
              g2d.drawRect(this.innerLineMargin + 1, this.innerLineMargin + 1, (this
                        .getWidth() - 2 * this.innerLineMargin) - 2,
                        (this.getHeight() - 2 * this.innerLineMargin) - 2);
              /* kreska */
              g2d.drawLine(this.innerLineMargin + 1, this.innerLineMargin + 1, (this
                        .getWidth() - this.innerLineMargin) - 2,
                        (this.getHeight() - this.innerLineMargin) - 2);
              Font f = new Font("serif", Font.PLAIN, UserData.fontSize);
              g2d.setFont(f);
              TextLayout txtl = new TextLayout(this.txt, f, g2d
                        .getFontRenderContext());
              double texth = txtl.getBounds().getHeight();
              double textw = txtl.getBounds().getWidth();
              int posx, posy;
              posx = (this.getWidth() - ((int) textw)) / 2;
              posy = (this.getHeight() - ((int) texth)) / 2;
              g2d.drawString(this.txt, posx, posy);
    }i try to swap from one to another using this method :
         public void showEndingSlide() {
              this.imagePanel.destroy();
              this.getContentPane().remove(this.imagePanel);
              this.imagePanel = null;
              this.getContentPane().invalidate();
              EndSlidePanel e = new EndSlidePanel();
              this.getContentPane().add(e, BorderLayout.CENTER);
              this.getContentPane().invalidate();
         }The problem is that layout dosent repaint itself untill i resize the window...
    tried to call invalidate everywhere :/ no effect :/
    Can you guys help me out ? :/

    OK now we.re getting somewhere :
    After doing :
              e.revalidate();
              this.getContentPane().repaint();i get contents of a panel 2 on top of panel1 so i just need to erease background now.
    i cant call revalidate() on .this.getContentPane() :/ dont know why :/
    ofcourse this extends JFrame....

  • How to swap Effects on a video processor?

    I have written a JMF based program that plays a video and applies an effect (I have written) to it. The code works just fine, but now I want to add the ability to add or swap other effects. The problem is I can't figure out how to correctly do this, and can't find any examples to model. Here's some of the relevant code:
         MediaLocator locator = new MediaLocator(videoFile);
         try {
              processor = Manager.createProcessor(locator);
              } catch (NoProcessorException e) {
                   System.out.println(e);
              } catch (IOException e) {
                   System.out.println(e);
         processor.addControllerListener(this);
         processor.configure();
         public void controllerUpdate(ControllerEvent event) {
              processor = (Processor) event.getSourceController();
              if (event instanceof ConfigureCompleteEvent) {
                   processor.setContentDescriptor(null);
                   TrackControl[] controls = processor.getTrackControls();
                   for (int i = 0; i < controls.length; i++) {
                        if (controls.getFormat() instanceof VideoFormat) {
                             videoTrack = controls[i];
                        else
                             controls[i].setFormat(new AudioFormat(AudioFormat.LINEAR));
                        try {
                             Codec codec[] = { new BorderEffect() };
                             videoTrack.setCodecChain(codec);
                        } catch (UnsupportedPlugInException e) {
                             System.err.println(e);
                   processor.prefetch();
                   processor.start();
              } else if (event instanceof RealizeCompleteEvent){
                   SwingUtilities.invokeLater(new AddComponentsThread());
              } else if (event instanceof EndOfMediaEvent) {
                   processor.setMediaTime(new Time(0));
                   processor.start();
         If I change the line Codec codec[] = { new BorderEffect() };toCodec codec[] = { new ConvolveEffect() };it works fine with the new convolve. Alternately if I change it to:Codec codec[] = { new BorderEffect(), new ConvolveEffect() };the video gets both effects added. But so far I haven't been able to react to a user button click to change from one effect to the other.
    First I tried to call processor.removeControllerListener() and processor.stop(), call a method to change the codec referenced just above and then call processor.addControllerListener(this) and processor.configure() all over again. This didn't work.
    After a bit of reading I have think there are two other tactics:
    *(1)* use a PluginManager and call addPlugin() or removePlugin() to enable / disable. I can't find any examples of using a PluginManager and some things aren't clear. Like - one you call addPlugin() do you still need the lines about new codec, setCodecChain() etc?
    *(2)* chain processors together to add effects, remove a processor from the chain to remove effects. The DataOutput of a processor allows the output of one to be fed to the input of another.
    I haven't been able to get any of these methods to work so far. Any ideas on what is the proper way to swap in/out effects?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    No ideas yet?
    After trying some more things I have my program working ... well working in that I can apply different effects, but I think it is a pretty ugly solution. Here is a representative code snippet:
          if (ae.getActionCommand().equalsIgnoreCase("GREYSCALE")) {
                   processor.stop();
                   removeComponents();
                   processor.removeControllerListener(this);     
                   try {
                        processor = Manager.createProcessor(locator);
                   } catch (NoProcessorException npe) {
                        System.out.println("No Processor Exception");
                   } catch (IOException ioe) {
                        System.out.println("IO error creating player");
                   setCodec("GREYSCALE");
                   processor.addControllerListener(this);
                   processor.configure();                               
              }I wrote a custom method removeComponents() which calls removeAll() on the JPanel containing the video and controls to essentially wipe them out. Then remove the ControllerListener and create a whole new processor. (THIS does not seem to be an elegant or correct way of doing things!) Another custom method setCodec() is used to specify which codec to use, a ControllerListener is added and the new processor is configured.
    This DOES work, but I am quite sure it isn't the best or most elegant way of doing things. Any advice would be much appreciated.
    Edited by: craighagerman on Oct 24, 2009 6:34 PM

  • Several Jpanels in a JFrame

    Hi,
    I have three buttons in Jtoolbar and a JPanel inside a JFrame. Now my program is supposed to work in the follwoing way-
    when I click a button a new JPanel containing general information comes in that fixed Jpanel place in that JFrame.
    When I press another button "a form" should come.
    When I press the third button then the a Jtable will come.
    Now all these should come in the same place inside that JFrame. So, when I press the JToggleButtons then how to call and set up so that the Jpanels replace each other?
    Please post some example if possible along with your advice.
    Thanks a lot in advance.

    I figured what the heck, here's a trivial example of card layout:
    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    * main jpanel that is added to a jframe's contentPane
    * this main panel uses a borderlayout and places a label
    * in the north position, a swap button in the south
    * position, and a jpanel in the center position that uses
    * the cardlayout. 
    * @author Pete
    public class CardPracticeMainPanel extends JPanel
        private static final long serialVersionUID = 1L;
        private JButton swapButton = new JButton("Swap Panels");
        private CardLayout cardlayout = new CardLayout();
        private JPanel cardLayoutPanel = null;
        public CardPracticeMainPanel()
            int ebGap = 20;
            setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
            setLayout(new BorderLayout());
            cardLayoutPanel = createCardLayoutPanel();
            add(createNorthPanel(), BorderLayout.NORTH);
            add(cardLayoutPanel, BorderLayout.CENTER);
            add(createSouthPanel(), BorderLayout.SOUTH);
        public void addCard(JPanel panel, String string)
            cardLayoutPanel.add(panel, string);
        private JPanel createNorthPanel()
            JPanel p = new JPanel();
            JLabel titleLabel = new JLabel("CardLayout Practice Program");
            titleLabel.setFont(new Font(Font.DIALOG, Font.BOLD, 24));
            p.add(titleLabel);
            return p;
        private JPanel createCardLayoutPanel()
            JPanel p = new JPanel();
            p.setLayout(cardlayout);
            return p;
        private JPanel createSouthPanel()
            JPanel p = new JPanel();
            p.add(swapButton);
            swapButton.addActionListener(new SwapButtonListener());
            return p;
        private class SwapButtonListener implements ActionListener
            public void actionPerformed(ActionEvent arg0)
                cardlayout.next(cardLayoutPanel);
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    * the "driver" program that creates a JFrame and places a
    * CardPracticeMainPanel into the contentpane of this jframe.
    * It also adds JPanel "cards" to the CardPracticeMainPanel object.
    * @author Pete
    public class CardPracticeTest
        private static Random rand = new Random();
        private static void createAndShowGUI()
            // create the main panel and add JPanel "cards" to it
            CardPracticeMainPanel mainPanel = new CardPracticeMainPanel();
            for (int i = 0; i < 4; i++)
                JPanel card = new JPanel();
                card.setPreferredSize(new Dimension(600, 400));
                card.setBorder(BorderFactory.createLineBorder(Color.blue));
                String panelString = "panel " + String.valueOf(i + 1);
                card.add(new JLabel(panelString));
                mainPanel.addCard(card, panelString);
                card.setBackground(new Color(
                        127 * rand.nextInt(3),
                        127 * rand.nextInt(3),
                        127 * rand.nextInt(3)));
            JFrame frame = new JFrame("CardLayout Practice Application");
            frame.getContentPane().add(mainPanel); // add main to jframe
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        // let's show the jframe in a thread-safe manner
        public static void main(String[] args)
            EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }

  • How do you switch between jpanels in a jframe?

    I have, what seems, a relatively simple question; however I cant find a solution to it anywhere!
    I have a jframe with a jmenubar which has 4 menu items. When each item is clicked a new JFrame is displayed with certain content. What I am trying to do, instead of creating a new Jframe each time a menu item is clicked, is display all jpanels within the current jframe. When different menu items in the jmenu are clicked it "switches" the main jpanel to display the required content.
    So basically I want 1 JFrame, which has 4 JPanels, (alhough only 1 is shown at any given time). When a menu item in the jmenubar is clicked the JPanel which corresponds to the menu item is displayed on the jframe.
    If your still confused, I basically want jtabbedpane functionality only I want to control the switching through tabs via the jmenubar (and I dont want the jtabbedpane tabs obviously).
    Thanks

    Myles wrote:
    Okay that seems obvious ;)
    What do you mean by "validating the content pane" though?
    Thanks for your quick reply.Containers have a method called validate() which will update them when components are added and removed. Without this, you won't see added components.
    And yes, you can have more than 1 container. JPanels are containers themselves and can have components added and removed from them as well. You only have one content pane in the JFrame, but you could add two JPanels to this, one static and one to act as your swapping container.

Maybe you are looking for