Swing垂直分割的窗格範例

2019-10-16 22:04:09

SplitPane類用於在兩個面板之間進行可移動分割。

範例

package com.yiibai.swingdemo;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;

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

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing垂直分割的窗格範例");
      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 buttonPanel = new JPanel(new FlowLayout());
      buttonPanel.add(new JButton("確定"));
      buttonPanel.add(new JButton("取消"));    
      JPanel textBoxPanel = new JPanel(new FlowLayout());
      textBoxPanel.add(new JLabel("名稱:"));
      textBoxPanel.add(new JTextField(20));
      JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, buttonPanel, textBoxPanel);
      splitPane.setOneTouchExpandable(true);
      splitPane.setDividerLocation(50);
      frame.getContentPane().add(splitPane, BorderLayout.CENTER);      
   }
}

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