JTable简单介绍,以及tableModel的使用

package com.tr.homework;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

import com.dao.*;
import com.entity.Login;

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);
        // 用来获得鼠标点击位置的内容
        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));
            }
        });
        jt.setRowHeight(30);// 设置表格的行高
        // jt.setRowSelectionAllowed(false);// 不能直接选中一行
        // jt.setSelectionMode(1);//里面为0只允许选择一个,为1,可以连续选择多个,为2可以任意选择多个
        // jt.setSelectionBackground(Color.red);//选中的背景颜色
        jt.setSelectionForeground(Color.red);// 设置选中的文字颜色
        // jt.setAutoResizeMode(1);
        // 设置表格的自动调整模式,0-关闭自动调整,1-只调整下一列的宽度,2-比例调整其后所有列的宽度,3-只调整最后一列的宽度
        // 4.按比例调整所有列的宽度
        jt.setRowSorter(new TableRowSorter(tableModel));
        // 增加一个排序器
        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;
            }
        }
        /*
         * Object rowData[][] = { { 1, 2, 3 }, { 2, 3, 4 }, { 5, 6, 7 } };
         * Object columnNames[] = { 1, 2, 3 };
         */
        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);
    }
}
使用 AbstractTableModel 构建Table 在表格中添加JButton按钮,之前在网上找了2天没有找到好用的程序,最终终于找到一个好用的例子。 不要使,我退你们分。。 sing the Swing JTable class can quickly become a sticky business when you want to customize it to your specific needs. First you must become familiar with how the JTable class is organized. Individual cells are rendered by TableCellRenderer implementations. The table contents are represented by an implementation of the TableModel interface. By default, JTable uses DefaultTableCellRenderer to draw its cells. DefaultTableCellRenderer recognizes a few primitive types, rendering them as strings, and can even display Boolean types as checkboxes. But it defaults to displaying the value returned by toString() for types it does not specifically handle. You have to provide your own TableCellRenderer implementation if you want to display buttons in a JTable. The TableCellRenderer interface contains only one method, getTableCellRendererComponent(...), which returns a java.awt.Component that knows how to draw the contents of a specific cell. Usually, getTableCellRendererComponent() will return the same component for every cell of a column, to avoid the unnecessary use of extra memory. But when the contents of a cell is itself a component, it is all right to return that component as the renderer. Therefore, the first step towards having JButtons display correctly in a JTable is to create a TableCellRenderer implementation that returns the JButton contained in the cell being rendered. In the accompanying code listing, JTableButtonRenderer demonstrates how to do this. Even after creating a custom TableCellRenderer, you're still not done. The TableModel associated with a given JTable does not only keep track of the contents of each cell, but it also keeps track of the class of data stored in each column. DefaultTableModel is designed to work with DefaultTableCellRenderer and will return java.lang.String.class for columns containing data types that it does not specifically handle. The exact method that does this is getColumnClass(int column). Your second step is to create a TableModel implementation that returns JButton.class for cells that contain JButtons. JTableButtonModel shows one way to do this. It just returns the result of getClass() for each piece of cell data. At this point, you're almost done, but not quite. What's the use of putting a JButton in a JTable if you can't press the darn thing? By default, JTable will not forward mouse events to components contained in its cells. If you want to be able to press the buttons you add to JTable, you have to create your own MouseListener that forwards events to the JButton cells. JTableButtonMouseListener demonstrates how you could do this.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值