I am a newbie in Java. I have a problem with making the program save the data in the txt file from the table and show it again after restart. I don't have idea how to make it. Can somebody help me with making this programme with auto-saving and keeping table info in txt file and then viewable table after restart? I would be very grateful ;)
Ui.java:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class Ui extends Main {
public DefaultTableModel m = new DefaultTableModel();
public JTable jt = new JTable(m);
static JMenuBar menuBar = new JMenuBar();
public void table(){
m.addRow(new String[] {"a1"});
m.addRow(new String[] {"a2"});
m.addRow(new String[] {"a3"});
m.addColumn("1");
m.addColumn("2");
m.addColumn("3");
m.addColumn("4");
m.addColumn("5");
JScrollPane sp = new JScrollPane(jt);
sp.setBounds(0,0,628,444);
frame.getContentPane().add(sp);
}
public void bar() {
frame.setJMenuBar(menuBar);
JMenu menu2 = new JMenu("File");
JMenuItem m2_1 = new JMenuItem("Exit");
JMenuItem m2_2 = new JMenuItem("Save");
m2_1.addActionListener((event) -> System.exit(0));
m2_1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
menu2.add(m2_2);
menu2.add(m2_1);
menuBar.add(menu2);
JMenu menu1 = new JMenu("Help");
JMenuItem m1_1 = new JMenuItem("Contact ");
JMenuItem m1_2 = new JMenuItem("About ");
menu1.add(m1_1);
menu1.add(m1_2);
menuBar.add(menu1);
JMenu menu3 = new JMenu("Add");
JMenuItem m3_1 = new JMenuItem("Add row");
menu3.add(m3_1);
menuBar.add(menu3);
m1_1.addActionListener(e -> JOptionPane.showMessageDialog(null,
"Text",
"Contact", JOptionPane.PLAIN_MESSAGE));
m1_2.addActionListener(e -> JOptionPane.showMessageDialog(null,
"Text ",
"About", JOptionPane.PLAIN_MESSAGE));
m3_1.addActionListener(e -> m.addRow(new String[]{}));
}
}
Main.java:
import javax.swing.*;
import java.awt.*;
public class Main {
static JFrame frame = new JFrame("Title of frame");
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException |
IllegalAccessException e) {
throw new RuntimeException(e);}
Ui p = new Ui();
p.table(); p.bar();
Image icon = Toolkit.getDefaultToolkit().getImage("icons\\logo.jpeg");
frame.setIconImage(icon);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(645, 506);
frame.setResizable(false);
frame.setVisible(true);
}
}