javagui界面连接数据库输出表格内容
时间: 2023-06-16 12:03:36 浏览: 434
以下是一个简单的Java GUI程序,它连接到MySQL数据库并从表格中检索数据并将其显示在JTable中。
首先,确保你已经安装了MySQL数据库并且已经将JDBC驱动程序添加到Java类路径中。
接下来,我们需要创建一个GUI界面,它包含一个文本框和一个按钮:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyGUI extends JFrame implements ActionListener {
private JTextField textField;
private JButton button;
public MyGUI() {
super("My GUI");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textField = new JTextField(20);
add(textField);
button = new JButton("Load Data");
button.addActionListener(this);
add(button);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
loadData();
}
}
private void loadData() {
// TODO: Connect to database and load data into JTable
}
public static void main(String[] args) {
new MyGUI();
}
}
```
现在我们需要编写代码来连接到MySQL数据库并从表格中检索数据。在此示例中,我们将使用JDBC和MySQL数据库。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class MyGUI extends JFrame implements ActionListener {
private JTextField textField;
private JButton button;
private JTable table;
private JScrollPane scrollPane;
public MyGUI() {
super("My GUI");
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textField = new JTextField(20);
add(textField, BorderLayout.NORTH);
button = new JButton("Load Data");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
loadData();
}
}
private void loadData() {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Replace "mydatabase" with your database name
String user = "root"; // Replace "root" with your MySQL username
String password = "password"; // Replace "password" with your MySQL password
try {
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable"); // Replace "mytable" with your table name
// Get column names
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
String[] columnNames = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
columnNames[i - 1] = metaData.getColumnName(i);
}
// Get row data
Object[][] rowData = new Object[100][columnCount];
int rowCount = 0;
while (resultSet.next()) {
for (int i = 1; i <= columnCount; i++) {
rowData[rowCount][i - 1] = resultSet.getObject(i);
}
rowCount++;
}
// Create JTable
table = new JTable(rowData, columnNames);
scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);
pack();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
new MyGUI();
}
}
```
现在运行程序并单击“Load Data”按钮,你将看到从MySQL数据库中检索的表格数据在JTable中显示。
阅读全文