下麵的示例展示了如何在基於Swing的應用程式中創建標準窗口。
使用以下API -
JFrame
- 創建標準框架或窗口。JFrame.getContentPane()
- 獲取框架的內容區域。JFrame.setSize()
- 設置框架的大小。JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
- 在Frame
關閉時設置動作。
示例
package com.zaixian.swingdemo;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
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(JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
panel.add(new JLabel("Welcome to xuhuhu.com!"));
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
執行上面示例代碼,得到以下結果:
上一篇:
Swing框架和窗口示例
下一篇:
Swing列表框示例