日期:2014-05-20  浏览次数:20856 次

各位大神,如何用TableModel实例化JTable?
package myeditmytable;

import javax.swing.*;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.table.AbstractTableModel;

class Mytable extends AbstractTableModel{
Object [][] computer={{"CPU","p4赛扬346",540},{"主板","foxconnPM800",564},{"内存","infinen",320},{"硬盘","seagate80G",410},{"液晶显示器","LG",1860},{"光驱","LGDVD",180},{"机箱电源","foxconn",260},{"鼠标键盘","套件",50}};
String []items={"部件","名称","价格"};

public int getRowCount(){
return computer.length;
}
public int getColumnCount(){
return items.length;
}
public boolean isCellEditable(int rowIndex,int columnIndex){
if(columnIndex==1)
return false;
else
return true;
}
public Object getValueAt(int row,int column){
return 0;
}
public void setValueAt(Object aValue,int rowIndex,int columnIndex){
computer[rowIndex][columnIndex]=aValue;
this.fireTableCellUpdated(rowIndex, columnIndex);
}
}

public class EditJTable {

public static void main(String[]args){
final Mytable mytable=new Mytable();
final JTable tab=new JTable(mytable);
JLabel lab1=new JLabel("个人电脑配置",JLabel.CENTER);
JScrollPane scroll=new JScrollPane(tab);
final JLabel lab2=new JLabel("所选部件的价格为:");
JButton pricebtn=new JButton("计算总价格");
JFrame frame=new JFrame();
frame.getContentPane().add(scroll);
JPanel pane=new JPanel();
pane.add(pricebtn);
pane.add(lab2);
frame.add(lab1,BorderLayout.NORTH);
//frame.add(tab,BorderLayout.CENTER);
frame.add(pane,BorderLayout.SOUTH);
frame.setVisible(true);
frame.pack();


pricebtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
double price=0.0;
for(int i=0;i<mytable.getRowCount();i++){
price+=Double.parseDouble(mytable.computer[i][2].toString());
}
lab2.setText("所选部件的价格为:"+String.valueOf(price));
}
});
}

}
我的这段代码TableModel为什么不能实例化JTable?
各位大神请赐教。

------解决方案--------------------
Java code
package test;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import java.awt.*;

public class TableModelDemo extends JFrame {
    private JTable table;

    public TableModelDemo() {
        Container container = getContentPane();
        addTable(container);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 400);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    protected void addTable(Container container) {
        String[] columnNames = {"First Name", "Last Name", "Sport",
                "# of Years", "Vegetarian"
        };

        Object[][] rowData = {
                {"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)}
        };

        table = new JTable(new MyTableModel(rowData, columnNames));
        table.setFillsViewportHeight(true);
        container.add(new JScrollPane(table));

        // 设置列宽
        TableColumn column = null;
        for (int i = 0; i < columnNames.length; ++i) {
            column = table.getColumnModel().getColumn(i);

            if (2 == i) {
                column.setPreferredWidth(150);
            } else {
                column.setPreferredWidth(50);
            }
        }

        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent event) {
                if (!event.getValueIsAdjusting()) {
                    TableModel model = table.getModel();
                    int row = table.getSelectedRow();
                    int column = table.getSelectedColumn();
                    System.out.println(model.getValueAt(row, column));
                }
            }
        });
    }

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

    protected class MyTableModel extends AbstractTableModel {
        private String[] columnNames;
        private Object[][] rowData;

        public MyTableModel(Object[][] rowData, String[] columnNames) {
            this.rowData = rowData;
            this.columnNames = columnNames;
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public int getRowCount() {
            return rowData.length;
        }

        @Override
        public String getColumnName(int col) {
            return columnNames[col];
        }

        @Override
        public Class getColumnClass(int col) {
            // 如果是boolean,则显示为JCheckBox
            // 如果是Integer,则只能输入整数
            return getValueAt(0, col).getClass();
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            // 第一列不能编辑
            return col == 0 ? false : true;
        }

        @Override
        public Object getValueAt(int row, int col) {
            return rowData[row][col];
        }

        @Override
        public void setValueAt(Object value, int row, int col) {
            // 双击时cell editor显示,然后输入值
            // 当cell失去焦点或者按下回车键后,setValueAt方法被调用,更新cell renderer
            System.out.println("setValuAt: Value: " + value + ", [" + row + ", " + col + "]");
            rowData[row][col] = value;
            fireTableCellUpdated(row, col);
        }
    }
}