当前位置: 动力学知识库 > 问答 > 编程问答 >

java - I have a text file loaded in a JTable, i want that the changes i make in the JTable to be made in in the text file as well, how can i do that?

问题描述:

String[] columns = {"nume", "compozitie", "indicatii", "contraindicatii", "administrare", "pret", "compensabil"};

Object[][] data = null;

try {

File file = new File("medicamente.txt");

FileReader fileReader = new FileReader(file);

BufferedReader bufferedReader = new BufferedReader(fileReader);

BufferedReader reader = new BufferedReader(new FileReader("medicamente.txt"));

int lines = 0;

while (reader.readLine() != null) {

lines++;

}

reader.close();

data = new Object[lines][];

String line;

int numLines = 0;

while ((line = bufferedReader.readLine()) != null) {

data[numLines] = line.split(",");

numLines++;

}

fileReader.close();

} catch (IOException e) {

e.printStackTrace();

}

final DefaultTableModel model = new DefaultTableModel(data, columns) {

@Override

public Class getColumnClass(int column) {

Class returnValue;

if ((column >= 0) && (column < getColumnCount())) {

returnValue = getValueAt(0, column).getClass();

} else {

returnValue = Object.class;

}

return returnValue;

}

};

JTable table = new JTable(model) {

public boolean isCellEditable(int row, int column) {

switch (column) {

case 5:

return true;

default:

return false;

}

}

};

final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);

table.setRowSorter(sorter);

JScrollPane scrollPane = new JScrollPane(table);

scrollPane.setPreferredSize(new Dimension(1000, 500));

mainPanel.add(scrollPane);

scrollPane.setBounds(0, 240, 995, 510);

as you can see i made one of the columns editable, the others are not. I read somewhere that the only solution is to clear the text file and than load the modified JTable in the text file. what would be the best option here ?

网友答案:

I read somewhere that the only solution is to clear the text file and than load the modified JTable in the text file.

Given that you are storing the data in a text file, that is correct.

You may want to check out Table Cell Listener. It tells you when data has changed in a cell. Then you can invoke your code to recreate the text file.

If you don't want to use this class then you can also use a TableModelListener for this purpose. Read the link for the difference between the two approaches.

分享给朋友:
您可能感兴趣的文章:
随机阅读: