如何更新JTable内容

时间:2014-02-24 18:54:43

标签: java swing jtable

以下代码会创建一个JTable,其中包含一些数据和JButton来处理事件。

按下按钮时,必须更改第一列中的JTable数据(请参阅getData(int)方法)。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


public class JTableDemo extends JFrame {

    private static final long serialVersionUID = 1L;

    JPanel pan = new JPanel();
    JTable tab = new JTable();
    JButton but = new JButton("Change");


    private int i=1;

    Object[][] data = {
            {"Kathy", "Smith", "Snowboarding", new Integer(5), 
                new Boolean(false)},
            {"John", "Doe", "Rowing", new Integer(3), new Boolean(true)},
            {"Sue", "Black", "Knitting", new Integer(2), new Boolean(false)},
    };

    String[] colNames = {"Roll No", "Name", "Fee Status", "Another", 
            "Some More"};

    DefaultTableModel tabmod = new DefaultTableModel(data,colNames);
    JTableDemo(){
        setVisible(true);
        setSize(500,500);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        //setLayout(null);

    //tabmod = new DefaultTableModel(data,colNames);
        tab.setModel(tabmod);
        pan.add(new JScrollPane(tab));
        pan.add(but);
        add(pan);

        but.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){

                data = getData(i);
                i++;
                System.out.println(data[0][0]);
                tabmod.fireTableDataChanged();
                tab.repaint();
                tab.invalidate();
            }
        });

    }

    private Object[][] getData(int cnt){
        if(cnt%2==0){
        Object[][] data = {
                {"DTR", "Smith",
                     "Snowboarding", new Integer(5), new Boolean(false)},
                    {"ANR", "Doe",
                     "Rowing", new Integer(3), new Boolean(true)},
                    {"STR", "Black",
                     "Knitting", new Integer(2), new Boolean(false)},
                    };
        return(data);
        }
        else{
            Object[][] data = {
                    {"Dharma", "Smith",
                         "Snowboarding", new Integer(5), new Boolean(false)},
                        {"Teja", "Doe",
                         "Rowing", new Integer(3), new Boolean(true)},
                        {"Reddy", "Black",
                         "Knitting", new Integer(2), new Boolean(false)},
                        };
            return(data);
        }
    }


    public static void main(String[] args) {
        new JTableDemo();
    }

}

我怎样才能做到这一点?

请帮帮我。 抱歉我的英文不好

0 个答案:

没有答案