Swing SpringLayout範例

2019-10-16 22:04:06

SpringLayout類根據一組約束定位其關聯容器的子節點。

範例

package com.yiibai.swingdemo;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;

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

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing SpringLayout範例");
      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("輸入名稱: ");
      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);    
   }
}

執行上面範例程式碼,得到以下結果: