我无法保存Form应用程序的状态并加载其状态。我使用netbeans在Java中创建了一个简单的Swing应用程序。该计划的目的是吐出一个唯一的4位数字,并在必要时有一个注释。我遇到了麻烦,我试图序列化数据,这样当应用程序再次打开时,我就可以从我停止的地方加载数据了。
以下是Swing Portion的代码:
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.Map;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author marcsantiago
*/
public class MainForm extends javax.swing.JFrame {
/**
* Creates new form MainForm
*/
public MainForm() {
//jTextField2.setVisible(false);
this.rndn = new RandomNumber();
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jCheckBox1 = new javax.swing.JCheckBox();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jTextField3 = new javax.swing.JTextField();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Generate Number");
jButton1.setToolTipText("");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextField1.setToolTipText("");
jCheckBox1.setText("Add Notes");
jButton2.setText("Save Note and Number");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("View Notes");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton4.setText("Save All Data");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton5.setText("Load Data");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(112, 112, 112)
.addComponent(jButton3)
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(77, 77, 77)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addComponent(jCheckBox1)))
.addGap(0, 82, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(111, 111, 111))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCheckBox1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public RandomNumber rndn;
//View Randomly Generated Number buttom
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jTextField1.setText(rndn.getNumber());
}
//save number button
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(jCheckBox1.isSelected()){
String text = jTextField3.getText();
rndn.removeNumber(text);
}else{
rndn.removeNumber("");
}
}
//view notes
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
StringBuilder sb = new StringBuilder();
for (Map.Entry<String,String> entry : rndn.getSaveState().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append("ID: ").append(key).append("\t");
sb.append("Note: ").append(value).append("\n");
}
jTextArea1.setText(sb.toString());
}
//save data
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
BufferedReader txtReader = rndn.getTxtReader();
ArrayList<String> numbers = rndn.getNumbers();
ArrayList<String> usedNumbers = rndn.getUsedNumbers();
String currentNumber = rndn.getCurrentNumber();
Map<String, String> saveState = rndn.getSaveState();
try
{
FileOutputStream fileOut = new FileOutputStream("/tmp/data.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(rndn);
out.close();
fileOut.close();
}catch(IOException i)
{
i.printStackTrace();
}
}
//load data
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// try
// {
// FileInputStream fileIn = new FileInputStream("/tmp/data.ser");
// ObjectInputStream in = new ObjectInputStream(fileIn);
// rndn = (RandomNumber) in.readObject();
// in.close();
// fileIn.close();
// }catch(IOException i)
// {
// i.printStackTrace();
// return;
// }catch(ClassNotFoundException c)
// {
// System.out.println("Employee class not found");
// c.printStackTrace();
// return;
// }
// System.out.println(rndn.getSaveState());
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField3;
// End of variables declaration
}
接近结尾我将这两个方法评论为// save和// load 那些方法我无法弄清楚。当我尝试序列化rndn对象时,我收到此错误:java.io.NotSerializableException:java.io.BufferedReader 包含数据的类是来自Form Class的serrate: 这是RandomNumber类:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author marcsantiago
*/
public class RandomNumber implements java.io.Serializable{
private BufferedReader txtReader;
private ArrayList<String> numbers;
private ArrayList<String> usedNumbers = new ArrayList<>();
private Random rnd = new Random();
private String currentNumber;
private Map<String, String> saveState = new HashMap<>();
RandomNumber(){
this.txtReader = new BufferedReader(new InputStreamReader(RandomNumber.class.getResourceAsStream("/resources/unique_nums")));
try{
numbers = new ArrayList(Arrays.asList(txtReader.readLine().split(",")));
}catch(IOException e){
}
}
public String getNumber(){
int item = rnd.nextInt(numbers.size());
currentNumber = numbers.get(item);
while(usedNumbers.contains(currentNumber)){
item = rnd.nextInt(numbers.size());
currentNumber = numbers.get(item);
}
return currentNumber;
}
public void removeNumber(String note){
usedNumbers.add(currentNumber);
saveState.put(currentNumber, note);
numbers.remove(currentNumber);
}
public ArrayList<String> getUsedNumbers() {
return usedNumbers;
}
public String getCurrentNumber() {
return currentNumber;
}
public Map<String, String> getSaveState() {
return saveState;
}
public void setTxtReader(BufferedReader txtReader) {
this.txtReader = txtReader;
}
public BufferedReader getTxtReader() {
return txtReader;
}
public ArrayList<String> getNumbers() {
return numbers;
}
public Random getRnd() {
return rnd;
}
public void setNumbers(ArrayList<String> numbers) {
this.numbers = numbers;
}
public void setUsedNumbers(ArrayList<String> usedNumbers) {
this.usedNumbers = usedNumbers;
}
public void setRnd(Random rnd) {
this.rnd = rnd;
}
public void setCurrentNumber(String currentNumber) {
this.currentNumber = currentNumber;
}
public void setSaveState(Map<String, String> saveState) {
this.saveState = saveState;
}
}
抱歉,如果它有点乱,我还没有清理代码,因为我还没有按照我想要的方式工作。非常感谢您完成此申请的任何帮助。
答案 0 :(得分:1)
您班级中的BufferedReader
不可串行化,应该导致问题。设为transient
,它应该有效。