我用Swing制作了一个扩展Jframe的GUI,我的jtable中有6列。我读取数据 从文本文件,第4列和第5列有值100和200,所以我想当用户在第4列编辑并将160而不是100列5自动更改为140或用户 第5列中的编辑说280而不是200列4自动更改为20.这是我的代码。
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class Cs extends JFrame
{
private JTable table;
private DefaultTableModel model;
public Cs()
{
String aLine ;
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
FileInputStream fin = new FileInputStream("cs.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while( st1.hasMoreTokens() )
{
columnNames.addElement(st1.nextToken());
}
while ((aLine = br.readLine()) != null)
{
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while(st2.hasMoreTokens())
{
row.addElement(st2.nextToken());
}
data.addElement( row );
}
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
}
public static void main(String[] args)
{
Cs frame = new Cs();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
答案 0 :(得分:0)
覆盖TableModel的setValueAt()并根据更改更新其他列。这是一个例子。希望这会对你有所帮助。
JFrame frame = new JFrame("Summation of 2 columns");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object rows[][] = { { 100, 200 } };
String columns[] = { "Column 1", "Column 2" };
JTable table = new JTable(new DefaultTableModel(rows, columns) {
private static final long serialVersionUID = 1L;
public Class<? extends Object> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
@Override
public void setValueAt(Object object, int row, int column) {
int changedValue = ((Integer) object).intValue();
if (column == 0) {
super.setValueAt(300 - changedValue, row, column + 1);
} else if (column == 1) {
super.setValueAt(300 - changedValue, row, column - 1);
}
super.setValueAt(object, row, column);
}
});
JScrollPane pane = new JScrollPane(table);
frame.add(pane, BorderLayout.CENTER);
frame.setSize(200, 150);
frame.setVisible(true);
您必须按照以下方式更改数据模型才能满足您的要求。
从
替换您的模型model = new DefaultTableModel(data, columnNames);
到
model = new DefaultTableModel(rows, columns) {
private static final long serialVersionUID = 1L;
public Class<? extends Object> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
@Override
public void setValueAt(Object object, int row, int column) {
int changedValue = ((Integer) object).intValue();
if (column == 2) {
super.setValueAt(300 - changedValue, row, column + 1);
} else if (column == 3) {
super.setValueAt(300 - changedValue, row, column - 1);
}
super.setValueAt(object, row, column);
}
};