Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

SpringLayout - resizing constraints on multiple frames

843805Nov 18 2006 — edited Nov 20 2006
Hello. I am trying to understand how SpringLayout works. I am trying to paint three JPanels in a JFrame, in such a way that they will all be resized when the JFrame is resized. The following program draws the JPanels in the size and orientation I want, but I can't figure out how to add the right constraints so the EAST side of each JPanel is constrained to the EAST side of the content pane; or how to constrain the width of the JPanels to match the content pane's width. Any help will be greatly appreciated.
package test;

import java.awt.*;
import javax.swing.*;
import static javax.swing.SpringLayout.*;

public class Test {
  public static void main(String[] argv){
    JFrame frame = new JFrame();
    Container contentPane = frame.getContentPane();
    
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    JPanel panel3 = new JPanel();
    
    panel1.setBackground(Color.red);
    panel2.setBackground(Color.white);
    panel3.setBackground(Color.blue);
    
    panel1.setPreferredSize(new Dimension(100,100));
    panel2.setPreferredSize(new Dimension(100,100));
    panel3.setPreferredSize(new Dimension(100,100));
    contentPane.setPreferredSize(new Dimension(100,300));
    
    contentPane.add(panel1);
    contentPane.add(panel2);
    contentPane.add(panel3);
    
    SpringLayout layout = new SpringLayout();
    contentPane.setLayout(layout);
    
    layout.putConstraint(NORTH, panel1, 0, NORTH, contentPane);
    layout.putConstraint(NORTH, panel2, 0, SOUTH, panel1);
    layout.putConstraint(NORTH, panel3, 0, SOUTH, panel2);
    
    layout.putConstraint(WEST, panel1, 0, WEST, contentPane);
    layout.putConstraint(WEST, panel2, 0, WEST, contentPane);
    layout.putConstraint(WEST, panel3, 0, WEST, contentPane);
    
    frame.pack();
    frame.setVisible(true);
  }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 18 2006
Added on Nov 18 2006
7 comments
242 views