Potresti usare un file di properties.
codice:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class Simple extends JFrame implements ActionListener, WindowListener{
private Properties config;
private JLabel label;
private JButton bottoneScrivi;
private JTextField campo;
private JPanel tmp;
public Simple(){
super("test properties");
//Carico il file di properties, se presente (in caso non sia presente l'oggetto config sarà vuoto)
config = new Properties();
try {
config.load(new FileInputStream("simo.properties"));
} catch (Exception e) {}
//carico la proprietà 'chiave' nella label, se non presente assegno il valore di default 'Proprietà non presente'
label = new JLabel(config.getProperty("chiave", "Proprietà non presente"));
bottoneScrivi = new JButton("Modifica proprietà");
bottoneScrivi.addActionListener(this);
campo = new JTextField(10);
tmp = new JPanel();
tmp.setLayout(new GridLayout(2,2));
tmp.add(label);
tmp.add(new JPanel());
tmp.add(campo);
tmp.add(bottoneScrivi);
this.add(tmp, BorderLayout.NORTH);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(this);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
//Al click del bottone salvo il nuovo valore della proprietà nell'oggetto config
config.setProperty("chiave", campo.getText());
label.setText(config.getProperty("chiave"));
}
public void windowClosing(WindowEvent e) {
//Prima di chiudere la finestra salvo le proprietà su file.
try {
config.store(new FileOutputStream("simo.properties"), null);
} catch (Exception ex) {
ex.printStackTrace();
}
this.dispose();
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public static void main(String[] args) {
new Simple();
}
}