This is how I add all of my JButtons to the panel and to the arraylist
private ArrayList<JButton> b;
String defaultLogo = "O";
for(int i=0; i<81;i++)
{
b.add(new JButton(defaultLogo));
b.get(i).addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < b.size(); i++){
if (e.getSource() == b.get(i)){
b.get(i).setText(getSymbol());
b.get(i).setForeground(getColor());
b.get(i).setBackground(getBackColor());
}
}
}
});
tilePanel.add(b.get(i));
}
The program allows a user to choose a symbol, background color, and foreground color and when each JButton is pressed it changes to the selected symbol, foreground color, and background color.
I want to be able to save the JButton configuration using DataOutputStream and DataInputStream. I have two action listeners attached to a save and load button that activate a save and load method when pressed. What should I write in each method to allow a user to save and load files of the JButton configurations.
save = new JMenuItem("Save");
file.add(save);
save.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==save){
save();
}
}
});
load = new JMenuItem("Load");
file.add(load);
load.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == load){
load();
}
}
});
You can try serialization, saving an object that holds your buttons.
Here's an example:
The object that holds the data
import java.io.Serializable;
import java.util.ArrayList;
public class Config implements Serializable {
private static final long serialVersionUID = 1L;
private ArrayList<String[]> Data;
public Config(){
Data=new ArrayList<String>();
}
public void addData(String path){
Data.add(path);
}
public String getData(int index){
return Data.get(index);
}
}
For serialization:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Paths;
import java.io.File;
public class FileSerial {
private FileSerial(){}
public static Config deserialize(){
Config result;
try {
FileInputStream fis = new FileInputStream(Paths.get("path to your file"));
ObjectInputStream ois = new ObjectInputStream(fis);
result = (Config) ois.readObject();
ois.close();
} catch (Exception e){
e.printStackTrace();
}
return result;
}
public static void serialize(Config obj){
try {
File file = new File(Paths.get("path to file"));
if(!file.exists()){
file.getParentFile().mkdirs();
}
FileOutputStream fos = new FileOutputStream(path.toString());
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
The filename of the object to serialize should have the extension ".ser"