如何使用 Java 中的 TableModel 从表单元格中获取值?


首先,使用 DefaultTableModel 创建一个表 −

String data[][] = {
   {"Australia","5","1"},
   {"US","10","2"},
   {"Canada","9","3"},
   {"India","7","4"},
   {"Poland","2","5"},
   {"SriLanka","5","6"}
};
String col [] = {"Team","Selected Players","Rank"};
DefaultTableModel tableModel = new DefaultTableModel(data,col);
JTable table = new JTable(tableModel);

现在,使用 getModel() 从表单元格中获取该值 −

Object ob = table.getModel().getValueAt(3, 2);
System.out.println("Value = "+ob);

以下是一个通过 TableModel 从表单元格中获取值的示例 −

示例

package my;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      JFrame frame = new JFrame("Demo");
      JPanel panel = new JPanel();
      String data[][] = {
         {"Australia","5","1"},
         {"US","10","2"},
         {"Canada","9","3"},
         {"India","7","4"},
         {"Poland","2","5"},
         {"SriLanka","5","6"}
      };
      String col [] = {"Team","Selected Players","Rank"};
      DefaultTableModel tableModel = new DefaultTableModel(data,col);
      JTable table = new JTable(tableModel);
      table.getTableHeader().setResizingAllowed(false);
      Dimension dim = new Dimension(50,2);
      table.setIntercellSpacing(new Dimension(dim));
      Object ob = table.getModel().getValueAt(3, 2);
      System.out.println("Value = "+ob);
      JScrollPane scrollPane = new JScrollPane(table);
      panel.add(scrollPane);
      frame.add(panel);
      frame.setSize(600,400);
      frame.setUndecorated(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getRootPane().setWindowDecorationStyle(JRootPane.INFORMATION_DIALOG);
      frame.setVisible(true);
   }
}

输出

单元格的值将在控制台中显示 −

更新日期:30-07-2019

712 次浏览

开启你的 职业生涯

完成课程认证

开始
广告