换种写法:import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class test2 extends JFrame implements ActionListener { private JLabel titleLabel, usernameLabel, passwordLabel, infoLabel; private JTextField usernameField; private JPasswordField passwordField; private JButton loginButton, cancelButton; public test2(String title) { super(title); Container contentPane = this.getContentPane(); contentPane.setLayout(new BorderLayout()); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(4, 2, 10, 10)); titleLabel = new JLabel("用户登录"); titleLabel.setFont(new Font("仿宋", Font.BOLD, 20)); titleLabel.setHorizontalAlignment(JLabel.CENTER); usernameLabel = new JLabel("用户名:"); passwordLabel = new JLabel("密码:"); usernameField = new JTextField(10); passwordField = new JPasswordField(10); loginButton = new JButton("登录"); cancelButton = new JButton("取消"); loginButton.addActionListener(this); cancelButton.addActionListener(this); infoLabel = new JLabel(); panel.add(usernameLabel); panel.add(usernameField); panel.add(passwordLabel); panel.add(passwordField); panel.add(loginButton); panel.add(cancelButton); panel.add(new JLabel()); panel.add(infoLabel); contentPane.add(titleLabel, BorderLayout.NORTH); contentPane.add(panel, BorderLayout.CENTER); this.setSize(300, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == loginButton) { String username = usernameField.getText().trim(); String password = new String(passwordField.getPassword()).trim(); if (username.isEmpty() || password.isEmpty()) { infoLabel.setText("请输入用户名和密码"); } else { infoLabel.setText("用户名: " + username + " 密码: " + password); } } else if (e.getSource() == cancelButton) { usernameField.setText(""); passwordField.setText(""); infoLabel.setText("用户登录"); } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { new test2("登录界面"); }); } }
时间: 2024-03-08 11:45:16 浏览: 184
Java--incident-response.zip_site:www.pudn.com
这段代码是一个简单的Java GUI程序,实现了一个用户登录界面。程序继承了JFrame类,并实现了ActionListener接口,用于监听登录按钮和取消按钮的事件。程序使用了Swing组件库,包括JLabel、JTextField、JPasswordField、JButton等组件,用于显示和输入用户名和密码。当用户点击登录按钮时,程序会获取输入框中的用户名和密码,并判断是否为空,如果为空则提示用户输入,否则显示输入的用户名和密码。当用户点击取消按钮时,程序会清空输入框,并将提示信息恢复为默认值。程序的入口方法为main方法,通过SwingUtilities类的invokeLater方法在事件分发线程中启动程序。
阅读全文