gpt4 book ai didi

java - 从 jTable 获取单个 INT 值

转载 作者:行者123 更新时间:2023-12-01 12:01:59 25 4
gpt4 key购买 nike

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

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

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

最佳答案

您将行号放入了错误的参数中。根据 JTable API 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();
}
});
}
}

关于java - 从 jTable 获取单个 INT 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27927959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com