演示使用模式对话框添加新用户到数据库的功能,创建一个名为DialogDemo 的类 JAVA使用
时间: 2024-02-03 22:15:22 浏览: 26
好的,以下是一个简单的示例代码,演示如何在模式对话框中添加新用户到数据库中:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class DialogDemo extends JFrame implements ActionListener {
private JTextField nameField;
private JPasswordField passwordField;
public DialogDemo() {
super("添加新用户");
// 创建界面元素
JLabel nameLabel = new JLabel("用户名:");
nameField = new JTextField(20);
JLabel passwordLabel = new JLabel("密码:");
passwordField = new JPasswordField(20);
// 创建按钮
JButton addButton = new JButton("添加");
addButton.addActionListener(this);
JButton cancelButton = new JButton("取消");
cancelButton.addActionListener(this);
// 创建面板并添加元素
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(nameLabel);
panel.add(nameField);
panel.add(passwordLabel);
panel.add(passwordField);
panel.add(addButton);
panel.add(cancelButton);
// 添加面板到窗口并设置大小
add(panel);
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("添加")) {
String name = nameField.getText();
String password = new String(passwordField.getPassword());
// 连接数据库
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
// 插入数据
String sql = "INSERT INTO users (name, password) VALUES (?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, name);
statement.setString(2, password);
statement.executeUpdate();
// 提示用户添加成功
JOptionPane.showMessageDialog(this, "添加用户成功!", "提示", JOptionPane.PLAIN_MESSAGE);
// 关闭连接
statement.close();
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "添加用户失败!", "错误", JOptionPane.ERROR_MESSAGE);
}
}
// 关闭窗口
dispose();
}
public static void main(String[] args) {
new DialogDemo();
}
}
```
以上代码演示了如何创建一个模式对话框,在对话框中添加用户名和密码,并将它们插入到 MySQL 数据库中的 users 表中。如果插入成功,则会提示用户添加成功,否则会提示用户添加失败。