java映像介面開發簡單一實例
JTextField、JPasswordField、JButton及事件的簡單應用,做一個登入介面用來顯示輸入的使用者名稱和密碼的小例子,代碼如下:
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
/**
* JTextField、JPasswordField、JButton及事件的簡單應用執行個體
* @author 左傑
*
*/
public class Example6Frame extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextField username; // 使用者名稱輸入框
private JPasswordField password; // 密碼輸入框
private JButton logonButton; // 登入按鈕
private JButton cancelButton; // 退出按鈕
public Example6Frame() {
setTitle("登入示範");// 設定表單的標題
setSize(300, 120);// 設定表單的大小
setLayout(new GridLayout(3, 2, 2, 2)); // 設定布局管理器(4個參數,分表表示行數,列數,水平間距,垂直間距)
setResizable(false); // 不允許使用者改變視窗大小
//設定顯示在螢幕的中間
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
this.setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
username = new JTextField(16); // 初始化文本輸入框,寬度為16列
password = new JPasswordField(16); // 初始化密碼輸入框,寬度為16列
logonButton = new JButton("登入"); // 初始化登入按鈕
logonButton.addActionListener( // 登入按鈕事件處理
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
char[] pw = password.getPassword(); // 得到密碼
String message = "您的使用者名稱:" + username.getText()
+ " 您的密碼:" + new String(pw); // 訊息字串
JOptionPane.showMessageDialog(null, message); // 顯示訊息
}
});
cancelButton = new JButton("退出"); // 初始化退出按鈕
cancelButton.addActionListener( // 初始化按鈕事件處理
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.exit(0); // 退出程式
}
});
//在表單上添加相應組件
add(new JLabel("使用者名稱:"));
add(username);
add(new JLabel("密 碼:"));
add(password);
add(logonButton);
add(cancelButton);
}
public static void main(String[] args) {
JFrame frame = new Example6Frame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 關閉視窗時退出程式
frame.setVisible(true);//顯示表單
}
}