1.简单的登陆界面示例
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;public class Main extends JFrame {private JTextField usernameField;private JPasswordField passwordField;public Main() {setTitle("登陆界面");setSize(300, 150);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JPanel panel = new JPanel();JLabel usernameLabel = new JLabel("用户名:");JLabel passwordLabel = new JLabel("密码:");usernameField = new JTextField(15);passwordField = new JPasswordField(15);JButton loginButton = new JButton("登陆");loginButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {String username = usernameField.getText();String password = new String(passwordField.getPassword());if (username.equals("admin") && password.equals("admin123")) {JOptionPane.showMessageDialog(Main.this, "登陆成功");} else {JOptionPane.showMessageDialog(Main.this, "用户名或密码错误");}}});panel.add(usernameLabel);panel.add(usernameField);panel.add(passwordLabel);panel.add(passwordField);panel.add(loginButton);add(panel);setVisible(true);}public static void main(String[] args) {new Main();}
}
效果
2. 点击按钮切换文本示例
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;public class ToggleTextFrame extends JFrame {private JLabel textLabel;private JButton toggleButton;private boolean isTextVisible = true;public ToggleTextFrame() {setTitle("文本显示切换");setSize(300, 150);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JPanel panel = new JPanel();textLabel = new JLabel("Hello, Swing!");toggleButton = new JButton("切换文本");toggleButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {isTextVisible = !isTextVisible;if (isTextVisible) {textLabel.setText("Hello, Swing!");} else {textLabel.setText("");}}});panel.add(textLabel);panel.add(toggleButton);add(panel);setVisible(true);}public static void main(String[] args) {new ToggleTextFrame();}
}