如何在Jtable中动态添加列名?

时间:2018-08-06 08:54:35

标签: java jtable

我在我的项目中使用Jtable,在其中按下Tab键时会添加新列,但该列的名称不存在。它在那个地方显示空白,我希望列名应该是excel格式,即。像excel列名应该是A,B,C等。所以我应该检查些什么。

private void datatypetableKeyPressed(java.awt.event.KeyEvent evt) {                                         

        if (evt.getKeyCode() == KeyEvent.VK_TAB) {
            addColumn();
        }
    } 

private void addColumn() {
        DefaultTableModel model = (DefaultTableModel) datatypetable.getModel();
        JTableHeader th = datatypetable.getTableHeader();
        TableColumnModel tcm = th.getColumnModel();
        TableColumn tc = tcm.getColumn(0);

        if (model != null) {
            Vector v = new Vector(1);
            for (int j = 0; j < datatypetable.getRowCount(); j++) {
                tc.setHeaderValue("???");
                v.add("");


            }
            model.addColumn(v);
            th.repaint();
        }
    }

这是我向jtable添加新列的代码。

3 个答案:

答案 0 :(得分:1)

您可以添加这样的列。

DefaultTableModel model = new DefaultTableModel();

JTable table = new JTable(model);
//add you dynamic column name logic. ex, I am adding with i loop variable.
for( int i=1; i<5;i++){
model.addColumn("Col"+i);
}

希望您有办法添加列。

答案 1 :(得分:1)

我已经以这种方式完成了它的工作。...希望我的回答能帮助任何人...

private void datatypetableKeyPressed(java.awt.event.KeyEvent evt) {                                         
            if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                int col = datatypetable.getSelectedColumn();
                int row = datatypetable.getSelectedRow();
                int colCount = datatypetable.getColumnCount();
                int rowCount = datatypetable.getRowCount();
                col++;
                if (col >= colCount) {
                    col = 0;
                    row++;
                }
                if (row >= rowCount) {
                    row = 0;
                }
    //            datatypetable.getSelectionModel().setSelectionInterval(row, row);
    //            datatypetable.getColumnModel().getSelectionModel().setSelectionInterval(col, col);
    //            datatypetable.editCellAt(row, col);
                if (row == rowCount - 1) {
                    addRow();
                    datatypetable.scrollRectToVisible(datatypetable.getCellRect(rowCount, 0, true));
                }
            }

            if (evt.getKeyCode() == KeyEvent.VK_TAB) {
                int col = datatypetable.getSelectedColumn();
                int row = datatypetable.getSelectedRow();
                int colCount = datatypetable.getColumnCount();
                int rowCount = datatypetable.getRowCount();
                col++;
                if (col >= colCount) {
                    col = 0;
                    row++;
                }
                if (row >= rowCount) {
                    row = 0;
                }
    //            datatypetable.getSelectionModel().setSelectionInterval(row, row);
    //            datatypetable.getColumnModel().getSelectionModel().setSelectionInterval(col, col);
    //            datatypetable.editCellAt(row, col);
                if (col == colCount - 1) {
                    addColumn();
                    int selectedRow = 0;
                    datatypetable.editCellAt(selectedRow, 0);
                    datatypetable.setSurrendersFocusOnKeystroke(true);
                    datatypetable.getEditorComponent().requestFocus();
                    datatypetable.scrollRectToVisible(datatypetable.getCellRect(colCount, 0, true));
                }
            }

        }  


    private void addRow() {
            DefaultTableModel model = (DefaultTableModel) datatypetable.getModel();

            if (model != null) {
                Vector v = new Vector(1);
    //            for (int j = 0; j <= datatypetable.getColumnCount(); j++) {
    //                v.add("");
    //            }
                v.add("");
                model.addRow(v);
            }
        }

        private void addColumn() {
            DefaultTableModel model = (DefaultTableModel) datatypetable.getModel();

            if (model != null) {
                Vector v = new Vector(1);
    //            for (int j = 0; j < datatypetable.getRowCount(); j++) {
    //                v.add("");
    //            }
                v.add("");
                model.addColumn(Character.toString((char) ('A' + datatypetable.getColumnCount())), v);
            }
        }

答案 2 :(得分:0)

  

我希望当我在该列中写了一些东西之后,应该生成该列...否则....

好的,基本上,当您确定您位于最后一列并按下 Tab 键时,您想确定当前列是否具有任何值,如果它包含任何“空”单元格,那么它将简单地移至下一行/第一列,否则将添加新列。

以下测试假定空单元格是具有null值的单元格,因此,如果您的需求不同,则需要更新代码以支持它。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JTable table = new JTable();
                table.setGridColor(Color.GRAY);
                table.setShowGrid(true);
                DefaultTableModel model = new DefaultTableModel();
                for (int col = 0; col < 10; col++) {
                    Vector<String> colData = new Vector<String>(10);
                    for (int row = 0; row < 10; row++) {
                        colData.add(row + "x" + col);
                    }
                    model.addColumn(Character.toString((char)('A' + col)), colData);
                }
                table.setModel(model);

                InputMap im = table.getInputMap();
                im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Action.NextCell");
                im.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "Action.NextCell");

                ActionMap am = table.getActionMap();
                am.put("Action.NextCell", new NextCellActioin(table, model));

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class NextCellActioin extends AbstractAction {

        private JTable table;
        private DefaultTableModel model;

        public NextCellActioin(JTable table, DefaultTableModel model) {
            this.table = table;
            this.model = model;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            int col = table.getSelectedColumn();
            int row = table.getSelectedRow();

            int colCount = table.getColumnCount();
            int rowCount = table.getRowCount();

            col++;
            boolean newColumn = true;
            if (col >= colCount) {
                int lastColumn = colCount - 1;
                for (int index = 0; index < table.getRowCount(); index++) {
                    if (table.getValueAt(index, lastColumn) == null) {
                        newColumn = false;
                        break;
                    }
                }
                if (!newColumn) {
                    col = 0;
                    row++;
                }
            }

            if (newColumn) {
                String name = Character.toString((char) ('A' + model.getColumnCount() + 1));
                model.addColumn(name);
                col++;
            } else {
                if (row >= rowCount) {
                    row = 0;
                }
            }
            table.getSelectionModel().setSelectionInterval(row, row);
            table.getColumnModel().getSelectionModel().setSelectionInterval(col, col);
        }

    }

}
  

当我们双击该列时

我假设您希望在双击最后一列时能够添加新列。基本思想与上面的键绑定中提供的思想相同,您计算出的列是否为最后一个,如果是最后一个,则确定该列是否包含任何“空”值,然后根据需要添加该列

table.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
            int viewCol = table.columnAtPoint(e.getPoint());
            if (viewCol == table.getColumnCount()) {
                // You know, check there are values
                // make new column as needed
            }
        }
    }
});