Adding and displaying a new JPanel -- not working as expected

I'm starting my own new thread that is based on a problem discussed in another person's thread that can be found here in the New to Java forum titled "ActionListener:
http://forum.java.sun.com/thread.jspa?threadID=5207301
What I want to do: press a button which adds a new panel into another panel (the parentPane), and display the changes. The Actionlistener-derived class (AddPaneAction) for the button is in it's own file (it's not an internal class), and I pass a reference to the parentPane in the AddPaneAction's constructor as a parameter argument.
What works: After the button is clicked the AddPaneAction's actionPerformed method is called without problem.
What doesn't work: The new JPanel (called bluePanel) is not displayed as I thought it would be after I call
        parentPane.revalidate();  // this doesn't work
        parentPane.repaint(); 
What also doesn't work: So I obtained a reference to the main app's JFrame (I called it myFrame) by recursively calling component.getParent( ), no problem there, and then tried (and failed to show the bluePanel with) this:
        myFrame.invalidate();  // I tried this with and without calling this method here
        myFrame.validate();  // I tried this with and without calling this method here
        myFrame.repaint();
What finally works but confuses me: I got it to work but only after calling this:
        myFrame.pack(); 
        myFrame.repaint();But I didn't think that I needed to call pack to display the panel. So, what am I doing wrong? Why are my expectations not correct? Here's my complete code/SSCCE below. Many thanks in advance.
Pete
The ParentPane class:
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ParentPane extends JPanel
    private JButton addPaneBtn = new JButton("Add new Pane");
    public ParentPane()
        super();
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        setBackground(Color.yellow);
        JPanel northPane = new JPanel();
        northPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        northPane.setBackground(Color.yellow);
        northPane.add(addPaneBtn);
        add(northPane, BorderLayout.NORTH);
        // add our actionlistener object and pass it a reference
        // to the main class which happens to be a JPanel (this)
        addPaneBtn.addActionListener(new AddPaneAction(this));
    public static void main(String[] args)
        javax.swing.SwingUtilities.invokeLater(new Runnable()
            public void run()
                createAndShowGUI();
    private static void createAndShowGUI()
        JFrame frame = new JFrame("test add panel");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new ParentPane());
        frame.pack();
        frame.setVisible(true);
} the AddPaneAction class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class AddPaneAction implements ActionListener
    private JPanel parentPane;
    private JFrame myFrame;
    public AddPaneAction(JPanel parentPane)
        this.parentPane = parentPane;
     * recursively get the JFrame that holds the parentPane panel.
    private JFrame getJFrame(Component comp)
        Component parentComponent = comp.getParent();
        if (parentComponent instanceof JFrame)
            return (JFrame)parentComponent;
        else
            return getJFrame(parentComponent);
    public void actionPerformed(ActionEvent arg0)
        JPanel bluePanel = new JPanel(new BorderLayout());
        bluePanel.setBackground(Color.blue);
        bluePanel.setPreferredSize(new Dimension(400, 300));
        JLabel myLabel = new JLabel("blue panel label");
        myLabel.setForeground(Color.LIGHT_GRAY);
        myLabel.setVerticalAlignment(SwingConstants.CENTER);
        myLabel.setHorizontalAlignment(SwingConstants.CENTER);
        bluePanel.add(myLabel, BorderLayout.CENTER);
        parentPane.add(bluePanel);
        myFrame = getJFrame(parentPane);
        //parentPane.revalidate();  // this doesn't work
        //parentPane.repaint(); 
        //myFrame.invalidate(); // and also this doesn't work
        //myFrame.validate();
        //myFrame.repaint();
        myFrame.pack();  // but this does!?
        myFrame.repaint();
}

