[java]代码库
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jtabel;
import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
public class TableModel extends JFrame {
public DefaultTableModel tableModel;
public JTable table;
JScrollPane tablePane;
Connection ct;
PreparedStatement ps;
ResultSet rs;
public ListSelectionListener selectAndDisplay;
public JTextField show;
int s;
public TableModel(){
selectAndDisplay = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int row = table.getSelectedRow();
// System.out.println("转化前 :"+row);
if(row!=-1){
s = table.convertColumnIndexToModel(row);
System.out.println("转化后:"+s);
show.setText((String) table.getValueAt(s,0));
}
}
};
String[] columnStrings ={
"goods_Id",
"goods_name",
"goods_price",
"goods_number"
};
tableModel = new DefaultTableModel();
for(String i :columnStrings)
tableModel.addColumn(i);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
ct=DriverManager.getConnection("jdbc:odbc:bean");
System.out.println("select * from test.dbo,Inventory");
ps = ct.prepareStatement("select * from Market.dbo.Inventory");
rs= ps.executeQuery();
while(rs.next()){
Vector<String> Ve= new Vector<>();
Ve.add(rs.getString(1));
Ve.add(rs.getString(2));
Ve.add(rs.getString(3));
Ve.add(rs.getString(4));
tableModel.addRow(Ve);
}
}catch(Exception e){
System.out.println("ERROR:"+e);
}
table = new JTable(tableModel);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(selectAndDisplay);
TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(tableModel);
table.setRowSorter(sorter);
show = new JTextField();
tablePane = new JScrollPane(table);
this.setLayout(new BorderLayout());
this.add(tablePane);
this.add(show,BorderLayout.SOUTH);
this.setTitle("JTable Model Test ");
this.setSize(500,300);
this.setVisible(true);
this.setDefaultCloseOperation(3);
}
public static void main(String[] args) {
new TableModel();
}
}