package com.jTablehomework;
import java.awt.*;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.swing.*;
import com.dao.CRUDDAO;
import com.entry.Login;
/**
*
* @author zzy
*
* 2016年12月1日下午1:52:29
*/
public class JTableDemo extends JFrame {
private JScrollPane jsp;
private JTable jt;
private DefaultTableModel tableModel;
public static void main(String[] args) {
new JTableDemo();
}
public JTableDemo() {
init();
setSize(400, 500);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void init() {
Container con = getContentPane();
con.setLayout(new BorderLayout());
createJTable(con);
}
public void createJTable(Container con) {
JLabel jl = new JLabel("用户信息");
jl.setHorizontalAlignment(SwingConstants.CENTER);
addData();
jt = new JTable(tableModel) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
System.out.println(jt.getName());
// 用来获得鼠标点击位置的内容
jt.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int selectRow = jt.getSelectedRow();
// System.out.println(selectRow);
// int selectcow = jt.getSelectedColumn();
for (int i = 0; i < jt.getColumnCount(); i++) {
System.out.print(jt.getColumnName(i) + ":");
System.out.print(jt.getValueAt(selectRow, i) + "\t");
}
System.out.println();
// System.out.println(selectcow);
// System.out.println(tableModel.getValueAt(selectRow,
// selectcow));
Vector v = tableModel.getDataVector();
}
});
jt.setRowHeight(30);// 设置表格的行高
jt.setSelectionForeground(Color.red);// 设置选中的文字颜色
jsp = new JScrollPane(jt);
jsp.setViewportView(jt);
con.add(jl, BorderLayout.NORTH);
con.add(jsp, BorderLayout.CENTER);
}
public void addData() {
List<Login> list = getData();
Field[] field = Login.class.getDeclaredFields();
/**
* 设置标题
*/
Object columnNames[] = new Object[field.length];
for (int i = 0; i < field.length; i++) {
columnNames[i] = field[i].getName();
}
/**
* 填充内容
*/
Object rowData[][] = new Object[list.size()][];
for (int i = 0; i < list.size(); i++) {
Login l = list.get(i);
Object ob[] = new Object[field.length];
for (int j = 0; j < field.length; j++) {
field[j].setAccessible(true);
try {
ob[j] = field[j].get(l);
} catch (IllegalArgumentException e) {
e.printStackTrace();
System.out.println("底层字段不可访问");
} catch (IllegalAccessException e) {
e.printStackTrace();
System.out.println("对象不是声明字段的实例");
}// 返回此对象上此字段的值
rowData[i] = ob;
}
}
tableModel = new DefaultTableModel(rowData, columnNames);
}
public List<Login> getData() {
String sql = "select * from Login";
Map<String, Object[]> m = new LinkedHashMap<String, Object[]>();
m.put(sql, null);
return new CRUDDAO<Login>(Login.class).selectAll(m).get(1);
}
}
自己创建实体类 jtree里面的点击事件只要在switch里面输入查询语句和实体类就行了
jdbc部分:
需要用到我之前的jdbc 和basejdbc
文章连接:
http://blog.csdn.net/fvdfsdafdsafs/article/details/53420589