Jtable中嵌入JCombox

package com.zte.settool;
import javax.swing.table.AbstractTableModel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ColumnModelTest{
    public ColumnModelTest() {
   JFrame f = new JFrame();
   /*由于我们的MyTable类继承了AbstractTableModel并且实作了getColmunCount(),
    * getRowCount(),getValueAt()方法.因此我们可以通
    *过MyTable来产生TableModel的实体.
    */
   MyTable mt=new MyTable();
   JTable t=new JTable(mt);//我们利用MyTable来建立JTable.
   JComboBox c = new JComboBox();//建立一个JComboBox的对象.
   c.addItem("南京");//我们在新建立的JComboBox对象里新增三个项目.
   c.addItem("上海");
   c.addItem("广州");
    /*我们利用JTable所提供的getTableColumnModel()方法取得TableColumnModel对象,再由TableColumnModel类所提供的getColumn()方
     *法取得TableColumn对象,TableColumn类可针对表格中的每一行做具体的设置,例如设置字段的宽度,某行的标头,设置输入较复杂的
     *数据类型等等.在这里,我们利用TableColumn类所提供的setCellEditor()方法,将JComboBox作为第二行的默认编辑组件.
     */
   t.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(c));
   t.setPreferredScrollableViewportSize(new Dimension(550, 30));
        JScrollPane s = new JScrollPane(t);
       
        f.getContentPane().add(s, BorderLayout.CENTER);
    f.setTitle("test");
        f.pack();
        f.setVisible(true);
       
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public static void main(String args[]) {
        new ColumnModelTest();
    }
}
class MyTable extends AbstractTableModel{
private static final long serialVersionUID = 1L;
Object[][] p = {
            {"张三", "南京",new Integer(66),
              new Integer(32),new Boolean(false)},
            {"李四", "上海",new Integer(85),
              new Integer(69),new Boolean(false)},         
        };
        String[] n = {"姓名",
                  "地址",
                      "数学",
                      "总分",
                      "及格"};
        public int getColumnCount() {
            return n.length;
        }

        public int getRowCount() {
            return p.length;
        }

        public String getColumnName(int col) {
            return n[col];
        }

        public Object getValueAt(int row, int col) {
            return p[row][col];
        }
    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }
    /**
     * 例如勾选CheckBox或是直接修改某个字段的数字,需要重写这两个方法
     */
    public boolean isCellEditable(int rowIndex, int columnIndex) {
    return true;
    }
    public void setValueAt(Object value, int row, int col) {
        p[row][col] = value;
    fireTableCellUpdated(row, col);
    }
   

}

你可能感兴趣的:(C++,c,swing,F#,C#)