Swing的SpringLayout示例

说明

SpringLayout类根据一组约束定位其关联容器的子项。

代码示例

package com.yiidian;

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

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("一点教程网:Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      SpringLayout layout = new SpringLayout();

      panel.setLayout(layout);
      JLabel label = new JLabel("Enter Name: ");
      JTextField textField = new JTextField("", 15);
      panel.add(label);
      panel.add(textField);

      layout.putConstraint(SpringLayout.WEST, label,5, SpringLayout.WEST, panel);
      layout.putConstraint(SpringLayout.NORTH, label,5, SpringLayout.NORTH, panel);
      layout.putConstraint(SpringLayout.WEST, textField,5, SpringLayout.EAST, label);
      layout.putConstraint(SpringLayout.NORTH, textField,5, SpringLayout.NORTH, panel);
      layout.putConstraint(SpringLayout.EAST, panel,5, SpringLayout.EAST, textField);
      layout.putConstraint(SpringLayout.SOUTH, panel,5, SpringLayout.SOUTH, textField); 
      frame.getContentPane().add(panel, BorderLayout.CENTER);
   }
}

执行效果如下:

热门文章

优秀文章