从jTable获取单个INT值

时间:2015-01-13 17:28:06

标签: java swing object int jtable

我有一个包含两个值的表:A和B. 是否可以使用getSelectedRow()来获取A作为int?

此刻我得到了这个,它找不到变量A的符号

 DefaultTableModel tm = (DefaultTableModel)jTabela.getModel();    
 int A = Integer.parseInt( tm.getValueAt(jTabela.A, getSelectedRow()).toString() );

1 个答案:

答案 0 :(得分:1)

您将行号放入错误的参数中。根据{{​​3}} getValueAt(...)方法需要两个int参数,第一个是行索引,第二个是列索引。所以你想要的东西是:

DefaultTableModel tm = (DefaultTableModel)jTabela.getModel(); 
int row = tm.getSelectedRow();
if (row == -1) {
   return;
}
Object value = jTabela.getValueAt(row, whateverYourColumnIs);
int intValue = value != null ? Integer.parseInt(value.toString()) : 0;

例如:

import java.awt.BorderLayout;
import java.util.Vector;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
public class TableExample extends JPanel {
   private static final String[] COLUMNS = {"Name", "Value"};
   private DefaultTableModel model = new DefaultTableModel(COLUMNS, 0) {
      public java.lang.Class<?> getColumnClass(int columnIndex) {
         Object value = getValueAt(0, columnIndex);
         if (value == null) {
            return super.getColumnClass(columnIndex);
         } else {
            return value.getClass();
         }
      };
   };
   private JTable table = new JTable(model);

   public TableExample() {
      for (int i = 0; i < 10; i++) {
         String name = "Row " + (i + 1);
         int value = (i + 1) * 10;
         Vector<Object> row = new Vector<>();
         row.add(name);
         row.add(value);
         model.addRow(row);
      }
      table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

         @Override
         public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
               return;
            }
            int row = table.getSelectedRow();
            if (row == -1) {
               return;
            }
            Object value = table.getValueAt(row, 1); // numbers are in row 1
            if (value != null) {
               System.out.println("Selected value: " + value);
               int intValue = Integer.parseInt(value.toString());
               // can use value here
            }
         }
      });

      setLayout(new BorderLayout());
      add(new JScrollPane(table));
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("Table Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new TableExample());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}