📄 spring.html
字号:
Our next example,<a class="SourceLink" target="_blank" href="examples/SpringDemo2.java"><code>SpringDemo2.java</code></a>,improves the situation a bit by specifyinglocations for each component.In this example, we'll specify that the componentsshould appear in a single row,with 5 pixels between them.The following code specifies the locationof the label:</p><blockquote><pre>//Adjust constraints for the label so it's at (5,5).layout.putConstraint(SpringLayout.WEST, label, 5, SpringLayout.WEST, contentPane);layout.putConstraint(SpringLayout.NORTH, label, 5, SpringLayout.NORTH, contentPane);</pre></blockquote>The first <code>putConstraint</code> callspecifies that the label's left (west) edgeshould be 5 pixels from its container's left edge.This translates to an <em>x</em> coordinate of 5.The second <code>putConstraint</code> callsets up a similar relationship between the top(north) edgesof the label and its container,resulting in a <em>y</em> coordinate of 5.<p>Here is the code that sets up the locationof the text field:<blockquote><pre>//Adjust constraints for the text field so it's at//(<em><label's right edge></em> + 5, 5).layout.putConstraint(SpringLayout.WEST, textField, 5, SpringLayout.EAST, label);layout.putConstraint(SpringLayout.NORTH, textField, 5, SpringLayout.NORTH, contentPane);</pre></blockquote><p>The first <code>putConstraint</code> callmakes the text field's left (west) edgebe 5 pixels away from the label's right (east) edge.The second <code>putConstraint</code> callis just like the second call in the first snippet,and has the same effect of setting thecomponent's <em>y</em> coordinate to 5.<p>The previous example still has the problem ofthe container coming up too small.But when we resize the window, the components arein the right place:</p><p><center><IMG SRC="../../figures/uiswing/layout/SpringDemo2-resized.png" WIDTH="235" HEIGHT="67" ALIGN="BOTTOM" ALT="SpringDemo2 -- at least now all the components are in the right position!"></center></p><p>To make the container initially appear at the right size,we need to set the springs that define the right(east) and bottom (south) edgesof the container itself.SpringDemo3 shows how to do this.You can<b><a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/layout/examples/SpringDemo3.jnlp">run SpringDemo3</a></b> using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a> and find its code in<a class="SourceLink" target="_blank" href="examples/SpringDemo3.java"><code>SpringDemo3.java</code></a>.Here is the code that sets the container's springs:</p><blockquote><pre>layout.putConstraint(SpringLayout.EAST, contentPane, 5, SpringLayout.EAST, textField);layout.putConstraint(SpringLayout.SOUTH, contentPane, 5, SpringLayout.SOUTH, textField);</pre></blockquote><p>The first <code>putConstraint</code> callmakes the container's right edge be 5 pixelsto the right of the text field's right edge.The second one makes its bottom edge be 5 pixels beyondthe bottom edge of the tallest component(which, for simplicity's sake,we've assumed is the text field).<p>Finally, the window comes up at the right size:</p><p><center><IMG SRC="../../figures/uiswing/layout/SpringDemo3.png" WIDTH="229" HEIGHT="64" ALIGN="BOTTOM" ALT="SpringDemo3 -- the parent now HAS a correct initial size!"></center></p><p>When we make the window larger we can see the spring layout in action,distributing the extra space between the available components.</p><p><center><IMG SRC="../../figures/uiswing/layout/SpringDemo3-resized.png" WIDTH="314" HEIGHT="117" ALIGN="BOTTOM" ALT="SpringDemo3 enlarged"></center></p><p>In this case the spring layout has chosen to give all the extra spaceto the text field.Although it seems like the spring layouttreats labels and text fields differently,spring layout has nospecial knowledge of any Swing or AWT components.It relies on the values of a componentsminimum, preferred, and maximum size properties.The next section discusses how spring layout uses these properties,and why they can cause uneven space distribution.</p></blockquote><h3>Springs and Component Size</h3><blockquote><p>A <code>SpringLayout</code> object automaticallyinstalls <code>Spring</code>s forthe height and width of each componentthat the <code>SpringLayout</code> controls.These springs are essentially covers forthe component抯<code>getMinimumSize</code>,<code>getPreferredSize</code>,and <code>getMaximumSize</code> methods.By "covers" we mean thatnot only are the springs <em>initialized</em>with the appropriate values from these methods,but also that the springs <em>track</em> those values.For example, the <code>Spring</code> objectthat represents the width of a componentis a special kind of springthat simply delegates its implementationto the relevant size methods of the component.That way the spring stays in sync with the size methodsas the characteristics of the component change.</p><p>When a component's <code>getMaximumSize</code> and<code>getPreferredSize</code> methodsreturn the same value,<code>SpringLayout</code> interprets this as meaning thatthe component should not be stretched.<code>JLabel</code> and <code>JButton</code>are examples of components implemented this way.For this reason,the label in the SpringDemo3 exampledoesn't stretch.</p><p>The <code>getMaximumSize</code> methodof some components, such as <code>JTextField</code>,returns the value <code>Integer.MAX_VALUE</code>for the width and height of its maximum size,indicating that the component can grow to any size.For this reason,when the SpringDemo3 window is enlarged,<code>SpringLayout</code> distributes all the extra spaceto the only springs that can grow —those determining the size of the text field.</p></blockquote><h3><a name="alternatives">More About the SpringLayout API</a></h3><blockquote>The SpringDemo examples used the <code>SpringLayout</code>method <code>putConstraint</code>to set the springs associated with each component.The <code>putConstraint</code> method isa convenience methodthat lets you modify a component's constraintswithout needing to use the full spring layout API.Here, again, is the code from <code>SpringDemo3</code>that sets the location of the label:<blockquote><pre>layout.putConstraint(SpringLayout.WEST, label, 5, SpringLayout.WEST, contentPane);layout.putConstraint(SpringLayout.NORTH, label, 5, SpringLayout.NORTH, contentPane);</pre></blockquote>Here is equivalent code that uses the<code>SpringLayout.Constraints</code>and <code>Spring</code> classes directly:<blockquote><pre>SpringLayout.Constraints labelCons = layout.getConstraints(label);labelCons.setX(Spring.constant(5));labelCons.setY(Spring.constant(5));</pre></blockquote>To see the entire democonverted to use this API, look at<a class="SourceLink" target="_blank" href="examples/SpringDemo4.java"><code>SpringDemo4.java</code></a>.That file also includes a more polished(and much longer)version of the code that sets the container's size.<p>As the preceding snippets imply,<code>SpringLayout</code>and<code>SpringLayout.Constraints</code>tend to use different conventionsfor describing springs.The <code>SpringLayout</code> API uses edges,which are specified by theseconstants:<ul><li> <code>SpringLayout.NORTH</code> (top edge)<li> <code>SpringLayout.SOUTH</code> (bottom edge)<li> <code>SpringLayout.EAST</code> (right edge)<li> <code>SpringLayout.WEST</code> (left edge)</ul>The <code>SpringLayout.Constraints</code> classknows about edges,but only has <code>Spring</code> objectsfor the following properties:<ul><li> <em>x</em><li> <em>y</em><li> <em>width</em><li> <em>height</em></ul>Each <code>Constraints</code> object maintainsthe following relationships between its springsand the edges they represent:<pre> west = xnorth = y east = x + widthsouth = y + height</pre><p>If you're confused, don't worry.The next section presents utility methodsyou can use to accomplish some common layout taskswithout knowing anything about the spring layout API.</blockquote><h3><a name="grid">Utility Methods for Grids</a></h3><blockquote><p>Because the <code>SpringLayout</code> classwas created for GUI builders,setting up individual springs for a layoutcan be cumbersome to code by hand.This section presents a couple of methodsyou can use to install all the springs neededto lay out a group of components in a grid.These methods emulate some of the features of the<code>GridLayout</code>,<code>GradBagLayout</code>, and<code>BoxLayout</code> classes.</p><p>The two methods, called<code>makeGrid</code> and<code>makeCompactGrid</code>,are defined in<a class="SourceLink" target="_blank" href="examples/SpringUtilities.java"><code>SpringUtilities.java</code></a>.Both methods workby grouping the components together into rows and columnsand using the <code>Spring.max</code> methodto make a width or height springthat makes a row or columnbig enough for all the components in it.In the<code>makeCompactGrid</code>method the same width or height springis used for all components in a particularcolumn or row, respectively.In the<code>makeGrid</code> method, by contrast,the width and height springs are sharedby every component in the container,forcing them all to be the same size.</p><p>Let's see these methods in action.Our first example,implemented in the source file<a class="SourceLink" target="_blank" href="examples/SpringGrid.java"><code>SpringGrid.java</code></a>, displays a bunch of numbers in text fields.The center text field is much wider than the others.Just as with <code>GridLayout</code>,having one large cellforces all the cells to be equally large.You can<b><a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/layout/examples/SpringGrid.jnlp">run SpringGrid</a></b> using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.</p><p><center><IMG SRC="../../figures/uiswing/layout/SpringGrid.png" WIDTH="400" HEIGHT="114" ALIGN="BOTTOM" ALT="SpringGrid"></center></p><p>Here is the code that creates and lays out the text fieldsin SpringGrid:</p><blockquote><pre>JPanel panel = new JPanel(new SpringLayout());for (int i = 0; i < 9; i++) { JTextField textField = new JTextField(Integer.toString(i)); ...<em>//when i==4, put long text in the text field</em>... panel.add(textField);}...SpringUtilities.makeGrid(panel, 3, 3, //rows, cols 5, 5, //initialX, initialY 5, 5);//xPad, yPad</pre></blockquote><p>Now let's look at an example,in the source file<a class="SourceLink" target="_blank" href="examples/SpringCompactGrid.java"><code>SpringCompactGrid.java</code></a>, that uses the <code>makeCompactGrid</code> method insteadof <code>makeGrid</code>.This example displays lots of numbersto show off spring layout's abilityto minimize the space required.You can<b><a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/layout/examples/SpringCompactGrid.jnlp">run SpringCompactGrid</a></b> using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.Here's what the SpringCompactGrid GUI looks like:</p><p><center><IMG SRC="../../figures/uiswing/layout/SpringCompactGrid.png" WIDTH="403" HEIGHT="267" ALIGN="BOTTOM" ALT="SpringCompactGrid"></center></p><p>Here is the code that creates and lays out the text fieldsin SpringCompactGrid:</p><blockquote><pre>JPanel panel = new JPanel(new SpringLayout());int rows = 10;int cols = 10;for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { int anInt = (int) Math.pow(r, c); JTextField textField = new JTextField(Integer.toString(anInt)); panel.add(textField); }}//Lay out the panel.SpringUtilities.makeCompactGrid(panel, //parent rows, cols, 3, 3, //initX, initY 3, 3); //xPad, yPad</pre></blockquote><p>One of the handiest uses forthe <code>makeCompactGrid</code> methodis associating labels with components,where the labels are in one columnand the components in another.The file<a class="SourceLink" target="_blank" href="examples/SpringForm.java"><code>SpringForm.java</code></a> uses <code>makeCompactGrid</code> in this way,as the following figure demonstrates .You can<b><a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/layout/examples/SpringForm.jnlp">run SpringForm</a></b> using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.</p><p><center><IMG SRC="../../figures/uiswing/layout/SpringForm.png" WIDTH="192" HEIGHT="144" ALIGN="BOTTOM" ALT="SpringForm"></center></p><p>Here is the code that creates and lays out thelabel-text field pairs in SpringForm:</p><blockquote><pre>String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};int numPairs = labels.length;//Create and populate the panel.JPanel p = new JPanel(new SpringLayout());for (int i = 0; i < numPairs; i++) { JLabel l = new JLabel(labels[i], JLabel.TRAILING); p.add(l); JTextField textField = new JTextField(10); l.setLabelFor(textField); p.add(textField);}//Lay out the panel.SpringUtilities.makeCompactGrid(p, numPairs, 2, //rows, cols 6, 6, //initX, initY 6, 6); //xPad, yPad</pre></blockquote><p>Because we are using a real layout managerinstead of absolute positioning,the layout manager responds dynamicallyto changes in components involved.For example, if the names of the labels are localized,
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -