Я играю в морскую битву в java, я создал меню с помощью JMenubar и хочу сохранить и загрузить игру.
Я создал класс chargerActionListener , который реализует ActionListener, чтобы добавить его к элементу в моем меню, но он не работает, это не возвращает мне ошибку, но не загружает объект плато , моя функция загрузки верна, я протестировал это.
package actionlistener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JFileChooser;
import Main.Plateau;
import interfaceGraphique.Fenetre;
import ioforme.IOPlateau;
public class ChargerActionListener implements ActionListener {
public Fenetre fenetre;
public Plateau plateau;
public ChargerActionListener(Fenetre fenetre)
{
this.fenetre = fenetre;
}
public void actionPerformed(ActionEvent arg0) {
JFileChooser choix = new JFileChooser();
int retour=choix.showOpenDialog(fenetre);
if(retour==JFileChooser.APPROVE_OPTION){
try {
Plateau p = IOPlateau.lire(choix.getSelectedFile().getAbsolutePath());
fenetre.setPlateau(p);
System.out.println(choix.getSelectedFile().getAbsolutePath());
fenetre.actualiserGrilleCible();
fenetre.actualiserMaGrille();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Я написал этот код быстро, он работает отлично, но та же проблема. У меня три кнопки; один, чтобы сохранить, загрузить и отобразить человеческий объект в консоли, я могу сохранить без беспокойства. например : я запускаю программу с human ("jean", 10) (в основной функции), который я сохраняю. Я закрываю свою программу и меняю человек («жан», 50) , когда я нажимаю кнопку загрузки, я загружаю свой файл, сохраненный ранее, и я нажимаю на кнопку, чтобы отобразить в консоли, она отобразит меня «Человек [Жан, 50] "но я хочу" Человек [Жан, 10] "
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.swing.*;
public class Main {
public static class Human implements Serializable {
String name;
int age;
public Human(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String toString() {
return "Human [name=" + name + ", age=" + age + "]";
}
}
public static class ChargerActionListener implements ActionListener {
public Fenetre fenetre;
public ChargerActionListener(Fenetre fenetre)
{
this.fenetre = fenetre;
}
public void actionPerformed(ActionEvent arg0) {
JFileChooser choix = new JFileChooser();
int retour=choix.showOpenDialog(null);
if(retour==JFileChooser.APPROVE_OPTION){
try {
Human h = IOPlateau.lire(choix.getSelectedFile().getAbsolutePath());
fenetre.setHuman(h);
System.out.println(choix.getSelectedFile().getAbsolutePath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static class SauvegarderActionListener implements ActionListener {
public Fenetre fenetre;
public SauvegarderActionListener(Fenetre fenetre)
{
this.fenetre = fenetre;
}
public void actionPerformed(ActionEvent arg0) {
JFileChooser choix = new JFileChooser();
int retour=choix.showSaveDialog(null);
if(retour==JFileChooser.APPROVE_OPTION){
try {
IOPlateau.sauver(fenetre.getHuman(),choix.getSelectedFile().getAbsolutePath());
System.out.println(choix.getSelectedFile().getAbsolutePath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static class Fenetre extends JFrame {
private Human human;
Fenetre (Human human)
{
this.human = human;
this.setTitle("test");
this.setSize(1200,500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton save = new JButton ();
save.addActionListener(new SauvegarderActionListener(this));
JButton load = new JButton();
load.addActionListener(new ChargerActionListener(this));
JButton display = new JButton ();
JPanel panel = new JPanel (new GridLayout(1,3));
// Button for load and save !
panel.add(save);
panel.add(load);
panel.add(display);
this.setContentPane(panel);
display.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evenement)
{
System.out.println(human);
}
});
this.setVisible(true);
}
public void setHuman (Human human)
{
this.human = human;
}
public Human getHuman ()
{
return this.human;
}
}
public static class IOPlateau {
public static Human lire(String fileName) throws IOException {
Human h = null;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
try {
h = (Human) ois.readObject();
} catch (ClassNotFoundException cnfe) {
// erreur de lecture
} catch (EOFException eofe) {
//fin de fichier
}
ois.close();
return h;
}
public static void sauver(Human h, String fileName) throws IOException {
try {
// Recevoir le fichier
File f = new File(fileName);
// Créer un nouveau fichier
// Vérifier s'il n'existe pas
if (f.createNewFile())
System.out.println("File created");
else
System.out.println("File already exists");
}
catch (Exception e) {
System.err.println(e);
}
ObjectOutputStream oos;
oos = new ObjectOutputStream(new FileOutputStream(fileName));
oos.writeObject(h);
oos.close();
}
}
public static void main(String[] args) {
Human human = new Human ("Jean",11);
Fenetre fenetre = new Fenetre(human);
}
}