Java作為一種高級編程語言,被廣泛應用于各種領域。在實際開發中,常常需要用戶進行登錄操作,這就需要使用Java編寫一個用戶名和密碼登錄界面。
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Login extends JFrame implements ActionListener { //用戶名和密碼的文本框 private JTextField usernameTextField; private JPasswordField passwordTextField; //登錄和重置按鈕 private JButton loginButton; private JButton resetButton; public Login() { this.setTitle("登錄界面"); this.setSize(300, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //使用網格布局 this.setLayout(new GridLayout(3, 2, 10, 10)); JLabel usernameLabel = new JLabel("用戶名:"); JLabel passwordLabel = new JLabel("密 碼:"); usernameTextField = new JTextField(10); passwordTextField = new JPasswordField(10); loginButton = new JButton("登錄"); resetButton = new JButton("重置"); //添加組件 this.add(usernameLabel); this.add(usernameTextField); this.add(passwordLabel); this.add(passwordTextField); this.add(loginButton); this.add(resetButton); //添加事件監聽器 loginButton.addActionListener(this); resetButton.addActionListener(this); this.setVisible(true); } //事件處理方法 public void actionPerformed(ActionEvent e) { if (e.getSource() == loginButton) { String username = usernameTextField.getText(); String password = new String(passwordTextField.getPassword()); //在這里編寫登錄處理代碼 } else if (e.getSource() == resetButton) { usernameTextField.setText(""); passwordTextField.setText(""); } } public static void main(String[] args) { new Login(); } }
以上是一個簡單的Java登錄界面的實現方法,使用了JFrame和swing組件。在登錄處理代碼中可以根據實際需要進行數據庫驗證等操作,保證系統的安全性。
上一篇css中表格合并邊框