One Components into 2 different panel problems

Hi,
I have one component, just call it A, and 2 different
panels just call it PA and PB.
I put A into PA and then I put A into PB,
and display PA & PB into screen together.
The problem is A is missing in PA but displayed
into PB. I know this is behavior of AWT/Swing,
but maybe some of you know how to solve
this problem without creating two instances of A.
Thank you in advance...

You could make something like this:
public class multicomponent
     Vector activecomponents=new Vector
     //all methods you intend to use on this component this way
     public method(somearg arg)
           for //all c in vector
               c.method(arg);
      public void addto(Container co)
           comp=new yourcomponent();
           co.add(comp);
           activecomponents.add(comp);
}You can enhance that by using weak references for the elements in the vector and you will have to think what to do for get methods.

Similar Messages

  • "Best practice" for components calling components on different panels.

    I'm very new to Swing. I have been learning from tutorials, but these are always relatively simple interfaces , in which every component and container is initialised and added in the constructor of a main JFrame (extension) object.
    I would assume that more complex, real-world examples would have JPanels initialise themselves. For example, I am working on a project in which the JFrame holds multiple JPanels. One of these Panels holds a group of JToggleButtons (grouped in a ButtonGroup). The action event for each button involves calling the repaint method of one of the other Panels.
    Obviously, if you initialise everything in the JFrame, you can simply have the ActionListener refer to the other JPanel directly, by making the ActionListener a nested class within the JFrame class. However, I would like the JPanels to initialise their own components, including setting the button actions, by using an extension of class JPanel which includes the ActionListeners as nested classes. Therefore the ActionListener has no direct access to JPanel it needs to repaint.
    What, then, is considered "best practice" for allowing these components to interact (not simply in this situation, but more generally)? Should I pass a reference to the JPanel that needs to be repainted to the JPanel that contains the ActionListeners? Should I notify the main JFrame that the Action event has fired, and then have that call "repaint"? Or is there a more common or more correct way of doing this?
    Similarly, one of the JPanels needs to use a field belonging to the JFrame that holds it. Should I pass a reference to this object to the JPanel, or should I have the JPanel use "getParent()", or some other method?
    I realise there are no concrete answers to this query, but I am wondering whether there are accepted practices for achieving this. My instinct is to simply pass a JPanel reference to the JPanel that needs to call repaint, but I am unsure how extensible this would be, how tightly coupled these classes would become.
    Any advice anybody could give me would be much appreciated. Sorry the question is so long-winded. :)

    Hello,
    nice to get feedback.
    I've been looking at a few resources on this issue from my last post. In my application I have been using the Observer and Observable classes to implement the MVC pattern suggested by T.PD.(...)
    Two issues (not fatal, but annoying) with this are:
    -Observable is a class, not an interface; since most of my Observers already extend JPanel (or some such), I have had to create inner classes.
    -If an Observer is observing multiple Observables, it will have to determine which Observer called its update() method (by using reference equality or class comparison or whatever). Again, a very minor issue, but something to keep in mind.I don't deem those issues are minor. The second one in particular, is rather annoying in terms of maintenance ("Err, remind me, which widget is calling this "update()" method?").
    In addition to that, the Observable/Observer are legacy non-generified classes, that incurr a loosely-typed approach (the subject and context arguments to the update(Observable subject, Object context) methods give hardly any info in themselves, and they generally have to be cast to provide app-specific information.
    Note that the "notification model" from AWT and Swing widgets is not Observer-Observable, but merely EventListener . Although we can only guess what reasons made them develop a specific notification model, I deem this essentially stems from those reasons.
    The contrasting appraoches are discussed in this article from Bill Venners: The Event Generator Idiom (http://www.artima.com/designtechniques/eventgenP.html).
    N.B.: this article is from a previous-millenary series of "Design Techniques" articles that I found very useful when I learned OO design (GUI or not).
    One last nail against the Observer/Observable model: these are general classes that can be used regardless of the context (GUI/non-GUI code), so this makes it easier to forget about Swing threading rules when using them (essentially: is the update method called in the EDT or not).
    If anybody has any information on the performance or efficiency of using Observable/ObserverI would be very surprised if this had any performance impact. If it had, that would mean that you have either:
    - a lot of widgets that are listening to one another (and then the Mediator pattern is almost a must to structure such entangled dependencies). And even then I don't think there could be any impact below a few thousands widgets.
    - expensive or long-running computation in the update methods. That's unrelated to the notification model itself.
    - a lot of non-GUI components that use the Observer/Observable to communicate among themselves - all the more risk then, to have a GUI update() called outside the EDT, see remark above.
    (or whether there are inbuilt equivalents for Swing components)See discussion above.
    As far as your remark 2 goes (if one observer observes more than one subjects, the update() method contains branching logic) : this also occurs with the Event Delegation model indeed: for example, it is quite common that people complain that their actionPerformed() method becomes unwieldy when the same class listens for several JButtons.
    The usual advice for this is, use anonymous listeners, each of which handles the event from only one source (and generally very close in code to the definition of that source), and that simply translates the "generic" event notification method into a specific method call of a Controller or Mediator .
    Best regards.
    J.
    Edited by: jduprez on May 9, 2011 10:10 AM

  • How to split one page into different frames in ADF?

    Hi,
    Can any one please guide me how to split a jspx into different frames.
    i.e., left frame contains <af:panelSideBar> which contains multiple <af:commandMenuItem> s. And whenver we click on the one <af:commandMenuItem>, it has to show the corresponing page inside center frame in this page itself. Is it possible in ADF? Which component we need to use?
    Can anyone guide me on this?
    Thanks in advance,
    Regards,
    Suresh Kethireddy

    You can use a combination of the ADF Faces 10.1.3 components like:
    af:panelPage
    af:panelSideBar
    af:panelHorizontal
    af:panelGroup
    to organize the screen layout, but it is not the interactive splitter that the 11g product provides.
    You can all all the 10.1.3 ADF Faces Components here:
    http://www.oracle.com/technology/products/jdev/htdocs/partners/addins/exchange/jsf/doc/tagdoc/core/imageIndex.html

  • Splitting one column into different columns.

    Hello Experts,
    How do i split datetime column into different columns while doing a Select statement.
    Ex:
    The column "REC_CRT_TS" has data like "2014-05-08 08:23:09.0000000".The datatype of this column is "DateTime". And i want it in SELECT statement like;
    SELECT
    YEAR(DATETIME) YEAR,
    MONTH(DATETIME) MONTH,
    DATENAME(DATETIME) MONTHNAME,
    DATEPART(DATETIME) WEEKNUM,
    DAY(DATETIME) DATE,
    DATEPART(DATETIME) HOUR
    FROM TABLE_NAME;
    The output should look like this;
    --YEAR| MONTH | MONTHNAME| WEEKNUM | DATE | HOUR
    --2014| 5 | May | 25 | 08 |08
    Any suggestions please.
    Thanks!
    Rahman

    I made a very quick research and I see in this blog post
    http://www.jamesserra.com/archive/2011/08/microsoft-sql-server-parallel-data-warehouse-pdw-explained/
    that  It also uses its own query engine and not all features of SQL
    Server are supported.  So, you might not be able to use all your DBA tricks.  And you wouldn’t want to build a solution against SQL Server and then just hope to upsize it to Parallel Data Warehouse Edition.
    So, it is quite possible that this function doesn't exist in PDW version of SQL
    Server. In this case you may want to implement case based month name or do it in the client application.
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog
    My TechNet articles

  • ALV GRID report( displayin one record into different rows)

    Dear ABAPERS,
    i have a request in ALV report. The requirement like
    EX: i have a 10 fields in internal table, i want display 5 fields in one row , 3 fields in one row and 2 fields in 3rd row. pleaz suggest the solution.
    thanks and regards,
    JP Reddy.

    JP,
    Below thread might help you for your requirement
    ALV grid Multiple Header ... ?
    Thanks,
    Chandra

  • Problem updating a control on one panel based on a value change in another control on a different panel

    Hi,
    I am trying to update the value of a control on one panel when the value of another control on a different panel is changed.  The two panels are saved in two different .uir files, so there are two associated .h files generated by CVI.  The problem is that, inside the callback function for the control that is being modified (Ctrl_Id_A on Panel_A), when I call SetCtrlVal(Panel_B, Ctrl_Id_B, Value); 'Panel_B' and 'Ctrl_Id_B' (which have the same numeric values as Panel_A = 1 and Ctrl_Id_A = 2 in their respective .h files) are being interpreted as Panel_A and Ctrl_Id_A.  I never understood how CVI makes this distinction, eg. knowing which of PANEL_A = 1 and PANEL_B = 1 is being referred to, but didn't worry about it since I never needed cross-communication between panels until now.  Any help on how to implement this would be greatly appreciated.  Thanks!
    Solved!
    Go to Solution.

    This is a basic issue on which you can find tons of forum posts
    The online help for the function recitates:
    int SetCtrlVal (int panelHandle, int controlID, ...);
    Parameters
    Input
    Name
    Type
    Description
    panelHandle
    int
    Specifier for a particular panel that is currently in memory. You obtain this
    handle from LoadPanel, NewPanel, or DuplicatePanel.
    controlID
    int
    The defined constant, located in the .uir header file, that you assigned to the control in the User Interface Editor, or the ID returned by NewCtrl or DuplicateCtrl.
    value
    New value of the control. The data type of value must match the data type of the control.
    That is, you must not use the panel constant name in the first parameter of SetCtrlVal, use the panel handle instead. The system guarantees that all panel handles are unique throughout the whole application whichever is the number of panels used in every moment.
    int SetCtrlVal (int panelHandle, int controlID, ...);
    Purpose
    Sets the value of a control to a value you specify.
    When you call SetCtrlVal on a list box or a ring control, SetCtrlVal
    sets the current list item to the first item that has the value you
    specify. To set the current list item through a zero-based index, use SetCtrlIndex.
    When you call SetCtrlVal on a text box, SetCtrlVal appends value to the contents of the text box and scrolls the text box to display value. Use ResetTextBox to replace the contents of the text box with value.
    Note   This function updates the displayed value immediately. Use SetCtrlAttribute with ATTR_CTRL_VAL to set the control value without immediately updating the displayed value. For this reason, SetCtrlAttribute with ATTR_CTRL_VAL is generally faster than SetCtrlVal. However, if the control in which you are setting the value is the active control in the panel, SetCtrlAttribute with ATTR_CTRL_VAL displays the value immediately.
    Note   This function is not valid for graph and strip chart controls.
    Parameters
    Input
    Name
    Type
    Description
    panelHandle
    int
    Specifier for a particular panel that is currently in memory. You obtain this
    handle from LoadPanel, NewPanel, or DuplicatePanel.
    controlID
    int
    The defined constant, located in the .uir header file, that you assigned to the control in the User Interface Editor, or the ID returned by NewCtrl or DuplicateCtrl.
    value
    New value of the control. The data type of value must match the data type of the control.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • My iphone will not recognize any usb cables. I have tried 3 official apple ones and 2 different plugs. Ive tried plugging it into my laptop but will not find the phone. it has had problems since i updated my ios. Battery has been replaced.

    I have tried 3 official apple ones and 2 different plugs. Ive tried plugging it into my laptop but will not find the phone. it has had problems since i updated my ios. Battery has been replaced. Any suggestions would be fantastic

    test if it charges with an ac charger
    test if it's detected by another computer
    if it's no to both then likely the connector is broken
    if it's yes to both thne it's likely your computers itunes install which is the problem

  • Event problem on two different panels

    I have an application which has a main JFrame.
    It has two panels north and south
    The one in the south has buttons that listens for events.
    The events are action events. The events on this panel works if I don't include the events for my other panel i.e
    PersonalDataPanel as described below.
    The noth panel uses card layout. Inside this layout has two panels.
    One panel is called PersonalDataPanel.
    Inside PersonalDataPanel are components.
    One is a group of radio buttons that listens for events
    the events are again action events and if one is choosen from the group it is written to a file.
    I have testdriver for this which works.
    My porblem occurs when I include the code for PersonalDataPanel to listen for events and the main JFrame also to listen for events.
    How should I handle this dilemma??

    Why does the JFrame also have to listen for events? If its only button events surely it doesn't need to be involved and could be causing the problem.
    Have you tried using different event handlers for the different panels...?

  • I have created a site with iWeb. I have replaced the iWeb Nav bar with a vertical one I made myself. Problem is, my top button disables itself if it overlaps into the "hidden" nav bar area. I can cmd click and drag it into this area, but then all the rest

    I have created a site with iWeb. I have replaced the iWeb Nav bar with a vertical one I made myself. Problem is, my top button disables itself (and the animation doesn't work) if it overlaps into the "hidden" nav bar area (indicated by a blue rectangle). I can cmd click and drag it into this area, but then all the rest of my site is pushed down the page. Don't know what to do about this. I don't know how to bring the rest of the page up without dragging it also into the designated nav bar area. Also, by doing this, is it affecting my site in ant way? see my site here at www.steveburrowsimages.com
    The home page is with it all draged into the nav bar area and the about page is with is outside the nav bar area (notice that the top button does not animate or work as a button.
    Getting confused here. Anyone got any ideas?

    Well, you made a good start with SEO by getting rid of the iWeb default navigation since it doesn't help the spiders and, out there in the real world, there are more people than you would think with javascript turned off in their browsers.
    One of the downsides of iWeb is that it doesn't allow for the alt attribute in the img tag. Its well worth adding these to give you extra keywords even if you have captioned all your images. Use iWeb SEO Tool for this...
    http://www.iwebformusicians.com/Search-Engine-Optimization/Tags.html
    iWeb, just like most drag and drop software, creates a huge amount of code which causes the pages to load slowly in the browser. Running you files through an optimizer will help to reduce this problem and further reduce the size of image files even beyond the initial optimization you do before loading them into iWeb...
    http://www.iwebformusicians.com/Search-Engine-Optimization/Optimize.html

  • One asset value to be transferred into different new asset codes

    Hello,
    I have one asset which has to be transferred into different new asset values. The instance as below:
    Old Asset: 1000
    Value: Rs. 10000
    Transferred into
    New asset code: 1100
    Value: Rs. 3000
    New Asset: 1200
    Value: Rs. 2000
    New Asset: 1300
    Value: Rs. 5000
    How to proceed? I have tried in ABUMN with partial Transfer but unable to get the result. Need help.
    JK

    Hi,
    This can be done through ABUMN only.
    You have to post 3 transactions individually to that old asset.
    For the first ABUMN transaction choode partial transfer and choose amount specification and enter 3000
    For the second ABUMN transaction choode partial transfer and choose amount specification and enter 2000
    For the last ABUMN transaction choode Complete retiremnet.(So the balance of 5000 will be transfered to the third new asset)
    Please check.
    Thanks,
    Srinu

  • Having a problem when scrolling through one clip: a different clip scrolls through point and time simultaneously. Can you please assist us?

    Having a problem when scrolling through one clip: a different clip scrolls through point and time simultaneously. Can you please assist us?

    First question: this is a Captivate forum, are you sure that you have a Captivate problem (with cpvc or an imported video)?

  • I have been trying to get the full version of lightroom after using a trial version but it says something about "GB" ? And i need to log into different account or set up a new one? Please help?

    I have been trying to get the full version of lightroom after using a trial version but it says something about "GB" ? And i need to log into different account or set up a new one? Please help?

    I would love to give you more information but i cannot access that page again? i can add Lightroom to my cart but when i go into my cart it says there is nothing in there? I have a red bubble above "my cart" with a number 4 in it to show there is something there but there is not? It just wont let me buy anything?

  • One SC splitting into different POs

    Hi SRM Experts,
    There is an incident where user is creating one SC with different line item and it is creating more than one PO while the Basic data are same ie Vendor/Source of Supply,Recipient,PurOrg,Prod Cat etc all are same.
    Should purchaser use Submit to Grouping to make different line items into one PO?
    When we use Carry Out Sourcing-in the extended search tab one field comes like Intended for Grouping (Chech  box) what  does it mean when we check this field.

    Hi,
    Please note that when you order a shopping cart, always a split
    happens at the item level if there is no Fixed Vendor specified
    for the items.
    This is the same case if only a preferred vendor is entered
    entered, because a preferred vendor cannot necessarily be a
    Fixed Vendor.
    However, if the same fixed vendor is specified for all the
    items in the shopping cart, then there would not be any split.
    Unfortunately this is the standard design, as the system cannot put all
    items in the single PO since it would provide the user an option to
    enter different vendors for each item later.
    Apart from the above, the following aspects also need to be ensured :
    Same purchase organisation, purchase group, recipient, pc number,
    pc institute & number of external quotation, etc. then only one PO
    will be created. Otherwise, multiple PO's will be created.
    If you mix services and materials different PO's will be created as the
    type of line is also a precondition for creating multiple local POs.
    Once you ensure that the above is correct, then you should only get one
    PO being created in the backend.
    Please,reward point if useful.
    Christian

  • How to pass/share components between different JPanels/Container

    Dear Friends,
    I know here a lot Java Guru, I met a problem below.
    How can I pass components between different JPanels??
    here, ListPanelMain.java is main,
    When I click a tree node in splitPane, I can see all its children on the right splitpane, but I hope they can be seen on another Panel called "ListRightPane.java"
    How to do it??
    Why cannot pass??
    [1]. main Program:
    package swing.com.test.test;
    import javax.swing.JFrame;
    import java.awt.BorderLayout;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.JTextArea;
    import java.io.Serializable;
    import swing.com.test.test.ListPanel;
    import java.awt.GridLayout;
    public class ListPanelMain implements java.io.Serializable{
         private JFrame frame;
         * Launch the application
         * @param args
         public static void main(String args[]) {
              try {
                   ListPanelMain window = new ListPanelMain();
                   window.frame.setVisible(true);
              } catch (Exception e) {
                   e.printStackTrace();
         * Create the application
         public ListPanelMain() {
              initialize();
         * Initialize the contents of the frame
         private void initialize() {
              frame = new JFrame("FileTreePanelMain");
              frame.setBounds(100, 100, 900, 675);
         //     FieTreePanelComm      ftreecomm                = new      FieTreePanelComm();
              ListPanel                ftree                     = new      ListPanel("C:\\");
    //          ListAllFile           ftree                     = new      ListAllFile("C:\\");
         //     FileTreePanelText      fileTreePanelText      = new      FileTreePanelText(ftreecomm);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              final JPanel panel = new JPanel();
              panel.setLayout(new GridLayout(0, 2));
              frame.getContentPane().add(panel, BorderLayout.CENTER);
         //     final JSplitPane splitPane = new JSplitPane();
         //     frame.getContentPane().add(splitPane, BorderLayout.CENTER);
         //     splitPane.setLeftComponent(ftree);
              panel.add(ftree);
              final ListRightPanel listRightPanel = new ListRightPanel(ftree);
              //splitPane.setRightComponent(listRightPanel);
              panel.add(listRightPanel);
         frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
         System.exit(0);
         frame.pack();
         frame.setVisible(true);
    [2]. Program 2:
    package swing.com.test.test;
    //File System Tree
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.io.File;
    import java.util.Iterator;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.JPanel;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import java.io.Serializable;
    public class ListPanel extends JPanel implements Serializable{
    protected JTree fileTree;
    private FileSystemModel fileSystemModel;
    private JTextArea ltextArea = new JTextArea();
    protected JTextArea fileDetailsTextArea = new JTextArea();
    private String str = "";
         public String getlTextArea() {
                   //textArea.getText();
                   return str;
         public String setlTextArea(String ta) {
                   ltextArea.setText(ta);
                   str = ta;
                   return str;
    public ListPanel(String directory) {
    //super("JTree FileSystem Viewer");
                   setLayout(new BorderLayout());
                   final JPanel panel = new JPanel();
                   panel.setLayout(new BorderLayout());
              add(panel, BorderLayout.CENTER);
    fileDetailsTextArea.setEditable(false);
    fileSystemModel = new FileSystemModel(new File(directory));
    fileTree = new JTree(fileSystemModel);
    fileTree.setEditable(true);
    fileTree.addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent event) {
    System.out.println("1. What we save is: getlTextArea() =" + getlTextArea() );
    File file = (File) fileTree.getLastSelectedPathComponent();
    fileDetailsTextArea.setText(getFileDetails(file));
    final ListRightPanel lrp = new ListRightPanel(this);
    lrp.textArea.setText(getFileDetails(file));
    setlTextArea(getFileDetails(file));
    System.out.println("2. What we save is: getlTextArea() =" + getlTextArea() );
              final JSplitPane splitPane = new JSplitPane();
              panel.add(splitPane, BorderLayout.CENTER);
              final JPanel panel_1 = new JPanel();
              splitPane.setLeftComponent(panel_1);
              panel_1.add(new JScrollPane(fileTree));
              final JPanel panel_2 = new JPanel();
              splitPane.setRightComponent(panel_2);
              panel_2.add(new JScrollPane(fileDetailsTextArea));
    setVisible(true);
    private String getFileDetails(File file) {
    if (file == null)
    return "";
    StringBuffer buffer = new StringBuffer();
    if (file.listFiles()!=null){
         for (int i=0; i< file.listFiles().length; i++){
         buffer.append(((file.listFiles())) + "\n");
         System.out.println("List all files");
    return buffer.toString();
    public static void main(String args[]) {
    new ListPanel("c:\\");
    class FileSystemModel implements TreeModel {
    private File root;
    private Vector listeners = new Vector();
    public FileSystemModel(File rootDirectory) {
    root = rootDirectory;
    public Object getRoot() {
    return root;
    public Object getChild(Object parent, int index) {
    File directory = (File) parent;
    String[] children = directory.list();
    return new TreeFile(directory, children[index]);
    public int getChildCount(Object parent) {
    File file = (File) parent;
    if (file.isDirectory()) {
    String[] fileList = file.list();
    if (fileList != null)
    return file.list().length;
    return 0;
    public boolean isLeaf(Object node) {
    File file = (File) node;
    return file.isFile();
    public int getIndexOfChild(Object parent, Object child) {
    File directory = (File) parent;
    File file = (File) child;
    String[] children = directory.list();
    for (int i = 0; i < children.length; i++) {
    if (file.getName().equals(children[i])) {
    return i;
    return -1;
    public void valueForPathChanged(TreePath path, Object value) {
    File oldFile = (File) path.getLastPathComponent();
    String fileParentPath = oldFile.getParent();
    String newFileName = (String) value;
    File targetFile = new File(fileParentPath, newFileName);
    oldFile.renameTo(targetFile);
    File parent = new File(fileParentPath);
    int[] changedChildrenIndices = { getIndexOfChild(parent, targetFile) };
    Object[] changedChildren = { targetFile };
    fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren);
    private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) {
    TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children);
    Iterator iterator = listeners.iterator();
    TreeModelListener listener = null;
    while (iterator.hasNext()) {
    listener = (TreeModelListener) iterator.next();
    listener.treeNodesChanged(event);
    public void addTreeModelListener(TreeModelListener listener) {
    listeners.add(listener);
    public void removeTreeModelListener(TreeModelListener listener) {
    listeners.remove(listener);
    private class TreeFile extends File {
    public TreeFile(File parent, String child) {
    super(parent, child);
    public String toString() {
    return getName();
    [3]. Program 3:
    package swing.com.test.test;
    import java.awt.BorderLayout;
    import java.io.File;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import java.io.Serializable;
    public class ListRightPanel extends JPanel implements TreeSelectionListener, Serializable{
         protected JTextArea textArea;
    //     protected ListAllFile laf;
    private String str = "";
              public String getlTextArea() {
                        //textArea.getText();
                        return str;
              public String setlTextArea(String ta) {
                        str = ta;
                        return str;
         * Create the panel
         public ListRightPanel(ListPanel laff) {
              super();
              setLayout(new BorderLayout());
              final JPanel panel = new JPanel();
              panel.setLayout(new BorderLayout());
              add(panel, BorderLayout.CENTER);
              textArea = new JTextArea();
    final String st = laff.getlTextArea();
    System.out.println("####################################");
    System.out.println("st=" + st);
         laff.fileTree.addTreeSelectionListener(new TreeSelectionListener() {
         public void valueChanged(TreeSelectionEvent event) {
         //laff.textArea.setText(getFileDetails(file));
              textArea.setText(getlTextArea());
         System.out.println("ListRightPanel Was Invoked from ListPanel!!getlTextArea() =" + getlTextArea() );
         System.out.println("st=" + st);
              panel.add(textArea, BorderLayout.CENTER);
         public void valueChanged(TreeSelectionEvent e){};
    It is runnable program, just compile and run it in Console is ok,
    Regards
    Sunny

    Thnaks, code post again, see
    [1]. package swing.com.test.test;
    import javax.swing.JFrame;
    import java.awt.BorderLayout;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.JTextArea;
    import java.io.Serializable;
    import swing.com.test.test.ListPanel;
    import java.awt.GridLayout;
    public class ListPanelMain implements java.io.Serializable{
         private JFrame frame;
          * Launch the application
          * @param args
         public static void main(String args[]) {
              try {
                   ListPanelMain window = new ListPanelMain();
                   window.frame.setVisible(true);
              } catch (Exception e) {
                   e.printStackTrace();
          * Create the application
         public ListPanelMain() {
              initialize();
          * Initialize the contents of the frame
         private void initialize() {
              frame = new JFrame("FileTreePanelMain");
              frame.setBounds(100, 100, 900, 675);
         //     FieTreePanelComm      ftreecomm                = new       FieTreePanelComm();
              ListPanel                 ftree                     = new      ListPanel("C:\\");
    //          ListAllFile            ftree                     = new      ListAllFile("C:\\");
         //     FileTreePanelText      fileTreePanelText      = new      FileTreePanelText(ftreecomm);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              final JPanel panel = new JPanel();
              panel.setLayout(new GridLayout(0, 2));
              frame.getContentPane().add(panel, BorderLayout.CENTER);
         //     final JSplitPane splitPane = new JSplitPane();
         //     frame.getContentPane().add(splitPane, BorderLayout.CENTER);
         //     splitPane.setLeftComponent(ftree);
              panel.add(ftree);
              final ListRightPanel listRightPanel = new ListRightPanel(ftree);
              //splitPane.setRightComponent(listRightPanel);
              panel.add(listRightPanel);
                frame.addWindowListener(new WindowAdapter() {
                     public void windowClosing(WindowEvent e) {
                         System.exit(0);
                 frame.pack();
                 frame.setVisible(true);
    }[2] Program 2
    package swing.com.test.test;
    //File System Tree
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.io.File;
    import java.util.Iterator;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.JPanel;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import java.io.Serializable;
    public class ListPanel extends JPanel implements Serializable{
      protected JTree fileTree;
      private FileSystemModel fileSystemModel;
      private JTextArea ltextArea = new JTextArea();
      protected JTextArea fileDetailsTextArea = new JTextArea();
      private String str = "";
         public  String getlTextArea()  {
                   //textArea.getText();
                      return str;
         public  String setlTextArea(String ta)  {
                   ltextArea.setText(ta);
                   str = ta;
                      return str;
      public ListPanel(String directory) {
        //super("JTree FileSystem Viewer");
                   setLayout(new BorderLayout());
                   final JPanel panel = new JPanel();
                   panel.setLayout(new BorderLayout());
                  add(panel, BorderLayout.CENTER);
        fileDetailsTextArea.setEditable(false);
        fileSystemModel = new FileSystemModel(new File(directory));
        fileTree = new JTree(fileSystemModel);
        fileTree.setEditable(true);
        fileTree.addTreeSelectionListener(new TreeSelectionListener() {
          public void valueChanged(TreeSelectionEvent event) {
            System.out.println("1. What we save is: getlTextArea() =" + getlTextArea() );
            File file = (File) fileTree.getLastSelectedPathComponent();
            fileDetailsTextArea.setText(getFileDetails(file));
            final ListRightPanel lrp = new ListRightPanel(this);
            lrp.textArea.setText(getFileDetails(file));
            setlTextArea(getFileDetails(file));
            System.out.println("2. What we save is: getlTextArea() =" + getlTextArea() );
              final JSplitPane splitPane = new JSplitPane();
              panel.add(splitPane, BorderLayout.CENTER);
              final JPanel panel_1 = new JPanel();
              splitPane.setLeftComponent(panel_1);
              panel_1.add(new JScrollPane(fileTree));
              final JPanel panel_2 = new JPanel();
              splitPane.setRightComponent(panel_2);
              panel_2.add(new JScrollPane(fileDetailsTextArea));
        setVisible(true);
      private String getFileDetails(File file) {
        if (file == null)
          return "";
        StringBuffer buffer = new StringBuffer();
        if (file.listFiles()!=null){
             for (int i=0; i< file.listFiles().length; i++){
             buffer.append(((file.listFiles())) + "\n");
         System.out.println("List all files");
    return buffer.toString();
    public static void main(String args[]) {
    new ListPanel("c:\\");
    class FileSystemModel implements TreeModel {
    private File root;
    private Vector listeners = new Vector();
    public FileSystemModel(File rootDirectory) {
    root = rootDirectory;
    public Object getRoot() {
    return root;
    public Object getChild(Object parent, int index) {
    File directory = (File) parent;
    String[] children = directory.list();
    return new TreeFile(directory, children[index]);
    public int getChildCount(Object parent) {
    File file = (File) parent;
    if (file.isDirectory()) {
    String[] fileList = file.list();
    if (fileList != null)
    return file.list().length;
    return 0;
    public boolean isLeaf(Object node) {
    File file = (File) node;
    return file.isFile();
    public int getIndexOfChild(Object parent, Object child) {
    File directory = (File) parent;
    File file = (File) child;
    String[] children = directory.list();
    for (int i = 0; i < children.length; i++) {
    if (file.getName().equals(children[i])) {
    return i;
    return -1;
    public void valueForPathChanged(TreePath path, Object value) {
    File oldFile = (File) path.getLastPathComponent();
    String fileParentPath = oldFile.getParent();
    String newFileName = (String) value;
    File targetFile = new File(fileParentPath, newFileName);
    oldFile.renameTo(targetFile);
    File parent = new File(fileParentPath);
    int[] changedChildrenIndices = { getIndexOfChild(parent, targetFile) };
    Object[] changedChildren = { targetFile };
    fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren);
    private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) {
    TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children);
    Iterator iterator = listeners.iterator();
    TreeModelListener listener = null;
    while (iterator.hasNext()) {
    listener = (TreeModelListener) iterator.next();
    listener.treeNodesChanged(event);
    public void addTreeModelListener(TreeModelListener listener) {
    listeners.add(listener);
    public void removeTreeModelListener(TreeModelListener listener) {
    listeners.remove(listener);
    private class TreeFile extends File {
    public TreeFile(File parent, String child) {
    super(parent, child);
    public String toString() {
    return getName();
    [3] Program 3:
    package swing.com.test.test;
    import java.awt.BorderLayout;
    import java.io.File;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import java.io.Serializable;
    public class ListRightPanel extends JPanel implements TreeSelectionListener, Serializable{
         protected JTextArea textArea;
    //     protected ListAllFile  laf;
        private String str = "";
              public  String getlTextArea()  {
                        //textArea.getText();
                           return str;
              public  String setlTextArea(String ta)  {
                        str = ta;
                           return str;
          * Create the panel
         public ListRightPanel(ListPanel  laff) {
              super();
              setLayout(new BorderLayout());
              final JPanel panel = new JPanel();
              panel.setLayout(new BorderLayout());
              add(panel, BorderLayout.CENTER);
              textArea = new JTextArea();
            final String st = laff.getlTextArea();
            System.out.println("####################################");
            System.out.println("st=" + st);
             laff.fileTree.addTreeSelectionListener(new TreeSelectionListener() {
                 public void valueChanged(TreeSelectionEvent event) {
                   //laff.textArea.setText(getFileDetails(file));
                      textArea.setText(getlTextArea());
                     System.out.println("ListRightPanel Was Invoked from ListPanel!!getlTextArea() =" + getlTextArea() );
                     System.out.println("st=" + st);
              panel.add(textArea, BorderLayout.CENTER);
           public void valueChanged(TreeSelectionEvent e){};
    }You can try this one, thanks again
    sunny

  • Reload different panels

    Hello all,
    Like to reload different panels onto the same load panel.
    Code sample below on what I'am trying to achieve
    Each panel size would like to be 45% of window size.
    Have problems of reloading different panels to achieve the size and
    also when resizing the window
    Have 8 dukes to get rid of from:
    http://forum.java.sun.com/thread.jsp?forum=43&thread=431639
    Thanks
    Abraham Khalil
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    * Want to test reloading panels of very different text sizes inside it<br>
    * The goal is no matter want the label text size is, each label panel should only
    * show a maximum of 45% of the window size. <br>
    * <p>
    * Each button on the right will show a more uglier panel to load
    public class PanelChangeTest extends JFrame implements ActionListener {
       private static final int WIDTH = 640;
       private static final int HEIGHT = 400;
       private static final String BUTTON_PANEL_TEST1 = "Load Normal Panel";
       private static final String BUTTON_PANEL_TEST2 = "Load bit ugly Panel";
       private static final String BUTTON_PANEL_TEST3 = "Load very ugly Panel";
       private static final String[] BUTTON_COMMANDS = {
                                                         BUTTON_PANEL_TEST1,
                                                         BUTTON_PANEL_TEST2,
                                                         BUTTON_PANEL_TEST3
       private JPanel loadPanel = new JPanel();
       private PanelChange[] testPanels = null;
        * Model for each panel. <br>
        * Each panel contain email fields of from, to, subject and cc
       private class PanelFields {
          private String from = null;
          private String to = null;
          private String subject = null;
          private String cc = null;
          public PanelFields(String from, String to, String subject, String cc) {
             this.from = from;
             this.to = to;
             this.subject = subject;
             this.cc = cc;
          public String getFrom() {
             return from;
          public String getTo() {
             return to;
          public String getSubject() {
             return subject;
          public String getCC() {
             return cc;
       } // End PanelFields class
        * View panel class <br>
        * Each panel change class will contain four panels and they are from, to, cc and subject panel. <br>
        * Each of the from, to, cc and subject panel contain two labels, one for description and other for
        * its text value.
        * Want to set each panel size to 45% of window size so it looks even, and if label text is too long
        * to fit in 45% view, it should truncate it..
       private class PanelChange extends JPanel {
          private static final float PERCENT = 1 / 100.0f;
          private static final float EACH_PANEL_SIZE = 45 * PERCENT;
          private JPanel getPanel(String labelForText, String text) {
             JLabel labelLeft = new JLabel(labelForText, JLabel.LEFT);
             JLabel labelRight = new JLabel(text, JLabel.LEFT);
             setBold(labelLeft, true);
             JPanel panel = new JPanel();
             panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0));
             panel.add(labelLeft);
             panel.add(labelRight);
             panel.setBorder(BorderFactory.createLineBorder(Color.blue));
             return panel;
          public void recalculate(Dimension parentSize) {
             Dimension eachPanelSize = new Dimension((int) (parentSize.width * EACH_PANEL_SIZE), 12);
             System.out.println("Parent size = (" + parentSize.width + ", " + parentSize.height + ")\n" +
                                "Each panel size is recalculated as (" + eachPanelSize.width + ", " + eachPanelSize.height + ")\n");
             Component[] components = getComponents();       
             for (int eachPanel = 0 ; eachPanel < components.length ; eachPanel++) {
                JComponent panel = (JComponent) components[eachPanel];
                panel.setMaximumSize(eachPanelSize);
                panel.setMinimumSize(eachPanelSize);
                panel.setSize(eachPanelSize);
          public PanelChange(PanelFields panelFields) {
             JPanel fromPanel = getPanel("From: ", panelFields.getFrom());
             JPanel toPanel = getPanel("To: ", panelFields.getTo());        
             JPanel subjectPanel = getPanel("Subject: ", panelFields.getSubject());
             JPanel ccPanel = getPanel("CC: ", panelFields.getCC());
             setLayout(new BorderLayout());
             JPanel panel = new JPanel();
             // Test with panel of GridLayout instead of GridBagLayout to see the difference...     
             panel.setLayout(new GridLayout(2, 2, 5, 5));
             panel.add(fromPanel);
             panel.add(toPanel);
             panel.add(subjectPanel);
             panel.add(ccPanel);
             panel.setLayout(new GridBagLayout());
             constrain(panel, fromPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       0, 0, 1, 1, 1.0, 0.0);
             constrain(panel, toPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       1, 0, 1, 1, 1.0, 0.0);
             constrain(panel, subjectPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       0, 1, 1, 1, 1.0, 0.0);
             constrain(panel, ccPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       1, 1, 1, 1, 1.0, 0.0);
             add(panel, BorderLayout.CENTER);
          private int getFontStyle(Component component, boolean makeBold) {
             int style = 0;
             if (component != null) {
                Font f = component.getFont();
                if (f != null) {
                   if (f.isPlain()) style = style | Font.PLAIN;
                   if (f.isItalic()) style = style | Font.ITALIC;
                   if (makeBold) style = style | Font.BOLD;
             return style;
          private void setBold(Component component, boolean makeBold) {
             int style = getFontStyle(component, makeBold);
             Font styleFont = component.getFont().deriveFont(style);
             component.setFont(styleFont);
       } // End PanelChange class
       public void constrain( Container container, Component component, 
                              int fill, int anchor,
                              int gx, int gy, int gw, int gh, double wx, double wy ) {
          GridBagConstraints c = new GridBagConstraints();
          c.fill = fill;
          c.anchor = anchor;
          c.gridx = gx;
          c.gridy = gy;
          c.gridwidth = gw;
          c.gridheight = gh;
          c.weightx = wx;
          c.weighty = wy;
          ( (GridBagLayout) container.getLayout() ).setConstraints( component, c );
          container.add( component );
       public void constrain( Container container, Component component, 
                              int fill, int anchor,
                              int gx, int gy, int gw, int gh,
                              double wx, double wy, Insets inset ) {
          GridBagConstraints c = new GridBagConstraints();
          c.fill = fill;
          c.anchor = anchor;
          c.gridx = gx;
          c.gridy = gy;
          c.gridwidth = gw;
          c.gridheight = gh;
          c.weightx = wx;
          c.weighty = wy;
          c.insets = inset;
          ( (GridBagLayout) container.getLayout() ).setConstraints( component, c );
          container.add( component );
       private void initPanels() {
          PanelFields okPanel = new PanelFields("Simple from...",
                                                "[email protected]; [email protected]",
                                                "Simple subject...",
                                                "[email protected]; [email protected]");
          PanelFields bitUglyPanel = new PanelFields("A bit ugly from................",
                                                     "[email protected]; [email protected]; [email protected]; [email protected]",
                                                     "A bit ungle subject.....................",
                                                     "[email protected]; [email protected]; [email protected]; [email protected]");
          PanelFields veryUglyPanel = new PanelFields("A very very very very very " +
                                                      "very very ugly from................",
                                                      "[email protected]; [email protected]; [email protected]; [email protected], " +
                                                      "[email protected]; [email protected]; [email protected]; [email protected]",
                                                      "A very very very very very very " +
                                                      "very ungle subject.....................",
                                                      "[email protected]; [email protected]; [email protected]; [email protected]; " +
                                                      "[email protected]; [email protected]; [email protected]; [email protected]");
          testPanels = new PanelChange[] {
                                            new PanelChange(okPanel),
                                            new PanelChange(bitUglyPanel),
                                            new PanelChange(veryUglyPanel)
          Container container = getContentPane();
          container.setLayout(new BorderLayout());
          JPanel buttonPanel = new JPanel();
          buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
          JButton button1 = new JButton(BUTTON_PANEL_TEST1);
          button1.setActionCommand(BUTTON_PANEL_TEST1);
          button1.addActionListener(this);
          JButton button2 = new JButton(BUTTON_PANEL_TEST2);
          button2.setActionCommand(BUTTON_PANEL_TEST2);
          button2.addActionListener(this);
          JButton button3 = new JButton(BUTTON_PANEL_TEST3);
          button3.setActionCommand(BUTTON_PANEL_TEST3);
          button3.addActionListener(this);
          buttonPanel.add(button1);
          buttonPanel.add(Box.createHorizontalStrut(5));
          buttonPanel.add(button2);
          buttonPanel.add(Box.createHorizontalStrut(5));
          buttonPanel.add(button3);
          JPanel mainPanel = new JPanel();
          mainPanel.setLayout(new GridBagLayout());
          constrain(mainPanel, loadPanel,
                    GridBagConstraints.BOTH, GridBagConstraints.WEST,
                    0, 0, 1, 1, 1.0, 1.0, new Insets(5, 5, 5, 5));
          constrain(mainPanel, buttonPanel,
                    GridBagConstraints.NONE, GridBagConstraints.CENTER,
                    0, 1, 1, 1, 0.0, 0.0, new Insets(5, 5, 5, 5));
          container.add(mainPanel);
       private void setupLoadPanel(PanelChange panelToLoad) {
          loadPanel.removeAll();
          panelToLoad.recalculate(getSize());
          loadPanel.add(panelToLoad);
          loadPanel.revalidate();     
       public void actionPerformed(ActionEvent e) {
          String actionCommand = e.getActionCommand();
          for (int i = 0 ; i < BUTTON_COMMANDS.length ; i++) {
             if (actionCommand.equals(BUTTON_COMMANDS)) {
    setupLoadPanel(testPanels[i]);
    break;
    public PanelChangeTest() {
    super("Panel change test...");
    Dimension size = new Dimension(WIDTH, HEIGHT);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (screenSize.width - size.width) / 2;
    int y = (screenSize.height - size.height) / 2;
    setBounds(x, y, WIDTH, HEIGHT);
    addWindowListener(new WindowAdapter() {
    public void windowClosing( WindowEvent e ) {
    System.exit(0);
    FontUIResource standardFont = new FontUIResource("dialogPlain11", Font.PLAIN, 11);
    UIManager.put("Label.font", standardFont);
    UIManager.put("Button.font", standardFont);
    initPanels();
    public static void main(String args[]) {
    new PanelChangeTest().setVisible(true);

    Please use the following code below:
    Somehow it doesn't show the text if it can't fit inside the panel.
    When resize to full screen, it shows the text??
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    * Want to test reloading panels of very different text sizes inside it<br>
    * The goal is no matter want the label text size is, each label panel should only
    * show a maximum of 45% of the window size. <br>
    * <p>
    * Each button on the right will show a more uglier panel to load
    public class PanelChangeTest extends JFrame implements ActionListener {
       private static final int WIDTH = 640;
       private static final int HEIGHT = 400;
       private static final String BUTTON_PANEL_TEST1 = "Load Normal Panel";
       private static final String BUTTON_PANEL_TEST2 = "Load bit ugly Panel";
       private static final String BUTTON_PANEL_TEST3 = "Load very ugly Panel";
       private static final String[] BUTTON_COMMANDS = {
                                                         BUTTON_PANEL_TEST1,
                                                         BUTTON_PANEL_TEST2,
                                                         BUTTON_PANEL_TEST3
       private JPanel loadPanel = new JPanel();
       private PanelChange[] testPanels = null;
        * Model for each panel. <br>
        * Each panel contain email fields of from, to, subject and cc
       private class PanelFields {
          private String from = null;
          private String to = null;
          private String subject = null;
          private String cc = null;
          public PanelFields(String from, String to, String subject, String cc) {
             this.from = from;
             this.to = to;
             this.subject = subject;
             this.cc = cc;
          public String getFrom() {
             return from;
          public String getTo() {
             return to;
          public String getSubject() {
             return subject;
          public String getCC() {
             return cc;
       } // End PanelFields class
        * View panel class <br>
        * Each panel change class will contain four panels and they are from, to, cc and subject panel. <br>
        * Each of the from, to, cc and subject panel contain two labels, one for description and other for
        * its text value.
        * Want to set each panel size to 45% of window size so it looks even, and if label text is too long
        * to fit in 45% view, it should truncate it..
       private class PanelChange extends JPanel {
          private static final float PERCENT = 1 / 100.0f;
          private static final float EACH_PANEL_SIZE = 45 * PERCENT;
          public PanelChange(PanelFields panelFields) {
             JPanel fromPanel = getPanel("From: ", panelFields.getFrom());
             JPanel toPanel = getPanel("To: ", panelFields.getTo());        
             JPanel subjectPanel = getPanel("Subject: ", panelFields.getSubject());
             JPanel ccPanel = getPanel("CC: ", panelFields.getCC());
             setLayout(new BorderLayout());
             JPanel panel = new JPanel();
             // Test with panel of GridLayout instead of GridBagLayout to see the difference...     
             panel.setLayout(new GridLayout(2, 2, 5, 5));
             panel.add(fromPanel);
             panel.add(toPanel);
             panel.add(subjectPanel);
             panel.add(ccPanel);
             panel.setLayout(new GridBagLayout());
             constrain(panel, fromPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       0, 0, 1, 1, 1.0, 0.0);
             constrain(panel, toPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       1, 0, 1, 1, 1.0, 0.0);
             constrain(panel, subjectPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       0, 1, 1, 1, 1.0, 0.0);
             constrain(panel, ccPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       1, 1, 1, 1, 1.0, 0.0);
             add(panel, BorderLayout.CENTER);
          public void recalculate(Dimension parentSize) {
             Dimension eachPanelSize = new Dimension((int) (parentSize.width * EACH_PANEL_SIZE), 20);
             System.out.println("Parent size = (" + parentSize.width + ", " + parentSize.height + ")\n" +
                                "Each panel size is recalculated as (" + eachPanelSize.width + ", " + eachPanelSize.height + ")\n");
             JPanel mainPanel = (JPanel) getComponent(0);
             Component[] components = mainPanel.getComponents();
             for (int eachPanel = 0 ; eachPanel < components.length ; eachPanel++) {
                JComponent panel = (JComponent) components[eachPanel];
                panel.setMaximumSize(eachPanelSize);
                panel.setMinimumSize(eachPanelSize);
                panel.setPreferredSize(eachPanelSize);
          private JPanel getPanel(String labelForText, String text) {
             JLabel labelLeft = new JLabel(labelForText, JLabel.LEFT);
             JLabel labelRight = new JLabel(text, JLabel.LEFT);
             setBold(labelLeft, true);
             JPanel panel = new JPanel();
             panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0));
             panel.add(labelLeft);
             panel.add(labelRight);
             panel.setBorder(BorderFactory.createLineBorder(Color.blue));
             return panel;
          private int getFontStyle(Component component, boolean makeBold) {
             int style = 0;
             if (component != null) {
                Font f = component.getFont();
                if (f != null) {
                   if (f.isPlain()) style = style | Font.PLAIN;
                   if (f.isItalic()) style = style | Font.ITALIC;
                   if (makeBold) style = style | Font.BOLD;
             return style;
          private void setBold(Component component, boolean makeBold) {
             int style = getFontStyle(component, makeBold);
             Font styleFont = component.getFont().deriveFont(style);
             component.setFont(styleFont);
       } // End PanelChange class
       public void constrain( Container container, Component component, 
                              int fill, int anchor,
                              int gx, int gy, int gw, int gh, double wx, double wy ) {
          GridBagConstraints c = new GridBagConstraints();
          c.fill = fill;
          c.anchor = anchor;
          c.gridx = gx;
          c.gridy = gy;
          c.gridwidth = gw;
          c.gridheight = gh;
          c.weightx = wx;
          c.weighty = wy;
          ( (GridBagLayout) container.getLayout() ).setConstraints( component, c );
          container.add( component );
       public void constrain( Container container, Component component, 
                              int fill, int anchor,
                              int gx, int gy, int gw, int gh,
                              double wx, double wy, Insets inset ) {
          GridBagConstraints c = new GridBagConstraints();
          c.fill = fill;
          c.anchor = anchor;
          c.gridx = gx;
          c.gridy = gy;
          c.gridwidth = gw;
          c.gridheight = gh;
          c.weightx = wx;
          c.weighty = wy;
          c.insets = inset;
          ( (GridBagLayout) container.getLayout() ).setConstraints( component, c );
          container.add( component );
       private void initPanels() {
          PanelFields okPanel = new PanelFields("Simple from...",
                                                "[email protected]; [email protected]",
                                                "Simple subject...",
                                                "[email protected]; [email protected]");
          PanelFields bitUglyPanel = new PanelFields("A bit ugly from................",
                                                     "[email protected]; [email protected]; [email protected]; [email protected]",
                                                     "A bit ungle subject.....................",
                                                     "[email protected]; [email protected]; [email protected]; [email protected]");
          PanelFields veryUglyPanel = new PanelFields("A very very very very very " +
                                                      "very very ugly from................",
                                                      "[email protected]; [email protected]; [email protected]; [email protected], " +
                                                      "[email protected]; [email protected]; [email protected]; [email protected]",
                                                      "A very very very very very very " +
                                                      "very ungle subject.....................",
                                                      "[email protected]; [email protected]; [email protected]; [email protected]; " +
                                                      "[email protected]; [email protected]; [email protected]; [email protected]");
          testPanels = new PanelChange[] {
                                            new PanelChange(okPanel),
                                            new PanelChange(bitUglyPanel),
                                            new PanelChange(veryUglyPanel)
          Container container = getContentPane();
          container.setLayout(new BorderLayout());
          JPanel buttonPanel = new JPanel();
          buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
          JButton button1 = new JButton(BUTTON_PANEL_TEST1);
          button1.setActionCommand(BUTTON_PANEL_TEST1);
          button1.addActionListener(this);
          JButton button2 = new JButton(BUTTON_PANEL_TEST2);
          button2.setActionCommand(BUTTON_PANEL_TEST2);
          button2.addActionListener(this);
          JButton button3 = new JButton(BUTTON_PANEL_TEST3);
          button3.setActionCommand(BUTTON_PANEL_TEST3);
          button3.addActionListener(this);
          buttonPanel.add(button1);
          buttonPanel.add(Box.createHorizontalStrut(5));
          buttonPanel.add(button2);
          buttonPanel.add(Box.createHorizontalStrut(5));
          buttonPanel.add(button3);
          JPanel mainPanel = new JPanel();
          mainPanel.setLayout(new GridBagLayout());
          constrain(mainPanel, loadPanel,
                    GridBagConstraints.BOTH, GridBagConstraints.WEST,
                    0, 0, 1, 1, 1.0, 1.0, new Insets(5, 5, 5, 5));
          constrain(mainPanel, buttonPanel,
                    GridBagConstraints.NONE, GridBagConstraints.CENTER,
                    0, 1, 1, 1, 0.0, 0.0, new Insets(5, 5, 5, 5));
          container.add(mainPanel);
       private void setupLoadPanel(PanelChange panelToLoad) {
          loadPanel.removeAll();
          Dimension parentSize = getSize();
          panelToLoad.recalculate(parentSize);     
          loadPanel.add(panelToLoad);
          loadPanel.revalidate();
          loadPanel.repaint(); 
       public void actionPerformed(ActionEvent e) {
          String actionCommand = e.getActionCommand();
          for (int i = 0 ; i < BUTTON_COMMANDS.length ; i++) {
             if (actionCommand.equals(BUTTON_COMMANDS)) {
    setupLoadPanel(testPanels[i]);
    break;
    public PanelChangeTest() {
    super("Panel change test...");
    Dimension size = new Dimension(WIDTH, HEIGHT);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (screenSize.width - size.width) / 2;
    int y = (screenSize.height - size.height) / 2;
    setBounds(x, y, WIDTH, HEIGHT);
    addWindowListener(new WindowAdapter() {
    public void windowClosing( WindowEvent e ) {
    System.exit(0);
    FontUIResource standardFont = new FontUIResource("dialogPlain11", Font.PLAIN, 11);
    UIManager.put("Label.font", standardFont);
    UIManager.put("Button.font", standardFont);
    initPanels();
    public static void main(String args[]) {
    new PanelChangeTest().setVisible(true);

Maybe you are looking for

  • What can I do if script runs faster than network?

    I've written an inter-application script that moves from InDesign, where it starts in AppleScript, to Photoshop, where the AppleScript runs a JavaScript to perform various tasks. It runs beautifully on my laptop at home where I do my development. Yes

  • Hardware test and disk repair

    Hi: I'm relatively new to the mac world and I have a Mini, core solo, intel. I have two questions that I hope you can answer: 1. How do I do a hardware test? 2. How do I repair the disk via the CD that came with the Mini? When I install the disk, it

  • Bus powered external Firewire drives

    Most portable external drives are now bus powered, many don't even have a power input. I wonder how many bus powered Firewire driives I can daisy-chain. Where should I place them, at the beginnig, in the middle, or the end of the daisy chain. I have

  • What is the Transport Seekvence in R3  and in BW

    Hi, i have Two Doubts, i have to transport the requests from DEV to QA. 1. what is the Transport Seekvence in <b>R3 DEV to R3 QA</b>    and <b>BW DEV to BW QA.</b> 2.in R/3 i have not cerated Logical System, is i have to creat Logical System. if i ha

  • Creative Zen j

    Headphone jack, do creative know that there is a headphone jack prob, if so, why dont they fit there new products eg sleek with good jacks, crwati've owners should get extedneded warrenty from creative for free for the jack,s