how to transfer data from java txt file to JTable
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
JFrame tableFrame = new JFrame("Table");
JPanel tablePanel = new JPanel();
tablePanel.setLayout(new BorderLayout());
DefaultTableModel defaultTableModel = new DefaultTableModel();
defaultTableModel.addColumn("Integers");
JTable table = new JTable(defaultTableModel);
JScrollPane scrollPane = new JScrollPane(table);
JButton button = new JButton("Load");
button.addActionListener(event -> {
try (BufferedReader fileIn = new BufferedReader(new InputStreamReader(new FileInputStream("data.txt")))) {
String line;
while ((line = fileIn.readLine()) != null) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new String[]{line});
}
} catch (Exception e) {
}
});
tablePanel.add(scrollPane, BorderLayout.CENTER);
tablePanel.add(button, BorderLayout.SOUTH);
tableFrame.add(tablePanel);
tableFrame.setSize(200, 250);
tableFrame.setResizable(false);
tableFrame.setVisible(true);
tableFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Comments
Leave a comment