Пожалуйста, помогите мне, что мне делать, если я хочу добавить новую строку, отредактировать строки и удалить строки из моей таблицы? Я пытался что-то сделать, но это не сработало. (Таблица открывает CSV-файлы, где столбцы разделены ;
, например, строка выглядит следующим образом:JTable - Добавление, редактирование, удаление строк
Майк, Тайсон, 50; [email protected]; 123123123
Вот мой код :
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
public class T1Data extends JPanel {
private final JTable table;
private MyModel model;
private JPanel buttonsPanel;
static File currentFile; //remember edited file
public T1Data() {
super(new BorderLayout(3, 3));
model = new MyModel();
table = new JTable(model);
table.setModel(model);
this.table.setPreferredScrollableViewportSize(new Dimension(700, 70));
this.table.setFillsViewportHeight(true);
JPanel ButtonOpen = new JPanel(new FlowLayout(FlowLayout.CENTER));
add(ButtonOpen, BorderLayout.SOUTH);
// Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
// Add the scroll pane to this panel.
add(scrollPane, BorderLayout.CENTER);
//Create button panel
buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout(5, 50, 5));
//add 'Open button
JButton open = new JButton("Open...");
buttonsPanel.add(open);
//add 'Add' button
JButton add = new JButton("Add row");
buttonsPanel.add(add);
//add 'Remove' button
JButton remove = new JButton("Remove row");
buttonsPanel.add(remove);
//add 'Save' button
JButton save = new JButton("Save");
buttonsPanel.add(save);
//add 'Save as...' button
JButton saveAs = new JButton("Save As...");
buttonsPanel.add(saveAs);
//add buttonPanel to Frame
add(buttonsPanel, BorderLayout.SOUTH);
// add a nice border
setBorder(new EmptyBorder(10, 10, 10, 10));
//'Open' button action
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter(
"Text/CSV file", "txt", "csv");
fileopen.addChoosableFileFilter(filter);
int ret = fileopen.showDialog(null, "Choose file");
if (ret == JFileChooser.APPROVE_OPTION) {
// Read Text file
File file = fileopen.getSelectedFile();
T1Data.currentFile = file;
CSVFile Rd = new CSVFile();
MyModel NewModel = new MyModel();
table.setModel(NewModel);
ArrayList<String[]> Rs2 = Rd.ReadCSVfile(file);
NewModel.AddCSVData(Rs2);
System.out.println("Rows: " + NewModel.getRowCount());
System.out.println("Cols: " + NewModel.getColumnCount());
}
}
});
//'Add row' button action
/*
add.addActionListener(new ActionListener(){
new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row!=-1) model.deleteRow(row);
}
}
});
*/
//'Remove row' button action
remove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row!=-1) model.deleteRow(row);
}
});
//'Save' button action
save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e){
try{
//the file path
File file = currentFile;
//if the file not exist create one
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
//loop for jtable rows
for(int i = 0; i < table.getRowCount(); i++){
//loop for jtable column
for(int j = 0; j < table.getColumnCount(); j++){
bw.write(table.getModel().getValueAt(i, j)+";");
}
//break line at the begin
//break line at the end
bw.write("\r\n");
}
//close BufferedWriter
bw.close();
//close FileWriter
fw.close();
JOptionPane.showMessageDialog(null, "Dane zostały zapisane.");
}catch(Exception ex){
ex.printStackTrace();
}
}
});
//'Save As...' button action
saveAs.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e){
try{
JFileChooser chooser = new JFileChooser(".");
int status = chooser.showSaveDialog(T1Data.this);
if (status == JFileChooser.APPROVE_OPTION) {
//the file path
File file = chooser.getSelectedFile();
//if the file not exist create one
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
//loop for jtable rows
for(int i = 0; i < table.getRowCount(); i++){
//loop for jtable column
for(int j = 0; j < table.getColumnCount(); j++){
bw.write(table.getModel().getValueAt(i, j)+";");
}
//break line at the begin
//break line at the end
bw.write("\r\n");
}
//close BufferedWriter
bw.close();
//close FileWriter
fw.close();
JOptionPane.showMessageDialog(null, "File saved.");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
});
}
// Method for reading CSV file
public class CSVFile {
private final ArrayList<String[]> Rs = new ArrayList<String[]>();
private String[] OneRow;
public ArrayList<String[]> ReadCSVfile(File DataFile) {
try {
BufferedReader brd = new BufferedReader(new FileReader(DataFile));
while (brd.ready()) {
String st = brd.readLine();
OneRow = st.split(";"); // OneRow = st.split(",|\\s|;");
Rs.add(OneRow);
System.out.println(Arrays.toString(OneRow));
} // end of while
} // end of try
catch (Exception e) {
String errmsg = e.getMessage();
System.out.println("File not found:" + errmsg);
} // end of Catch
return Rs;
}// end of ReadFile method
}// end of CSVFile class
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("T1Data");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
T1Data newContentPane = new T1Data();
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
class MyModel extends AbstractTableModel {
//public boolean isCellEditable(int row, int col) { return true; } //CELL EDITING
private final String[] columnNames = { "Name", "Surname", "Age", "Email", "Telephone"};
private ArrayList<String[]> Data = new ArrayList<String[]>();
public void AddCSVData(ArrayList<String[]> DataIn) {
this.Data = DataIn;
this.fireTableDataChanged();
}
@Override
public int getColumnCount() {
return columnNames.length;// length;
}
@Override
public int getRowCount() {
return Data.size();
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int row, int col) {
return Data.get(row)[col];
}
/*
DOESN'T WORK!!!!!!!!!!!!!!!!!!!1
// Deletes the given row
public void deleteRow(int row) {
if (row == -1) return;
Data.remove(row);
fireTableRowsDeleted(row, row);
}
*/
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
}
Вы можете удалить некоторые из этого дополнительного кода? – CaffeineToCode
@ jaa232 см. Ответы MadProgrammer о [JTable + AbstractTableModel + ArrayList] (http://stackoverflow.com/search?q=user%3A992484+ [jtable] + abstracttablemodel + arraylist + is% 3Aanswer), он ссылается, наиболее активно в AbstractTableModel против различные типы массивов – mKorbel