java - 如何在 JTable 中显示从数据库中检索到的数据?
问题描述
JTable
任何人都可以帮助从数据库中检索数据并通过使用将它们放入JButton
吗?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
public class try1 extends JFrame implements ActionListener {
JLabel Lsearch;
static JTable table;
String column[]={"ID","NAME"};
JTextField Tsearch;
//String driverName;
JButton Bsearch;
//String url;
DefaultTableModel model = new DefaultTableModel();
//String userName;String password;
String id= "";
String name= "";
String textvalue;
String sql;
public try1() {
Lsearch = new JLabel(" ID:");
Tsearch = new JTextField(15);
Bsearch = new JButton("SEARCH");
//String driverName = "com.mysql.jdbc.Driver";
//String url = "jdbc:mysql://localhost:3306/example";
//String userName = "root";String password = "root";
String id= "";
String name= "";
model.setColumnIdentifiers(column);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
textvalue = Tsearch.getText();
add(scroll);add(Lsearch);add(Tsearch);add(Bsearch);
Lsearch.setBounds(0, 0, 100,30);
Tsearch.setBounds(30,3,100,20);
Bsearch.setBounds(150,3,100,20);
Bsearch.addActionListener(this);
scroll.setBounds(0 , 100, 350, 50);
getContentPane().setLayout(null);
setSize(500,300);
setVisible(true);
}
public static void main(String[] args) {
new try1();
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == Bsearch) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/example", "root", "");
sql = "select * from edata where ID = " + textvalue;
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
id = rs.getString("ID");
name = rs.getString("NAME");
model.addRow(new Object[]{id, name});
}
JOptionPane.showMessageDialog(null, "Data Successfully Update", "Confirmation", JOptionPane.INFORMATION_MESSAGE);
} catch(Exception ei) {
System.out.println("");
}
}
}
}
截屏:
解决方案
推荐阅读
- android - 为多个应用程序创建深层链接
- espeak - espeak 跳过句子的第一个音素
- java - Maven 依赖问题 - 缺少工件
- r - 边际效应图与 R 中的发生率比率不对应
- c# - 将存储库注入 SiteResourceGraphType 时,“没有为 SiteResourceGraphType 类型定义无参数构造函数”消息
- javascript - 使用 while 循环生成多个按钮
- leaflet - 获取在 DRAWVERTEX 事件传单中绘制的顶点的经纬度
- python - 如何使用 Selenium 和 Python 选择具有 unselectable="on" 属性的剑道下拉元素
- tensorflow - 如何在tensorflow的while循环中迭代和更改变量的值
- asp.net-mvc-5 - Visual Studio 2017 无法启动调试适配器“chrome”