使用JTable实现一些excel功能

时间:2013-10-19 16:38:37

标签: java swing jtable spreadsheet

我正在尝试实现MS EXCEL的Summation功能,但没有办法从JTable单元获取值。你能建议我从细胞中获取值并将其用于我的函数吗?

1 个答案:

答案 0 :(得分:1)

例如,如何获得价值 -

  String data[][] = {{"Value1", "Value2", "Value3"},{"Value4", "Value5", "Value6"},
  {"Value7", "Value8", "Value9"},{"Value10", "Value11", "Value12"}};

  String col[] = {"Column1", "Column2", "Column3"};  

  DefaultTableModel model = new DefaultTableModel(data, col);
  JTable table = new JTable(model);
  ...
  System.out.println(table.getModel().getValueAt(2, 2)); // row index and column index
  ...

它给出了 -

Value9

要从表中获取值,您可以在匿名内部类中实现接口MouseListener,例如 -

table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
         JTable target = (JTable) e.getSource();

         int rowIndex = target.getSelectedRow();
         int columnIndex = target.getSelectedColumn();

        System.out.println(target.getModel().getValueAt(rowIndex, columnIndex));
     }
});

另见: