jtabledemo.java
来自「java课件 java课件 java课件 java课件」· Java 代码 · 共 101 行
JAVA
101 行
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;
import javax.swing.table.*;
public class JTableDemo extends JFrame{
JTable table;
String titles[];
JScrollPane scrollpane;
AbstractTableModel model;
Vector records;
public JTableDemo(){
records = new Vector();
model = new AbstractTableModel(){
public int getColumnCount(){
return titles.length;
}
public int getRowCount(){
return records.size();
}
public Object getValueAt(int row,int column){
if(!records.isEmpty()){
return ((Vector)records.elementAt(row)).elementAt(column);
}else
return null;
}
public String getColumnName(int column){
return titles[column];
}
public void setValuesAt(Object value,int row,int column){
}
public Class getColumnClass(int c){
return getValueAt(0,c).getClass();
}
public boolean isCellEditable(int row,int column){
return false;
}
};
}
public void start() throws SQLException,ClassNotFoundException{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:student";
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select * from student");
ResultSetMetaData meta = rst.getMetaData();
int cols = meta.getColumnCount();
System.out.println(cols);
titles = new String[cols];
for(int i=0;i<cols;i++){
titles[i]=meta.getColumnName(i+1);
}
records.removeAllElements();
while(rst.next()){
Vector rec_vector =new Vector();
for(int i=0;i<titles.length;i++){
rec_vector.addElement(rst.getObject(i+1).toString());
}
records.addElement(rec_vector);
}
table = new JTable(model);
table.setToolTipText("Display all result");
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setCellSelectionEnabled(false);
table.setShowVerticalLines(true);
table.setShowHorizontalLines(true);
scrollpane = new JScrollPane(table);
getContentPane().add(scrollpane);
model.fireTableStructureChanged();
}
public static void main(String[]args){
JTableDemo frame = new JTableDemo();
try{
frame.start();
}catch(Exception e){
e.printStackTrace();
}
frame.setSize(400,300);
frame.setTitle("Show Student data");
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?