swing 连接数据库
原创
©著作权归作者所有:来自51CTO博客作者痛而不觉的原创作品,请联系作者获取转载授权,否则将追究法律责任
package com.test;
import org.mmc.util.swing.JswUtils;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* swing 连接数据库
* 更新时间: 2024年10月10日 14:07:52
*/
public class DatabaseQueryApp extends JFrame {
private JTextField dbUrlField;
private JTextField usernameField;
private JPasswordField passwordField;
private JTextArea logArea;
private JTable resultTable;
private DefaultTableModel tableModel;
private JList<String> itemList;
private DefaultListModel<String> listModel;
public DatabaseQueryApp() {
setTitle("Database Query Interface");
setSize(900, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JswUtils.setScreenMiddle(this);
// North Panel with FlowLayout
JPanel northPanel = new JPanel(new FlowLayout());
dbUrlField = new JTextField(20);
usernameField = new JTextField(10);
passwordField = new JPasswordField(10);
JButton connectButton = new JButton("连接");
JButton runButton = new JButton("运行");
northPanel.add(new JLabel("数据库地址:"));
northPanel.add(dbUrlField);
northPanel.add(new JLabel("账号:"));
northPanel.add(usernameField);
northPanel.add(new JLabel("密码:"));
northPanel.add(passwordField);
northPanel.add(connectButton);
northPanel.add(runButton);
// West Panel with List
JPanel westPanel = new JPanel();
listModel = new DefaultListModel<>();
for (int i = 0; i < 200; i++) {
// 添加示例数据到列表
listModel.addElement("数据项 " + i);
}
itemList = new JList<>(listModel);
itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane listScrollPane = new JScrollPane(itemList);
// 设置首选大小,调整宽度
listScrollPane.setPreferredSize(new Dimension(100, 200)); // 设置300px宽和200px高
westPanel.setLayout(new BorderLayout());
westPanel.add(listScrollPane, BorderLayout.CENTER);
// Context Menu for JList
JPopupMenu contextMenu = new JPopupMenu();
JMenuItem menuItem1 = new JMenuItem("菜单1");
JMenuItem menuItem2 = new JMenuItem("菜单2");
JMenuItem menuItem3 = new JMenuItem("菜单3");
contextMenu.add(menuItem1);
contextMenu.add(menuItem2);
contextMenu.add(menuItem3);
itemList.setComponentPopupMenu(contextMenu);
// Mouse Listener for the JList
itemList.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
contextMenu.show(itemList, e.getX(), e.getY());
}
}
});
// Center Panel with TextArea and JTable
JPanel centerPanel = new JPanel(new BorderLayout());
logArea = new JTextArea();
logArea.setLineWrap(true); // 设置换行
logArea.setWrapStyleWord(true); // 按词换行
logArea.setEditable(true);
JScrollPane textAreaScrollPane = new JScrollPane(logArea);
textAreaScrollPane.setPreferredSize(new Dimension(400, 200)); // 设置首选大小
centerPanel.add(textAreaScrollPane, BorderLayout.NORTH);
tableModel = new DefaultTableModel();
resultTable = new JTable(tableModel);
JScrollPane tableScrollPane = new JScrollPane(resultTable);
centerPanel.add(tableScrollPane, BorderLayout.CENTER);
// South Panel with FlowLayout
JPanel southPanel = new JPanel(new FlowLayout());
JButton logButton1 = new JButton("打印日志");
JButton logButton2 = new JButton("打印日志");
JButton logButton3 = new JButton("打印日志");
JButton logButton4 = new JButton("打印日志");
southPanel.add(logButton1);
southPanel.add(logButton2);
southPanel.add(logButton3);
southPanel.add(logButton4);
// Add panels to the frame
add(northPanel, BorderLayout.NORTH);
add(westPanel, BorderLayout.WEST);
add(centerPanel, BorderLayout.CENTER);
add(southPanel, BorderLayout.SOUTH);
// Action Listeners
connectButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
connectToDatabase();
}
});
runButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
runQuery();
}
});
menuItem1.addActionListener(e -> printSelectedItem());
menuItem2.addActionListener(e -> printSelectedItem());
menuItem3.addActionListener(e -> printSelectedItem());
// Display the application
setVisible(true);
}
private void connectToDatabase() {
String dbUrl = dbUrlField.getText();
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
logArea.append("尝试连接到数据库: " + dbUrl + "\n");
try {
Connection connection = DriverManager.getConnection(dbUrl, username, password);
logArea.append("连接成功!\n");
} catch (Exception e) {
logArea.append("连接失败: " + e.getMessage() + "\n");
}
}
private void runQuery() {
String sql = logArea.getText(); // Assuming SQL is inputted in the log area for simplicity
logArea.append("执行查询: " + sql + "\n");
try {
// Here you would execute the SQL query and populate the resultTable
// For demonstration, we're using a mockup
tableModel.setRowCount(0); // Clear previous results
tableModel.setColumnCount(2); // Set number of columns
tableModel.setColumnIdentifiers(new Object[]{"Column 1", "Column 2"}); // Sample header
// Mock data for demonstration
tableModel.addRow(new Object[]{"Sample Data 1", "Value 1"});
tableModel.addRow(new Object[]{"Sample Data 2", "Value 2"});
logArea.append("查询完成!\n");
} catch (Exception e) {
logArea.append("查询失败: " + e.getMessage() + "\n");
}
}
private void printSelectedItem() {
String selectedItem = itemList.getSelectedValue();
if (selectedItem != null) {
logArea.append("打印选中的项: " + selectedItem + "\n");
} else {
logArea.append("没有选中任何项!\n");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(DatabaseQueryApp::new);
}
}
/**
* 居中显示
*/
public static void setScreenMiddle(JFrame frame) {
int windowWidth = frame.getWidth(); //获得窗口宽
int windowHeight = frame.getHeight(); //获得窗口高
Toolkit kit = Toolkit.getDefaultToolkit(); //定义工具包
Dimension screenSize = kit.getScreenSize(); //获取屏幕的尺寸
int screenWidth = screenSize.width; //获取屏幕的宽
int screenHeight = screenSize.height; //获取屏幕的高
frame.setLocation((screenWidth - windowWidth) / 2, (screenHeight - windowHeight) / 2);//设置窗口居中显示
}