gpt4 book ai didi

java - 是否可以一次更新JTable的整行

转载 作者:行者123 更新时间:2023-11-30 07:19:47 24 4
gpt4 key购买 nike

是否可以一次更新 JTable 的整行,而不是按列更新??这是我下面的程序目前我只能修改列使用

model.setValueAt("1111", 0, 0)

我可以用吗

model.setValueAt(new Object[]{"1111","Pavan","Developer"}, 0, 0);


import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class Preethi {
protected void initUI() {
final DefaultTableModel model = new DefaultTableModel(new String[] {
"Id", "Name", "Desg" }, 0);
final JTable table = new JTable(model);
// table.setFillsViewportHeight(true);
JFrame frame = new JFrame(Preethi.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollpane = new JScrollPane(table);
frame.add(scrollpane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
Vector vec = new Vector();
vec.add("1122");
vec.add("Iraneee");
vec.add("Dev");
model.insertRow(0, vec);
model.setValueAt("1111", 0, 0);
//model.setValueAt(new Object[]{"1111","Pavan","Developer"}, 0, 0);

}

public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Preethi().initUI();
}
});
}

}

最佳答案

作为docs指示,setValueAt 设置单个单元格值。

Sets the object value for the cell at column and row. aValue is the new value.

但是,您可以重载处理Object 数组的方法:

class MyTableModel extends DefaultTableModel {

public MyTableModel(Object[] columnNames, int rowCount) {
super(columnNames, rowCount);
}

public void setValueAt(Object[] valueArray, int row) {
int column = 0;
for (Object cellValue: valueArray) {
setValueAt(cellValue, row, column);
column++;
}
}
}

使用此模型,您将能够为给定行设置值:

model.setValueAt(new Object[] { "1111", "Pavan", "Developer" }, 0);

略短的版本:

class MyTableModel extends DefaultTableModel {

public MyTableModel(Object[] columnNames, int rowCount) {
super(columnNames, rowCount);
}

public void setValueAt(Object[] valueArray, int row) {

getDataVector().setElementAt(new Vector(Arrays.asList(valueArray)), row);
}
}

关于java - 是否可以一次更新JTable的整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14415981/

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