For me (as it happens I'm using JDK 1.5.0_04) your code appears to work fine.
It may be that we're seeing the same thing but interpreting it differently.
1. When I run your application with your "working" code, and press the button then the JFrame resizes and the blue area appears.
2. When I run your application with your "not working" code and press the button then the JFrame does not resize. If I manually resize it then the blue area is there.
3. When I run your application with your "not working" code, resize it first and then press the button then the JFrame then the blue area is there.
I interpret all of this as correct behaviour.
Is this what you are seeing too?
Are you expecting revalidate, repaint, invalidate or validate to resize your JFrame? I do not.
As an aside, I do remember having problems with this kind of thing in earlier JVMs (e.g. various 1.2 and 1.3), but I haven't used it enough recently to know if your code would manifest one of the previous problems or not. Also I don't know if they've fixed any stuff in this area.

Similar Messages

  • Notification "Launch the app and go to the library" not working as expected

    Hello,
    we are sending notification "Launch the app and go to the library" - but it's not working as expected, it's still just launching app with last open folio.
    Whats wrong there? Do we need v30 app? We have V29, but this is not mentioned in documentation.
    Thanks
    Martin

    Ah.
    Ok, now it's clear.
    Anyway i would appreciate possibility to force viewer to switch to library view after new issue is detected, even without notification. Quite often requested feature - "there is new cover in Newsstand, but customer don't know how to download new publication easily".
    Martin

  • Import-CSV | New-ADGroup not working as expected with Powershell

    I've looked all over and I can't seem to find an explanation for why this command works perfectly with New-ADUser but not with New-ADGroup.
    These are commands I'm using:
    For Users:
    Import-CSV C:\Imports\adusers.csv | New-ADUser
    This works great. All 500+ users imported with all fields.
    For Groups:
    Import-CSV C:\Imports\adgroups.csv | New-ADGroup
    Only the first line is run correctly. Then I get this error: The specified group already exists
    Here is a snip of my CSV for Groups:
    Name,DisplayName,Description,GroupCategory,GroupScope,Path
    DB Users,DB Users,Group for DB users,Global,"OU=Security Groups,OU=ABC Users,DC=domain,DC=local"
    Accounting,Accounting,Access to the Accounting folder,Security,Global,"OU=Security Groups,OU=ABC Users,DC=domain,DC=local"
    Am I missing something here or is this not possible?
    THanks.

    I knew I would figure this out as soon as I posted it...
    This is the behavior you see if the SamAccountName field is not included.

  • Drag and relate from User query not working as expected

    Hi All,
    Could anyone shed some light on why using drag and relate from a user query is not working for me?
    Drag and relate works well from all system generated queries, but not from my user queries.
    For example:
    - System query/report - running a system stock report and dragging the 'Item number' field result to a D&R Sales Order generates a report of all Sales Orders for the selected Item Number. As expected - success.
    - User Query - running a item lookup report from a user generated query and then D&R to Sales order for the selected Item Number does not work. Error = 'No matching records found (ODBC -2028) [message 131-183]
    Any ideas?
    Best regards,
    John

    Hi John,
    I believe Drag and relate only works for system form.  The whole function is hard coded.  It will not work for any queries including system queries.
    Thanks,
    Gordon

  • JavaScript and "Open In New Window" not working.

    I've been using Safari 5 since it came out and there were no problems. But recently my JavaScript has stopped working. Whenever I click on a link that is supposed to run a script nothing happens. Similarly when I click a link that is supposed to open automatically in a new window, nothing happens. I've tried reseting Safari but that did not help. I had this same issue with Safari 4 and the update to 5 solved it, but now I do not know what to do.

    HI and welcome to Apple Discussions...
    From the Safari Menu Bar click Safari/Preferences then select the Security tab.
    Make sure Java is enabled.
    And, from a Finder window select your Home Folder in the Sidebar on the left. Then open the Library folder, then the Caches folder, then the com.apple.Safari folder. Move the cache.db file to the Trash.
    Relaunch Safari. If you still have problems, go to the Safari Menu Bar, click Safari/Preferences. Make note of all the preferences under each tab. Quit Safari. Now go to ~/Library/Preferences and move this file com.apple.safari.plist to the Desktop.
    Relaunch Safari and see if that makes a difference. If not, move the .plist file back to the Preferences folder. If Safari functions as it should, move that .plist file to the Trash.
    I had this same issue with Safari 4 and the update to 5 solved it, but now I do not know what to do.
    If nothing above helps, install the v10.6.4 Combo Update
    Then repair permissions.
    Launch Disk Utility. (Applications/Utilities) Select MacintoshHD in the panel on the left, select the FirstAid tab. Click: Repair Disk Permissions. When it's finished from the Menu Bar, Quit Disk Utility and restart your Mac. If you see a long list of "messages" in the permissions window, it's ok. That can be ignored. As long as you see, "Permissions Repair Complete" when it's finished... you're done. Quit Disk Utility and *restart your Mac*.
    Carolyn

  • N82 new battery not working as expected

    Hi
    I bought a new N82 BP-6MT battery. Now I see when the battery drops 1 bar from full, it skips through all the other bars and goes to only 1 bar remaining! This happens especially when I use a power hungry application, like games or GPS navigation.
    Is there something I can do about it? Is the battery faulty?

    Make sure you have a look at our Pool of Knowledge article regarding that subject:
    PoK - Maximize battery performance
    Especially the last tip may be interesting for you!   
    Message Edited by illinjah on 13-Dec-2009 12:32 AM
    By clicking the "Kudos!" or the "Solution?" button on the right you can say "Thank You" and you´ll show the author and others that the post is useful.
    The day we stop improving is the day we stop being good.

  • I bought a new Epson printer WR-7620 on Saturday and the Air Printer is not working. I spoke to Epson and they said it is an Apple problem, can anyone help. Thanks Peter

    I bought a new Epson printer WR-7620 on Saturday and the Air Printer is not working. I spoke to Epson and they said it is an Apple problem, can anyone help. Thanks Peter

    Peter,
    deggie gave you that link so you'd know that airprint is a reduced-options print system, designed for mobile devices (not Macs), and you need to use the specific airprint driver on the Mac when adding the printer if you want Airprint, no-options printing. Otherwise, select the "non-airprint" driver when you add the printer.
    It may be helpful to Reset the Printing System to get OS X to find the right driver.
    Mac OS X: How to reset the printing system - Apple Support
    (And "not working" doesn't help us to help you - please give more detail next time)

  • I bought my iPhone5 4 months ago and now the camera is not working, it only displays black in the screen. I've tried reset, restore for how many times but still the problem is not being resolve. Any help from you Apple team?

    I bought my iPhone5 4 months ago and now the camera is not working, it only displays black in the screen. I've tried reset, restore for how many times but still the problem is not being resolve. Any help from you Apple team?

    There is no Apple here, this is a user to user forum.  When you said you restored, then you restore as NEW?
    If you restored as New and still the problem persiist, then it time to take a trip to the Apple store.

  • Hi Guys,  I am using the full width video widget on a site. The widget was working perfectly however I have just added additional content to the site and re-uploaded and now the video is not working! Please help I have tried everything and am freaking out

    Hi Guys,
    I am using the full width video widget on a site. The widget was working perfectly however I have just added additional content to the site and re-uploaded and now the video is not working! Please help I have tried everything and am freaking out as this web-site has been payed for by my client.
    Alex

    Many thanks.
    With those symptoms, I'd try the following document:
    Apple software on Windows: May see performance issues and blank iTunes Store
    (If there's a SpeedBit LSP showing up in Autoruns, it's usually best to just uninstall your SpeedBit Video Accelerator.)

  • I have done absalutely nothing to my 4g apple ipod touch, and it over heats, won't hold a charge, and the front camera will not work. I bought this brand new in december, and i've barely used it. I've tried restarting it and everything, what should i do?

    I have done absalutely nothing to my 4g apple ipod touch, and it over heats, won't hold a charge, and the front camera will not work. I bought this brand new in december, and i've barely used it. I've tried restarting it and everything, I honestly think this is out raging because i spend over $200 on this. To have for music and instagram. I use it about an hour a day, but i've only been using it for about 3 months although i've had it since December. Any suggestions that may help me?

    Try:
    - A reset. Nothing is lost
    Reset iPod touch: Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears.
    - Restore from backup
    - Restore to factory settings/new iPod
    If still problem make an appointment at the Genius Bar of an Apple store.

  • In outlook 2013 Add-In, Adding dynamic menu to splitButton idMso="DialMenu" is working and the same code is not working in outlook 2010 Add-In.

    In outlook 2013 Add-In, Adding dynamic menu to <splitButton idMso="DialMenu"> is working and the same code is not working in outlook
    2010 Add-In. please let me know, if i am missing something. Below is the xml and screen shot
    <contextMenu idMso="ContextMenuFlaggedContactItem">
     <splitButton idMso="DialMenu">
              <menu>
                <dynamicMenu id="CallContactwithFreedomvoice
    " label="CallContactwithFreedomvoice" 
                            getContent="OnGetContenttest"                           insertAfterMso="Call"/> 
            </menu>       </splitButton>    </contextMenu> 

    Hi Narasimha prasad2,
    Based on the description, the context menu for the flagged contact doen't work in Outlook. I am tring to rerpoduce this issue however failed.
    I suggest that you check the state of the add-in first to see wether the add-in was loaded successfully.
    Regards & Fei
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Hello everybody,i've forgot my apple password and i wanted to reset it to a new one but i also forgot the security question and the alternative email does not work and i am really need to log in to my apple i d because my iPhone 4g won't  let me access it

    Hello everybody,i've forgot my apple password and i wanted to reset it to a new one but i also forgot the security question and the alternative email does not work and i am really need to log in to my apple i d because my iPhone 4g won't  let me access it so anyone can help me with it or can i put another apple id to it without putting the first password?THANKS FOR YOUR HELP.

    Then call AppleCare and talk to someone in account security.

  • I just buy a new i phone 5 and the hand free is not working

    Hi i phone support team
    I just bue a new i phone 5 and the head set is not working
    I got it from frind
    Pleas i need you support to change the head set
    Ahmed shindy
    Phone number.  00201148886700
    Email. [email protected]

    If they are Apple-brand headphones, then the Apple Store will handle the warrranty and, absent any evidence of abuse, should replace the headphones. If the headphones were made by some other company, then unless you purchased the headphones in the last fourteen days, you will have to contact the manufacturer of the headphones for warranty support.
    Regards.

  • I buy my Headphones on Apple Store, and the left sight is not working that much.II want to know if i can replace to a new one.

    I buy my Headphones on Apple Store and it cost me about $36 with Tax, and the left sight is not working that much.I want to know if i can replace to a new one without no charge.

    If they are Apple-brand headphones, then the Apple Store will handle the warrranty and, absent any evidence of abuse, should replace the headphones. If the headphones were made by some other company, then unless you purchased the headphones in the last fourteen days, you will have to contact the manufacturer of the headphones for warranty support.
    Regards.

  • I have cs5 on my home mac. I had it on my old mac laptop. I deactivated it then went to reinstall it on my new laptop and my serial number does not work. Any help?

    I have CS5 photoshop extended on my mac home computer. I had it also on my mac laptop. I deactivated it from my old laptop and tried to install it on my new laptop and the serial number would not work. Any thoughts?

    David o"bryan did you migrate/transfer any files/folders/applications to the new Mac laptop?  You can verify that your serial number is valid by checking under your account at http://www.adobe.com/.  You can find more details on how to locate your serial number at Find your serial number quickly - http://helpx.adobe.com/x-productkb/global/find-serial-number.html.

Maybe you are looking for

  • Every app is crashing?

    Every app is crashing including Apple apps.

  • Currency conversion error in SRM

    Hi, When we are trying post the confirmation in SRM it is giving the error message that "Error in currency conversion between EUR and USD". We have checked the exchange rate settings in SRM and Backend (R/3) there is no issue at all. Everything is ma

  • An Innovative Design That Breaks from the All the Rest.

    An Innovative Design That Breaks the Mold! With a new, curved screen that wraps around the side of the display, the Samsung Galaxy Note® Edge redefines smartphone design by creating a groundbreaking way to deliver information while keeping you in con

  • Booting from usb disk

    hello I'm new in solaris and I need help very much. I installed Solaris 10 for x86 on external 3.5'' usb HD but on boot it hangs and a perpetual black screen appears.I've read about usb legacy and I disabled it but now BIOS doesn't see usb disk. I tr

  • CF Builder CFML toolbar

    I've been using CFEclipse for years, looking at CF Builder as an alternative. I installed the trial, been using it for a couple of days and like it so far, but I can't figure out (and I spent way to much time trying) how to get the CFML toolbar to sh