Unfair resizing in BorderLayout

Greetings:
I have a panel with border layout. There are two scroll panes
on West and East and a scroll panel in the Center.
Both West and East panels host JTree in them. The middle
scroll pane hosts JPanel with bunch of JLabel+ JTestField's.
The problem is that when the frame is resized or any of the
JTree's get expanded, the middle pane is squeezed to almost
nothing. Endless playing with setting size constraints does
not seem to make any good. The layout manager still likes
JTree much better than any other components.
Also, when the middle pane has the horizontal scroll bar visible,
the components get corrupted when scrolled from right side.
Any idea?
Thanks.
Vlad

I think the BorderLayout uses as much space as needed for North and South, then as much as needed for West and East, and, finally, allocates the rest to Center.
You might try putting your three ScrollPanes in a BoxLayout.
Good luck,
  -- Scott

Similar Messages

  • AVReceive2 in a Web

    Hello.
    I want to create a web that reproduce the video and the audio that AVReceive2 receives.
    the video and the audio must be in the same player, like a normal Video in youtube.
    Thank u in advance.

    Looking at the code for JMFApplet, it shouldn't open a new window. It specificlly embeds the Player object into the applet.
            // Now that we have a Realized player, we can get the
            // VisualComponent and ControlPanelComponent and pack
            // them into our applet.
            myVisual = myPlayer.getVisualComponent();
            if (myVisual != null) {
               // In order to ensure that the VisualComponent
               // is not resized by BorderLayout, I nest it
               // within visualPanel using FlowLayout.
               visualPanel = new Panel();
               visualPanel.setLayout(new FlowLayout());
               visualPanel.add(myVisual);
               add("Center",visualPanel);
            } else {
               remove(status);
               add("Center",status);
               status.setText("No VisualComponent available.");
            myControls = myPlayer.getControlPanelComponent();
            if (myControls != null) {
               add("South",myControls);
            validate();So, do that...

  • BorderLayout vs SpringLayout : resizing application user interface

    I have an application that resized (i.e. maximized to fill monitor) readily when I used BorderLayout. After changing the layout to SpringLayout, I am happier with my user interface but it does not maximize.
    Actually it does maximize, but it leaves the rest of the larger screen blank. Any ideas on how to fix that? So that the entire user interface fills the window whether maximized or smaller?
    Thanks.

    Follow the link to the Swing tutorials from the topic listing page for this forum and go through the trail on Laying out Components in a Container. After that, if you have a specific issue with your layout, post a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://mindprod.com/jgloss/sscce.html] that demonstrates the problem.
    When you do so, use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db

  • JPanel not resizing BorderLayout.CENTER component

    I have a JPanel (panel_1) with a BorderLayout. In response to a mous event, I want to replace the component at BorderLayout.CENTER. I'm tracking which component is currently there, so when i get the event, I remove the component currently there, and then add a different one using add(component, BorderLayout.CENTER), and then for good measure I call getLayout().layoutContainer(this) (where "this" is panel_1). At this point, I've got another JPanel, panel_2, in the CENTER position of PANEL_1, and I can see that it's been resized correctly. However, panel_2 also has a BorderLayout, and has a JScrollPane in it's CENTER position. adding panel_2 to panel_1 at center, and redoing the layout, doesn't resize the ScrollPane inside panel_2, even though panel_2 itself is resized.
    Furthermore, in panel_2, I tried overloading setSize(int, int), setSize(Dimension), resize(int, int), resize(Dimension), and even reshape(int, int, int, int), and none of them got called during the layout, but it's size still comes out different on the other side of the layout.
    Can anyone suggest a good way to automatically resize the JScrollPane when the parent container (panel_2) is resized? Is this normal behvior? I thought that BorderLayout was supposed to do this automatically?
    Message was edited by:
    B.Mearns

    LayoutManagers uses the preferredSize to help layout components. The size means nothing, so using setSize() will not help. You should be using setPreferredSize(...).
    You may also want to look at using a [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]Card Layout which is designed to flip back and forth between multiple panels in the same container.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Jpanel, resize, borderlayout, browser, applet

    Sorry i cant find a good topic for my problem. :) I have an applet with a borderlayout, each time the browser is resize, my applet component is resize too , its ok, BUT i need to put a maximum size for my JPanel (in "Center"), is there a way to change the way that the automatic resize works? I explain why, i have a JPanel, the center one, that have a picture draw on it, when the view area of the JPanel is tiner than the size of the image, i put scrollbar, but i dont want to have the view area bigger than the picture..
    so is there a way
    sorry another time, when i have something long to explain in english, it could be not understandable :)
    thx a lot in advance

    try this, maybe works as you want,
    here component is you JPanel;
    Component component = new Component(){
    public Dimensin getMaximumSize()
    return new Dimension( 100, 100 ); // your picture size
    and as this you can overwrite
    getMinimumSize() and getPreferredSize() methods,
    Sorry i cant find a good topic for my problem. :) I
    have an applet with a borderlayout, each time the
    browser is resize, my applet component is resize too ,
    its ok, BUT i need to put a maximum size for my JPanel
    (in "Center"), is there a way to change the way that
    the automatic resize works? I explain why, i have a
    JPanel, the center one, that have a picture draw on
    it, when the view area of the JPanel is tiner than the
    size of the image, i put scrollbar, but i dont want to
    have the view area bigger than the picture..
    so is there a way
    sorry another time, when i have something long to
    explain in english, it could be not understandable :)
    thx a lot in advance

  • Resizing JButtons in a BorderLayout

    Hi, I've been working with a BorderLayout and whenever I try and set a JButton's size or preferredSize, it always ignores what I set it at and puts it's size as filling the entire BorderLayout.CENTER. Any ideas?

    {color:#507C9A}1. In future, post Swing questions in the Swing forum: http://forum.java.sun.com/forum.jspa?forumID=57
    2. The behaviour of a Borderlayout is to ignore a component's preferredSize and stretch it to fill the centre.
    Solution: nest.
    JPanel withBorderLayout = ...
    JButton btn = ...
    //withBorderLayout .add(btn, BorderLayout.CENTER);
    JPanel centrePanel = new JPanel(); //FlowLayout by default, you may want to change this
    centrePanel .add(btn);
    withBorderLayout .add(centrePanel , BorderLayout.CENTER);{color}

  • BorderLayout - cant resize

    i added some buttons on BorderLayout.SOUTH, but the SOUTH size is too small to fit in all the buttons i have added.

    I assume you added the buttons to a panel and that panel is in the SOUTH of a larger panel, m'kay?
    What layout manager is the smaller panel using?
    When did you add the buttons, before or after you packed the frame?
    The best thing to do, as always, is to post a SSCCE: [http://mindprod.com/jgloss/sscce.html]
    And in future, post Swing questions to the Swing forum.

  • Resized animated gif ImageIcon not working properly with JButton etc.

    The problem is that when I resize an ImageIcon representing an animated gif and place it on a Jbutton, JToggelButton or JLabel, in some cases the image does not show or does not animate. More precicely, depending on the specific image file, the image shows always, most of the time or sometimes. Images which are susceptible to not showing often do not animate when showing. Moving over or clicking with the mouse on the AbstractButton instance while the frame is supposed to updated causes the image to disappear (even when viewing the non-animating image that sometimes appears). No errors are thrown.
    Here some example code: (compiled with Java 6.0 compliance)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test
         public static void main(String[] args)
              new Test();
         static final int  IMAGES        = 3;
         JButton[]           buttons       = new JButton[IMAGES];
         JButton             toggleButton  = new JButton("Toggle scaling");
         boolean            doScale       = true;
         public Test()
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel p = new JPanel(new GridLayout(1, IMAGES));
              for (int i = 0; i < IMAGES; i++)
                   p.add(this.buttons[i] = new JButton());
              f.add(p, BorderLayout.CENTER);
              f.add(this.toggleButton, BorderLayout.SOUTH);
              this.toggleButton.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e)
                        Test.this.refresh();
              f.setSize(600, 300);
              f.setVisible(true);
              this.refresh();
         public void refresh()
              this.doScale = !this.doScale;
              for (int i = 0; i < IMAGES; i++)
                   ImageIcon image = new ImageIcon(i + ".gif");
                   if (this.doScale)
                        image = new ImageIcon(image.getImage().getScaledInstance(180, 180, Image.SCALE_AREA_AVERAGING));
                   image.setImageObserver(this.buttons);
                   this.buttons[i].setIcon(image);
                   this.buttons[i].setSelectedIcon(image);
                   this.buttons[i].setDisabledIcon(image);
                   this.buttons[i].setDisabledSelectedIcon(image);
                   this.buttons[i].setRolloverIcon(image);
                   this.buttons[i].setRolloverSelectedIcon(image);
                   this.buttons[i].setPressedIcon(image);
    Download the gif images here:
    http://djmadz.com/zombie/0.gif
    http://djmadz.com/zombie/1.gif
    http://djmadz.com/zombie/2.gif
    When you press the "Toggle scaling"button it switches between unresized (properly working) and resized instances of three of my gif images. Notice that the left image almost never appears, the middle image always, and the right image most of the time. The right image seems to (almost) never animate. When you click on the left image (when visble) it disappears only when the backend is updating the animation (between those two frames with a long delay)
    Why are the original ImageIcon and the resized ImageIcon behaving differently? Are they differently organized internally?
    Is there any chance my way of resizing might be wrong?

    It does work, however I refuse to use SCALE_REPLICATE for my application because resizing images is butt ugly, whether scaling up or down. Could there be a clue in the rescaling implementations, which I can override?
    Maybe is there a way that I can check if an image is a multi-frame animation and set the scaling algorithm accordingly?
    Message was edited by:
    Zom-B

  • Resizing an apps window interrupts mplayer

    Hi all,
    I use mplayer to play music from internet radio but when I resize another apps window, the music is interrupted. I have an AMD Athlon 64x2 2.4GHz machine and this seems rather unacceptable to me... ;-) I have always used a custom-compiled kernel on my Arch x86-64 installation but this problem seems to have started with using a custom 2.6.24.x kernel.
    Any hints on what kernel config item(s) could produce this problem? Is it a matter of unfair multitasking resource allocation?
    My thanks in advance.

    On the mini, try booting into the Safe Mode using your normal account.  Disconnect all peripherals except those needed for the test. Shut down the computer and then power it back up after waiting 10 seconds. Immediately after hearing the startup chime, hold down the shift key and continue to hold it until the gray Apple icon and a progress bar appear and again when you log in. The boot up is significantly slower than normal. This will reset some caches, forces a directory check, and disables all startup and login items, among other things. When you reboot normally, the initial reboot may be slower than normal. If the system operates normally, there may be 3rd party applications which are causing a problem. Try deleting/disabling the third party applications after a restart by using the application un-installer. For each disable/delete, you will need to restart if you don’t do them all at once.
    Safe Mode - About
    Safe Mode - Yosemite
    Apple doesn’t routinely monitor the discussions. These are mostly user to user discussions.
    Send Apple feedback. They won't answer, but at least will know there is a problem. If enough people send feedback, it may get the problem solved sooner.
    Feedback
    Or you can use your Apple ID to register with this site and go the Apple BugReporter. Supposedly you will get an answer if you submit feedback.
    Feedback via Apple Developer

  • How can I create JEditorPane which scrolls to the bottom on every resize?

    JRE 1.3.0
    Included a simple frame with the only control - JEditorPane (contained within JScrollPane). Every time scroll pane size changes, attempt to scroll down to the end of JEditorPane is made.
    The problem is: although everything works 9 times of 10, sometimes editor is scrolled almost to the end, sometimes - to the very top. On the next resize editor is scrolled correctly.
    I think, there are some delayed layout recalculations inside SWING which prevent JEditorPane and/or JScrollPane from knowing actual size.
    Is it possible to force JEditorPane+JScrollPane pair to update dimensions? ( explicit call to doLayout() does not fix anything )
    Thanks
    public class TestFrame extends JFrame
    BorderLayout borderLayout1 = new BorderLayout();
    JScrollPane jScrollPane1 = new JScrollPane();
    JEditorPane jEditorPane1 = new JEditorPane();
    public TestFrame()
    try
    jbInit();
    catch(Exception e)
    e.printStackTrace();
    private void jbInit() throws Exception
    this.getContentPane().setLayout(borderLayout1);
    jEditorPane1.setContentType("text/html");
    jEditorPane1.setText("test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test ");
    jScrollPane1.addComponentListener(new java.awt.event.ComponentAdapter()
    public void componentResized(ComponentEvent e)
    jScrollPane1_componentResized(e);
    this.getContentPane().add(jScrollPane1, BorderLayout.CENTER);
    jScrollPane1.getViewport().add(jEditorPane1, null);
    void jScrollPane1_componentResized(ComponentEvent e)
    Dimension size = jEditorPane1.getPreferredSize();
    jEditorPane1.scrollRectToVisible( new Rectangle(0, size.height, 0, 0) );
    System.out.println("preferred height=" + size.height);
    }

    Seen this thread?
    Return to previously viewed page

  • Animated gif resizing problem

    Im trying to achieve the following: showing an animated gif that resizes to fill the area of a canvas. I tried the easy way: adding a label and setting the icon for that label, but when trying to resize the image it doesnt show (see code below). Is there any particular way of resizing an animated gif? can the labe-icon approach be used with animated gif that must be resized?
    Thanks a lot in advance.
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Image;
    import javax.swing.ImageIcon;
    public class TestFrame extends javax.swing.JFrame {
    /** Creates new form TestFrame */
    public TestFrame() {
    initComponents();
    Image image = this.getToolkit().getImage("C:\\multivideo\\img\\39.gif");
    Dimension dim = jLabel1.getPreferredSize();
    image = image.getScaledInstance(dim.width, dim.height, Image.SCALE_SMOOTH);
    ImageIcon i = new ImageIcon(image);
    jLabel1.setIcon(i);
    jLabel1.setBackground(Color.BLUE);
    pack();
    /** This method is called from within the constructor to
    * initialize the form.
    private void initComponents()
    jLabel1 = new javax.swing.JLabel();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel1.setIcon(new javax.swing.ImageIcon("C:\\multivideo\\img\\40.gif"));
    jLabel1.setMaximumSize(new java.awt.Dimension(1436, 86));
    jLabel1.setMinimumSize(new java.awt.Dimension(1436, 86));
    jLabel1.setPreferredSize(new java.awt.Dimension(1436, 86));
    getContentPane().add(jLabel1, java.awt.BorderLayout.CENTER);
    pack();
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new TestFrame().setVisible(true);
    private javax.swing.JLabel jLabel1;
    }

    I don't think getScaledInstance is smart enough to return a scaled image.
    You could try doing your own scaling:
    import java.awt.*;
    import java.awt.geom.*;
    import java.net.*;
    import javax.swing.*;
    public class Animated extends JComponent {
        private Image image;
        private double scale;
        public Animated(URL url, double scale) {
            image = new ImageIcon(url).getImage();
            this.scale = scale;
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Insets insets = getInsets();
            Graphics2D g2 = (Graphics2D) g.create();
            g2.translate(insets.left, insets.top);
            g2.scale(scale, scale);
            g2.drawImage(image, 0, 0, this);
            g2.dispose();
        public Dimension getPreferredSize() {
            Insets insets = getInsets();
            int w = insets.left + insets.right + (int)(scale*image.getWidth(null));
            int h = insets.top + insets.bottom + (int)(scale*image.getHeight(null));
            return new Dimension(w,h);
        public static void main(String[] args) throws MalformedURLException {
            URL url = new URL("http://members.aol.com/royalef/sunglass.gif");
            final JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new Animated(url, 2), BorderLayout.NORTH);
            f.getContentPane().add(new Animated(url, 1), BorderLayout.SOUTH);
            f.pack();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }Or you could explicitly extract the images from the animated gif and
    resize them individually. The sample code here does the extraction:
    http://forum.java.sun.com/thread.jspa?forumID=20&threadID=500348

  • How to resize a custom tree node like you would a JFrame window?

    Hello,
    I am trying to resize a custom tree node like you would a JFrame window.
    As with a JFrame, when your mouse crosses the Border, the cursor should change and you are able to drag the edge to resize the node.
    However, I am faced with a problem. Border cannot detect this and I dont want to use a mouse motion listener (with a large number of nodes, I fear it will be inefficient, calculating every node's position constantly).
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Insets;
    import java.util.EventObject;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeSelectionModel;
    public class ResizeNode extends JPanel {
           AnilTreeCellRenderer2 atcr;
           AnilTreeCellEditor2 atce;
           DefaultTreeModel treeModel;
           JTree tree;
           DefaultMutableTreeNode markedNode = null;
         public ResizeNode() {
                super(new BorderLayout());
                   treeModel = new DefaultTreeModel(null);
                   tree = new JTree(treeModel);          
                  tree.setEditable(true);
                   tree.getSelectionModel().setSelectionMode(
                             TreeSelectionModel.SINGLE_TREE_SELECTION);
                   tree.setShowsRootHandles(true);
                  tree.setCellRenderer(atcr = new AnilTreeCellRenderer2());
                  tree.setCellEditor(atce = new AnilTreeCellEditor2(tree, atcr));
                   JScrollPane scrollPane = new JScrollPane(tree);
                   add(scrollPane,BorderLayout.CENTER);
         public void setRootNode(DefaultMutableTreeNode node) {
              treeModel.setRoot(node);
              treeModel.reload();
           public static void main(String[] args){
                ResizeNode tb = new ResizeNode();
                tb.setPreferredSize(new Dimension(400,200));
                  JFrame frame = new JFrame("ResizeNode");
                  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                  frame.setContentPane(tb);
                  frame.setSize(400, 200);
                  frame.pack();
                  frame.setVisible(true);
                  tb.populate();
         private void populate() {
              TextAreaNode2 r = new TextAreaNode2(this);
               setRootNode(r);
               TextAreaNode2 a = new TextAreaNode2(this);
               treeModel.insertNodeInto(a, r, r.getChildCount());          
    class AnilTreeCellRenderer2 extends DefaultTreeCellRenderer{
    TreeBasic panel;
    DefaultMutableTreeNode currentNode;
      public AnilTreeCellRenderer2() {
         super();
    public Component getTreeCellRendererComponent
       (JTree tree, Object value, boolean selected, boolean expanded,
       boolean leaf, int row, boolean hasFocus){
         TextAreaNode2 currentNode = (TextAreaNode2)value;
         NodeGUI2 gNode = (NodeGUI2) currentNode.gNode;
        return gNode.box;
    class AnilTreeCellEditor2 extends DefaultTreeCellEditor{
      DefaultTreeCellRenderer rend;
      public AnilTreeCellEditor2(JTree tree, DefaultTreeCellRenderer r){
        super(tree, r);
        rend = r;
      public Component getTreeCellEditorComponent(JTree tree, Object value,
       boolean isSelected, boolean expanded, boolean leaf, int row){
        return rend.getTreeCellRendererComponent(tree, value, isSelected, expanded,
         leaf, row, true);
      public boolean isCellEditable(EventObject event){
        return true;
    class NodeGUI2 {
         final ResizeNode view;
         Box box = Box.createVerticalBox();
         final JTextArea aa = new JTextArea( 1, 5 );
         final JTextArea aaa = new JTextArea( 1, 8 );
         NodeGUI2( ResizeNode view_ ) {
              this.view = view_;
              box.add( aa );
              aa.setBorder( BorderFactory.createMatteBorder( 0, 0, 1, 0, Color.GREEN ) );
              box.add( aaa );
              box.setBorder( BorderFactory.createMatteBorder( 5, 5, 5, 5, Color.CYAN ) );
         private Dimension getEditorPreferredSize() {
              Insets insets = box.getInsets();
              Dimension boxSize = box.getPreferredSize();
              Dimension aaSize = aa.getPreferredSize();
              Dimension aaaSize = aaa.getPreferredSize();
              int height = aaSize.height + aaaSize.height + insets.top + insets.bottom;
              int width = Math.max( aaSize.width, aaaSize.width );
              if ( width < boxSize.width )
                   width += insets.right + insets.left + 3;     // 3 for cursor
              return new Dimension( width, height );               
    class TextAreaNode2 extends DefaultMutableTreeNode {  
         NodeGUI2 gNode;
         TextAreaNode2(ResizeNode view_) {     
              gNode = new NodeGUI2(view_);
    }

    the node on the tree is only painted on using the
    renderer to do the painting work. A mouse listener
    has to be added to the tree, and when moved over an
    area, you have to determine if you are over the
    border and which direction to update the cursor and
    to know which way to resize when dragged. One of the
    BasicRootPaneUI has some code that can help determine
    that.Thanks for replying. What is your opinion on this alternative idea that I just had?
    I am wondering if it might be easier to have a toggle button in the node that you click when you want to resize the node. Then a mouse-down and dragging the mouse will resize the node. Mouse-up will reset the toggle button, and so will mouse down in an invalid area.
    Anil

  • Why table getWidth and setWidth is not working when resize column the table

    hi all,
    i want to know why the setWidth is not working in the following code,
    try to uncomment the code in columnMarginChanged method and run it wont resize the table.
    i cont set width(using setWidth) of the other table column using getWidth of the main table column.
    and i want to resize the right side columns only (you can check when you resize the any column the left and right side columns also resizing)
    any suggestions could be helpful.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.TableColumnModelEvent;
    import javax.swing.event.TableColumnModelListener;
    import javax.swing.table.TableColumnModel;
    public class SynTableResize extends JFrame implements TableColumnModelListener, ActionListener
        JTable  table1       = new JTable(5, 5);
        JTable  table2       = new JTable(5, 5);
        JTable  table3       = new JTable(5, 5);
        JButton btn          = new JButton("refresh");
        JPanel  pnlcontainer = new JPanel();
        public SynTableResize()
            setLayout(new BorderLayout());
            pnlcontainer.setLayout(new BoxLayout(pnlcontainer, BoxLayout.Y_AXIS));
            pnlcontainer.add(table1.getTableHeader());
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(table2);
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(table3);
            table2.setTableHeader(null);
            table3.setTableHeader(null);
            table1.getColumnModel().addColumnModelListener(this);
            table3.setColumnModel(table1.getColumnModel());
            table2.setColumnModel(table1.getColumnModel());
            table2.getColumnModel().addColumnModelListener(table1);
            table3.getColumnModel().addColumnModelListener(table1);
            btn.addActionListener(this);
            getContentPane().add(pnlcontainer, BorderLayout.CENTER);
            getContentPane().add(btn, BorderLayout.SOUTH);
            setSize(new Dimension(400, 400));
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        public static void main(String[] args)
            new SynTableResize();
        public void columnAdded(TableColumnModelEvent e)
        public void columnMarginChanged(ChangeEvent e)
            TableColumnModel tcm = table1.getColumnModel();
            int columns = tcm.getColumnCount();
            for (int i = 0; i < columns; i++)
                table2.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getWidth());
                table3.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getWidth());
                // the following commented code wont work.
    //            table2.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getPreferredWidth());
    //            table3.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getPreferredWidth());
    //            table2.getColumnModel().getColumn(i).setWidth(tcm.getColumn(i).getWidth());
    //            table3.getColumnModel().getColumn(i).setWidth(tcm.getColumn(i).getWidth());
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    table2.revalidate();
                    table3.revalidate();
        public void columnMoved(TableColumnModelEvent e)
        public void columnRemoved(TableColumnModelEvent e)
        public void columnSelectionChanged(ListSelectionEvent e)
        public void actionPerformed(ActionEvent e)
            JTable table = new JTable(5, 5);
            table.setColumnModel(table1.getColumnModel());
            table.getColumnModel().addColumnModelListener(table1);
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(table);
            pnlcontainer.validate();
            pnlcontainer.repaint();
    }thanks
    dayananda b v

    hi,
    thanks for your replay,
    yes i know that, you can check the following code it works fine.
    actually what i want is, when i resize table column it shold not automaticaly reszie when table resized and i dont want horizontal scroll bar, meaning that all table columns should resize with in the table size(say width 300)
    if i make table autoresize off than horizontal scroll bar will appear and the other columns moved and i want scroll to view other columns.
    please suggest me some way doing it, i tried with doLayout() no help,
    doLayout() method only can be used when table resizes. first off all i want to restrict table resizing with in the limited size
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.event.ChangeEvent;
    import javax.swing.table.TableColumnModel;
    public class TempSycnTable extends JFrame
        JTable  table1       = new JTable(5, 5);
        MyTable table2       = new MyTable(5, 5);
        MyTable table3       = new MyTable(5, 5);
        JPanel  pnlcontainer = new JPanel();
        public TempSycnTable()
            JScrollPane src2 = new JScrollPane(table2);
            JScrollPane src3 = new JScrollPane(table3);
    //        table1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //        table2.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //        table3.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //        src2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    //        src3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            table2.setTableHeader(null);
            table3.setTableHeader(null);
            table3.setColumnModel(table1.getColumnModel());
            table2.setColumnModel(table1.getColumnModel());
            table2.getColumnModel().addColumnModelListener(table1);
            table3.getColumnModel().addColumnModelListener(table1);
            table2.setTableHeader(null);
            table3.setTableHeader(null);
            setLayout(new BorderLayout());
            pnlcontainer.setLayout(new BoxLayout(pnlcontainer, BoxLayout.Y_AXIS));
            pnlcontainer.add(table1.getTableHeader());
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(src2);
            pnlcontainer.add(Box.createVerticalStrut(5));
            pnlcontainer.add(src3);
            getContentPane().add(pnlcontainer, BorderLayout.CENTER);
            setSize(new Dimension(300, 300));
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        public static void main(String[] args)
            new TempSycnTable();
        class MyTable extends JTable
            public MyTable()
                super();
            public MyTable(int numRows, int numColumns)
                super(numRows, numColumns);
            public void columnMarginChanged(ChangeEvent event)
                final TableColumnModel eventModel = table1.getColumnModel();
                final TableColumnModel thisModel = getColumnModel();
                final int columnCount = eventModel.getColumnCount();
                for (int i = 0; i < columnCount; i++)
                    thisModel.getColumn(i).setWidth(eventModel.getColumn(i).getWidth());
                repaint();
    }thanks
    daya

  • How to have automatic resizing of container when JInternalFrame resizes?

    Is there a good way for the automatic resizing of its container when a JInternalFrame is resized?
    The intent is to have the JTree below, automatically resize. for example,
    if you type newlines into the JTextArea contained in JInternalFrames.
    (Tried adding the JInternalFrames to a JDesktopPane, but it did not display them. I wonder if it is inefficient to have a JDesktopPane for each tree node).
    Is there any way to know if a JInternalFrame is resizing? Perhaps then one can reload the tree as:
    treeModel.reload()thanks,
    Anil
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.util.EventObject;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextArea;
    import javax.swing.JToggleButton;
    import javax.swing.JTree;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeSelectionModel;
    public class TreeFrames extends JPanel {
           AnilTreeCellRenderer3 atcr;
           AnilTreeCellEditor4 atce;
           DefaultTreeModel treeModel;
           JTree tree;
         public TreeFrames() {
                super(new BorderLayout());
                   treeModel = new DefaultTreeModel(null);
                   tree = new JTree(treeModel);
                  tree.setEditable(true);
                   tree.getSelectionModel().setSelectionMode(
                             TreeSelectionModel.SINGLE_TREE_SELECTION);
                   tree.setShowsRootHandles(true);
                  tree.setCellRenderer(atcr = new AnilTreeCellRenderer3());
                  tree.setCellEditor(atce = new AnilTreeCellEditor4(tree, atcr));
                   JScrollPane scrollPane = new JScrollPane(tree);
                   add(scrollPane,BorderLayout.CENTER);
         public void setRootNode(DefaultMutableTreeNode node) {
              treeModel.setRoot(node);
              treeModel.reload();
           public static void main(String[] args) throws ClassNotFoundException,
           InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException{
                TreeFrames tb = new TreeFrames();
                tb.setPreferredSize(new Dimension(800,600));
                  JFrame frame = new JFrame("Tree Windows UI Failed");
                  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                  frame.setContentPane(tb);
                  frame.setSize(800, 600);
                  frame.pack();
                  frame.setVisible(true);
                  tb.populate();
         private void populate() {
              TextAreaNode3 r = new TextAreaNode3(this);
              setRootNode(r);
              r.gNode.addFrame();
              r.gNode.addFrame();
              TextAreaNode3 a = new TextAreaNode3(this);
              a.gNode.addFrame();
              treeModel.insertNodeInto(a, r, r.getChildCount());
              treeModel.reload();
    class AnilTreeCellRenderer3 extends DefaultTreeCellRenderer{
         TreeFrames panel;
    DefaultMutableTreeNode currentNode;
      public AnilTreeCellRenderer3() {
         super();
    public Component getTreeCellRendererComponent
       (JTree tree, Object value, boolean selected, boolean expanded,
       boolean leaf, int row, boolean hasFocus){
         TextAreaNode3 currentNode = (TextAreaNode3)value;
         NodeGUI4 gNode = (NodeGUI4) currentNode.gNode;
        return gNode.hBox;
    class AnilTreeCellEditor4 extends DefaultTreeCellEditor{
      DefaultTreeCellRenderer rend;
      public AnilTreeCellEditor4(JTree tree, DefaultTreeCellRenderer r){
        super(tree, r);
        rend = r;
      public Component getTreeCellEditorComponent(JTree tree, Object value,
       boolean isSelected, boolean expanded, boolean leaf, int row){
        return rend.getTreeCellRendererComponent(tree, value, isSelected, expanded,
         leaf, row, true);
      public boolean isCellEditable(EventObject event){
        return true;
    * this is done to keep gui separate from model - as in MVC.
    * not necessary.
    * @author juwo
    class NodeGUI4 {
         JPanel notes = new JPanel();
         final TreeFrames view;
         Box hBox = Box.createHorizontalBox();
         final JTextArea textArea = new JTextArea( 1, 5 );
         NodeGUI4( TreeFrames view_ ) {
              this.view = view_;
              hBox.add( textArea );
              textArea.setBorder( BorderFactory.createMatteBorder( 0, 0, 1, 0, Color.GREEN )
              hBox.add(notes);
              hBox.setBorder( BorderFactory.createMatteBorder( 5, 5, 5, 5, Color.CYAN ) );
         void addFrame() {
            MyInternalFrame frame = new MyInternalFrame();
            frame.add(new JTextArea(1,5));
            frame.setVisible(true); //necessary as of 1.3
            notes.add(frame);
            try {
                frame.setSelected(true);
            } catch (java.beans.PropertyVetoException e) {}
    class TextAreaNode3 extends DefaultMutableTreeNode {
         NodeGUI4 gNode;
         TextAreaNode3(TreeFrames view_t) {
              gNode = new NodeGUI4(view_t);
    class MyInternalFrame extends JInternalFrame {
        static int openFrameCount = 0;
        static final int xOffset = 0, yOffset = 0;
        public MyInternalFrame() {
            super("Document #" + (++openFrameCount),
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  true);//iconifiable
            //...Create the GUI and put it in the window...
            //...Then set the window size or call pack...
            setSize(300,300);
            //Set the window's location.
            setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
            this.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE);
    }

    I think this does what you want; it's basically the same technique as we used before.
    It also suffers from an interesting bug: if I type in the text area inside the internal frame, the editor resizes nicely
    with the node below it staying visible; if I type in the text area next to the panel, the editor will resize over the node
    below it. I didn't dig into it further to see the cause.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.util.EventObject;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.plaf.basic.BasicTreeUI;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    public class TreeFrames extends JPanel {
         AnilTreeCellRenderer3 atcr;
         AnilTreeCellEditor4 atce;
         DefaultTreeModel treeModel;
         JTree tree;
         public TreeFrames() {
              super( new BorderLayout() );
              treeModel = new DefaultTreeModel( null );
              tree = new JTree( treeModel );
              tree.setUI( new TextAreaTreeUI() );
              tree.setEditable( true );
              tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION );
              tree.setShowsRootHandles( true );
              tree.setCellRenderer( atcr = new AnilTreeCellRenderer3() );
              tree.setCellEditor( atce = new AnilTreeCellEditor4( tree, atcr ) );
              JScrollPane scrollPane = new JScrollPane( tree );
              add( scrollPane, BorderLayout.CENTER );
         public void setRootNode( DefaultMutableTreeNode node ) {
              treeModel.setRoot( node );
              treeModel.reload();
         public static void main( String[] args ) throws ClassNotFoundException, InstantiationException,
                   IllegalAccessException, UnsupportedLookAndFeelException {
              TreeFrames tb = new TreeFrames();
              tb.setPreferredSize( new Dimension( 800, 600 ) );
              JFrame frame = new JFrame( "Tree Windows UI Failed" );
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.setContentPane( tb );
              frame.setSize( 800, 600 );
              frame.pack();
              frame.setVisible( true );
              tb.populate();
         private void populate() {
              TextAreaNode3 r = new TextAreaNode3( this );
              setRootNode( r );
              r.gNode.addFrame();
              r.gNode.addFrame();
              TextAreaNode3 a = new TextAreaNode3( this );
              a.gNode.addFrame();
              treeModel.insertNodeInto( a, r, r.getChildCount() );
              treeModel.reload();
         private static class AnilTreeCellRenderer3 extends DefaultTreeCellRenderer {
              TreeFrames panel;
              DefaultMutableTreeNode currentNode;
              public AnilTreeCellRenderer3() {
                   super();
              public Component getTreeCellRendererComponent( JTree tree, Object value, boolean selected, boolean expanded,
                        boolean leaf, int row, boolean hasFocus ) {
                   TextAreaNode3 currentNode = (TextAreaNode3) value;
                   NodeGUI4 gNode = (NodeGUI4) currentNode.gNode;
                   return gNode.hBox;
         private static class AnilTreeCellEditor4 extends DefaultTreeCellEditor {
              DefaultTreeCellRenderer rend;
              public AnilTreeCellEditor4( JTree tree, DefaultTreeCellRenderer r ) {
                   super( tree, r );
                   rend = r;
              public Component getTreeCellEditorComponent( JTree tree, Object value, boolean isSelected, boolean expanded,
                        boolean leaf, int row ) {
                   return rend.getTreeCellRendererComponent( tree, value, isSelected, expanded, leaf, row, true );
              public boolean isCellEditable( EventObject event ) {
                   return true;
          * this is done to keep gui separate from model - as in MVC. not necessary.
          * @author juwo
         private static class NodeGUI4 {
              JPanel notes = new JPanel();
              final TreeFrames view;
              Box hBox = Box.createHorizontalBox();
              final JTextArea textArea = new JTextArea( 1, 5 );
              NodeGUI4( TreeFrames view_ ) {
                   this.view = view_;
                   hBox.add( textArea );
                   textArea.setBorder( BorderFactory.createMatteBorder( 0, 0, 1, 0, Color.GREEN ) );
                   hBox.add( notes );
                   hBox.setBorder( BorderFactory.createMatteBorder( 5, 5, 5, 5, Color.CYAN ) );
                   DocumentListener dl = new DocumentListener() {
                        public void insertUpdate( DocumentEvent de ) {
                             resizeEditor();
                        public void removeUpdate( DocumentEvent de ) {
                             resizeEditor();
                        public void changedUpdate( DocumentEvent de ) {
                   textArea.getDocument().addDocumentListener( dl );
              void addFrame() {
                   MyInternalFrame frame = new MyInternalFrame();
                   frame.getContentPane().add( new JTextArea( 1, 5 ) );
                   frame.setVisible( true ); // necessary as of 1.3
                   notes.add( frame );
                   try {
                        frame.setSelected( true );
                   } catch ( java.beans.PropertyVetoException e ) {
                   frame.addComponentListener( new ComponentAdapter() {
                        public void componentResized( ComponentEvent e ) {
                             resizeEditor();
              private void resizeEditor() {
                   TreePath path = view.tree.getEditingPath();
                   if ( path != null ) {
                        Rectangle nodeBounds = ( (BasicTreeUI) view.tree.getUI() ).getPathBounds( view.tree, path );
                        Dimension editorSize = getEditorPreferredSize();
                        hBox.setBounds( nodeBounds.x, nodeBounds.y,
                                  editorSize.width, editorSize.height );
                        hBox.validate();
                        Rectangle visRect = view.tree.getVisibleRect();
                        view.tree.paintImmediately( nodeBounds.x, nodeBounds.y,
                                  visRect.width + visRect.x - nodeBounds.x,
                                  editorSize.height );
                        ( (TextAreaTreeUI) view.tree.getUI() ).resizeTree( path );
              private Dimension getEditorPreferredSize() {
                   Insets insets = hBox.getInsets();
                   Dimension boxSize = hBox.getPreferredSize();
                   Dimension taSize = textArea.getPreferredSize();
                   Dimension nSize = notes.getPreferredSize();
                   int height = taSize.height + nSize.height + insets.top
                             + insets.bottom;
                   int width = taSize.width + nSize.width;
                   if ( width < boxSize.width )
                        width += insets.right + insets.left + 3; // 3 for cursor
                   return new Dimension( width, height );
         private static class TextAreaNode3 extends DefaultMutableTreeNode {
              NodeGUI4 gNode;
              TextAreaNode3( TreeFrames view_t ) {
                   gNode = new NodeGUI4( view_t );
         private static class MyInternalFrame extends JInternalFrame {
              static int openFrameCount = 0;
              static final int xOffset = 0, yOffset = 0;
              public MyInternalFrame() {
                   super( "Document #" + ( ++openFrameCount ), true, // resizable
                             true, // closable
                             true, // maximizable
                             true );// iconifiable
                   // ...Create the GUI and put it in the window...
                   // ...Then set the window size or call pack...
                   setSize( 300, 300 );
                   // Set the window's location.
                   setLocation( xOffset * openFrameCount, yOffset * openFrameCount );
                   this.putClientProperty( "JInternalFrame.isPalette", Boolean.TRUE );
         private class TextAreaTreeUI extends BasicTreeUI {
              public void resizeTree( TreePath path ) {
                  treeState.invalidatePathBounds(path);
                  updateSize();
    }

  • How to resize JPanel at Runtime ??

    Hi,
    Our Project me t a problem as below, we hope to resize JPanel at Runtime , not at design time, ie, when we first click the button called "Move JPanel" , then we click the JPanel, then we can drag it around within main panel, but we hope to resize the size of this JPanel when we point to the border of this JPanel then drag its border to zoom in or zoom out this JPanel.
    Please advice how to do that??
    Thanks in advance.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.border.LineBorder;
    import javax.swing.event.*;
    public class ResizeJPanels extends JPanel
        protected JLabel label1, label2, label3, label4, labeltmp;
        protected JLabel[] labels;
        protected JPanel[] panels;
        protected JPanel selectedJPanel;
        protected JButton btn  = new JButton("Move JPanel");
        int cx, cy;
        protected Vector order = new Vector();      
         public static void main(String[] args)
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new ResizeJPanels().GroupJLabels());
            f.setSize(600,700);
            f.setLocation(200,200);
            f.setVisible(true);
         private MouseListener ml = new MouseAdapter() {  
              public void mousePressed(MouseEvent e) {   
                   Point p = e.getPoint();      
                   JPanel jp = new JPanel();
                   jp.setLayout(null);
                   Component[] c = ((JPanel)e.getSource()).getComponents();
                   System.out.println("c.length = " + c.length);      
                   for(int j = 0; j < c.length; j++) {        
                        if(c[j].getBounds().contains(p)) {     
                             if(selectedJPanel != null && selectedJPanel != (JPanel)c[j])
                                  selectedJPanel.setBorder(BorderFactory.createEtchedBorder());
                             selectedJPanel = (JPanel)c[j];            
                             selectedJPanel.setBorder(BorderFactory.createLineBorder(Color.green));
                             break;             
                        add(jp);
                        revalidate();
    public JPanel GroupJLabels ()
              setLayout(null);
            addLabels();
            label1.setBounds( 125,  150, 125, 25);
            label2.setBounds(425,  150, 125, 25);
            label3.setBounds( 125, 575, 125, 25);
            label4.setBounds(425, 575, 125, 25);
            //add(btn);
            btn.setBounds(10, 5, 205, 25);
                add(btn);
           determineCenterOfComponents();
            ComponentMover mover = new ComponentMover();
             ActionListener lst = new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                     ComponentMover mover = new ComponentMover();
                           addMouseListener(mover);
                           addMouseMotionListener(mover);
              btn.addActionListener(lst);
              addMouseListener(ml); 
              return this;
        public void paintComponent(final Graphics g)
             super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
             Point[] p;
            g2.setStroke(new BasicStroke(4f));
           for(int i = 0 ; i < order.size()-1; i++) {
                JPanel l1 = (JPanel)order.elementAt(i);
                JPanel l2 = (JPanel)order.elementAt(i+1);
                p = getCenterPoints(l1, l2);
                g2.setColor(Color.black);
               // g2.draw(new Line2D.Double(p[0], p[1]));            
        private Point[] getCenterPoints(Component c1, Component c2)
            Point
                p1 = new Point(),
                p2 = new Point();
            Rectangle
                r1 = c1.getBounds(),
                r2 = c2.getBounds();
                 p1.x = r1.x + r1.width/2;
                 p1.y = r1.y + r1.height/2;
                 p2.x = r2.x + r2.width/2;
                 p2.y = r2.y + r2.height/2;
            return new Point[] {p1, p2};
        private void determineCenterOfComponents()
            int
                xMin = Integer.MAX_VALUE,
                yMin = Integer.MAX_VALUE,
                xMax = 0,
                yMax = 0;
            for(int i = 0; i < labels.length; i++)
                Rectangle r = labels.getBounds();
    if(r.x < xMin)
    xMin = r.x;
    if(r.y < yMin)
    yMin = r.y;
    if(r.x + r.width > xMax)
    xMax = r.x + r.width;
    if(r.y + r.height > yMax)
    yMax = r.y + r.height;
    cx = xMin + (xMax - xMin)/2;
    cy = yMin + (yMax - yMin)/2;
    private class ComponentMover extends MouseInputAdapter
    Point offsetP = new Point();
    boolean dragging;
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    for(int i = 0; i < panels.length; i++)
    Rectangle r = panels[i].getBounds();
    if(r.contains(p))
    selectedJPanel = panels[i];
    order.addElement(panels[i]);
    offsetP.x = p.x - r.x;
    offsetP.y = p.y - r.y;
    dragging = true;
    repaint(); //added
    break;
    public void mouseReleased(MouseEvent e)
    dragging = false;
    public void mouseDragged(MouseEvent e)
    if(dragging)
    Rectangle r = selectedJPanel.getBounds();
    r.x = e.getX() - offsetP.x;
    r.y = e.getY() - offsetP.y;
    selectedJPanel.setBounds(r.x, r.y, r.width, r.height);
    //determineCenterOfComponents();
    repaint();
    private void addLabels()
    label1 = new JLabel("Label 1");
    label2 = new JLabel("Label 2");
    label3 = new JLabel("Label 3");
    label4 = new JLabel("Label 4");
    labels = new JLabel[] {
    label1, label2, label3, label4
    JLabel jl = new JLabel("This is resizeable JPanel at Runtime");
    jl.setBackground(Color.green);
    jl.setOpaque(true);
              jl.setFont(new Font("Helvetica", Font.BOLD, 18));
    JPanel jp = new JPanel();
    jp.setLayout(new BorderLayout());
    panels = new JPanel[]{jp};
              jp.setBorder(new LineBorder(Color.black, 3, false));
    jp.setPreferredSize(new Dimension(400,200));
    jp.add(jl, BorderLayout.NORTH);
    for(int i = 0; i < labels.length; i++)
    labels[i].setHorizontalAlignment(SwingConstants.CENTER);
    labels[i].setBorder(BorderFactory.createEtchedBorder());
    jp.add(labels[i], BorderLayout.CENTER);
    jp.setBounds(100, 100, 400,200);
    add(jp);

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.MouseInputAdapter;
    public class Resizing extends JPanel {
        public Resizing() {
            super(null);
            addPanel();
            PanelControlAdapter control = new PanelControlAdapter(this);
            addMouseListener(control);
            addMouseMotionListener(control);
        private void addPanel() {
            JLabel jl = new JLabel("This is resizeable JPanel at Runtime");
            jl.setBackground(Color.green);
            jl.setOpaque(true);
            jl.setFont(new Font("Helvetica", Font.BOLD, 18));
            JPanel jp = new JPanel();
            jp.setLayout(new BorderLayout());
            jp.setBorder(new LineBorder(Color.black, 3, false));
            jp.add(jl, BorderLayout.NORTH);
            jp.setBounds(50,50,400,200);
            add(jp);
        public static void main(String[] args) {
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new Resizing());
            f.setSize(500,400);
            f.setLocation(100,100);
            f.setVisible(true);
    class PanelControlAdapter extends MouseInputAdapter {
        Resizing host;
        Component selectedComponent;
        LineBorder black;
        LineBorder green;
        Point offset = new Point();
        Point start = new Point();
        boolean dragging = false;
        boolean resizing = false;
        public PanelControlAdapter(Resizing r) {
            host = r;
            black = new LineBorder(Color.black, 3, false);
            green = new LineBorder(Color.green, 3, false);
        public void mouseMoved(MouseEvent e) {
            Point p = e.getPoint();
            boolean hovering = false;
            Component c = host.getComponent(0);
            Rectangle r = c.getBounds();
            if(r.contains(p)) {
                hovering = true;
                if(selectedComponent != c) {
                    if(selectedComponent != null)  // reset
                        ((JComponent)selectedComponent).setBorder(black);
                    selectedComponent = c;
                    ((JComponent)selectedComponent).setBorder(green);
                if(overBorder(p))
                    setCursor(p);
                else if(selectedComponent.getCursor() != Cursor.getDefaultCursor())
                    selectedComponent.setCursor(Cursor.getDefaultCursor());
            if(!hovering && selectedComponent != null) {
                ((JComponent)selectedComponent).setBorder(black);
                selectedComponent = null;
        private boolean overBorder(Point p) {
            Rectangle r = selectedComponent.getBounds();
            JComponent target = (JComponent)selectedComponent;
            Insets insets = target.getBorder().getBorderInsets(target);
            // Assume uniform border insets.
            r.grow(-insets.left, -insets.top);
            return !r.contains(p);
        private void setCursor(Point p) {
            JComponent target = (JComponent)selectedComponent;
            AbstractBorder border = (AbstractBorder)target.getBorder();
            Rectangle r = target.getBounds();
            Rectangle ir = border.getInteriorRectangle(target, r.x, r.y, r.width, r.height);
            int outcode = ir.outcode(p.x, p.y);
            Cursor cursor;
            switch(outcode) {
                case Rectangle.OUT_TOP:
                    cursor = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_TOP + Rectangle.OUT_LEFT:
                    cursor = Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_LEFT:
                    cursor = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_LEFT + Rectangle.OUT_BOTTOM:
                    cursor = Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_BOTTOM:
                    cursor = Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_BOTTOM + Rectangle.OUT_RIGHT:
                    cursor = Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_RIGHT:
                    cursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
                    break;
                case Rectangle.OUT_RIGHT + Rectangle.OUT_TOP:
                    cursor = Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR);
                    break;
                default:
                    cursor = Cursor.getDefaultCursor();
            selectedComponent.setCursor(cursor);
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            if(selectedComponent != null) {
                Rectangle r = selectedComponent.getBounds();
                if(selectedComponent.getCursor() == Cursor.getDefaultCursor()) {
                    offset.x = p.x - r.x;
                    offset.y = p.y - r.y;
                    dragging = true;
                } else {
                    start = p;
                    resizing = true;
        public void mouseReleased(MouseEvent e) {
            dragging = false;
            resizing = false;
        public void mouseDragged(MouseEvent e) {
            Point p = e.getPoint();
            if(dragging || resizing) {
                Rectangle r = selectedComponent.getBounds();
                if(dragging) {
                    r.x = p.x - offset.x;
                    r.y = p.y - offset.y;
                    selectedComponent.setLocation(r.x, r.y);
                } else if(resizing) {
                    int type = selectedComponent.getCursor().getType();
                    switch(type) {
                        case Cursor.N_RESIZE_CURSOR:
                            r.height -= p.y - start.y;
                            r.y = p.y;
                            break;
                        case Cursor.NW_RESIZE_CURSOR:
                            r.width -= p.x - start.x;
                            r.x = p.x;
                            r.height -= p.y - start.y;
                            r.y = p.y;
                            break;
                        case Cursor.W_RESIZE_CURSOR:
                            r.width -= p.x - start.x;
                            r.x = p.x;
                            break;
                        case Cursor.SW_RESIZE_CURSOR:
                            r.width -= p.x - start.x;
                            r.x = p.x;
                            r.height += p.y - start.y;
                            break;
                        case Cursor.S_RESIZE_CURSOR:
                            r.height += p.y - start.y;
                            break;
                        case Cursor.SE_RESIZE_CURSOR:
                            r.width += p.x - start.x;
                            r.height += p.y - start.y;
                            break;
                        case Cursor.E_RESIZE_CURSOR:
                            r.width += p.x - start.x;
                            break;
                        case Cursor.NE_RESIZE_CURSOR:
                            r.width += p.x - start.x;
                            r.height -= p.y - start.y;
                            r.y = p.y;
                            break;
                        default:
                            System.out.println("Unexpected resize type: " + type);
                    selectedComponent.setBounds(r.x, r.y, r.width, r.height);
                    start = p;
    }

Maybe you are looking for

  • An error occurred when attempting to change modules (Slideshow)

    Not sure what happened as I havent had any trouble before but I created a new catalog with 300 images for a show that is due this sunday and I am getting an error that will not let me switch to the slideshow mode. Any help is appreciated as I am up a

  • A day in the life of a collge intern

    I'm working alone on a project for a company that required that I learn java. Java in and of itself isn't that difficult to pick up. However, one problem that i've run into is that I'm trying to run video through a program that requires me to program

  • Java Help Exception in Linux

    Hi all, I have a piece of code that initializes Java help on windows perfectly but the same code causes an exception in Linux. below is the exception I am getting in Linux. because of this, the applications help is not appearing in Linux. Does anybod

  • Leopard prompts for 802.1X username and password instead of WEP password

    hey! so i got leopard on friday and i haven't been able to connect to my wireless properly since. i have an old D-Link DI-624 (Revision B) router that i have protected with a WEP password. in tiger i never had any problems with this, but now instead

  • Complex formating in a form letter

    I need to build a report that will: 1. choose one of several letters based upon the data in a table (for example, one person gets a thank you for your interest in product A and the next gets a thank you for your interest in product B). 2. handle comp