Why my JTextArea is not displaying properly from the while loop? - java

My GUI application allows users to type into a JTextField object stating the name of a file to open and display its contents onto a JTextArea object. If the entered information consists of the file name then it shall retrieve its contents otherwise, in other case, it shall be a directory then it shall display the files and folders. Right now, I'm stuck as in the setText() of my JTextArea does not display contents correctly. It only display once which means to say there's some problem with my while loop. Could you guys help me out here please?
Please note the code below has been altered to the correct working version provided all the helpful contributors below.
Main class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
class MyFileLister extends JPanel implements ActionListener {
private JLabel prompt = null;
private JTextField userInput = null;
private JTextArea textArea = null;
public MyFileLister()
{
prompt = new JLabel("Enter filename: ");
prompt.setOpaque(true);
this.add(prompt);
userInput = new JTextField(28);
userInput.addActionListener(this);
this.add(userInput);
textArea = new JTextArea(10, 30);
textArea.setOpaque(true);
JScrollPane scrollpane = new JScrollPane(textArea);
this.add(textArea, BorderLayout.SOUTH);
}
Scanner s = null;
File af = null;
String[] paths;
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
while(s.hasNextLine())
{
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(truea);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath = "";
for(String path: paths)
{
tempPath += path + "\n";
}
textArea.setText(tempPath);
}
}
}
Driver class:
import java.util.*;
import java.awt.*;
import javax.swing.*;
class TestMyFileLister {
public static void main(String [] args)
{
MyFileLister thePanel = new MyFileLister();
JFrame firstFrame = new JFrame("My File Lister");
firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstFrame.setVisible(true);
firstFrame.setSize(500, 500);
firstFrame.add(thePanel);
}
}
Here's one of the screenshot which I have to achieve. It shows that when the user's input is on a directory it displays the list of files and folders under it.
I tried to put in an if statement to see if I can slot in a show message dialog but I seriously have no idea where to put it.
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
if(af == null)
{
System.out.println("Error");
}
while(s.hasNextLine())
{
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(true);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath = "";
for(String path: paths)
{
tempPath += path + "\n";
}
textArea.setText(tempPath);
}
}

You're outputting text to textArea based on the Last File on the list !!! ( don't set your text to JTextArea directly inside a loop, the loop is fast and the UI can't render it, so concatenate the string then set it later after the loop finishes ).
// These lines below are causing only last file shown.
for(String path: paths)
{
textArea.setText(path);
}
Here is your modified version for MyFileLister class :
public class MyFileLister extends JPanel implements ActionListener {
private JLabel prompt = null;
private JTextField userInput = null;
private JTextArea textArea = null;
public MyFileLister()
{
prompt = new JLabel("Enter filename: ");
prompt.setOpaque(true);
this.add(prompt);
userInput = new JTextField(28);
userInput.addActionListener(this);
this.add(userInput);
textArea = new JTextArea(10, 30);
textArea.setOpaque(true);
JScrollPane scrollpane = new JScrollPane(textArea);
this.add(scrollpane, BorderLayout.SOUTH);
}
Scanner s = null;
File af ;
String[] paths;
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
while(s.hasNext())
{
String as = s.next();
textArea.setText(as);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath="";
for(String path: paths)
{
tempPath+=path+"\n";
}
textArea.setText(tempPath);
}
}
}
Output :

Code:
public void actionPerformed(ActionEvent ae) {
try (Scanner s = new Scanner(new File(userInput.getText()))) {
while (s.hasNextLine()) {
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(true);
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this,
"File not found",
"No File Error",
JOptionPane.ERROR_MESSAGE);
}
}
Notes:
Just try to read your file line by line so you can copy the same structure from your file into your JTextArea.
Use setLineWrap method and set it to true
read here http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#setLineWrap(boolean)
use append method in order to add text to end of your JTextArea
read here
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#append(java.lang.String)
Use JOptionPane to show error message to an user

Related

How to make a String available in other classes

I've managed to make the input into a string which is available within the same class but I want to make it so the input string can be available in different classes. Current class is OpenDetails and I want the string selectedFile to be available in a different class called OpenFileInfo. How would I set it so the result from selectedFile can be stored in either selectedRequirement or make it available in other classes?
I'm new to Java so if someone could help thank you.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class OpenFile
{
String selectedRequirement = "";
public static void main(String a[])
{
JFrame parent = new JFrame();
String selectedFile;
selectedFile = JOptionPane.showInputDialog(parent, "Add a new module");
if(selectedFile.equalsIgnoreCase(selectedFile)){
//Makes the user input case insensitive
}
final JTextArea edit = new JTextArea(60,100);
JButton read = new JButton("Open "+ selectedFile +".txt");
read.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileReader reader = new FileReader(selectedFile + ".txt");
BufferedReader br = new BufferedReader(reader);
edit.read( br, null );
br.close();
edit.requestFocus();
}
catch(Exception e2) { System.out.println(e2); }
}
});
JButton write = new JButton("Save "+ selectedFile + ".txt");
write.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter writer = new FileWriter(selectedFile + ".txt");
BufferedWriter bw = new BufferedWriter( writer );
edit.write( bw );
bw.close();
edit.setText("");
edit.requestFocus();
}
catch(Exception e2) {}
}
});
System.out.println("Module: " + selectedFile);
JFrame frame = new JFrame("Requirements");
frame.getContentPane().add( new JScrollPane(edit), BorderLayout.NORTH );
frame.getContentPane().add(read, BorderLayout.WEST);
frame.getContentPane().add(write, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
As you are running from a static context, you need to define selectedRequirement as static:
private static String selectedRequirement = "";
To make selectedRequirement equal to selectedFile, simply say selectedRequirement = selectedFile; towards the end of the main function (maybe where you print it already).
To make selectedRequirement available to other classes, you need to create a "getter function" in the OpenFIle class (outside of the main function) like:
public String getSelectedRequirement(){
return selectedRequirement;
}
As pointed out in the comments, it would be a good idea for you (or anyone who finds this in the future) to look at some tutorials on getters, setters, and general encapsulation.

Deleting a set of data in text file

I'm creating a program in Java(GUI) that when you fill out the TextFields and click enter; the name,age,email,nationality and cell number will be saved in a textfile named StoredInfo.txt . The program I created didn't delete the data you entered if you fill out the textfields again.
What I want want to do is to use the Clear Data button I created and it will delete all the data stored in the text file (StoredInfo.txt).
Here's my program:
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SignUp extends JFrame implements ActionListener
{
//Variables
private JButton enter,clear;
private JLabel header,name,age,email,nationality,cellno;
private JTextField nameTF,ageTF,emailTF,nationalityTF,cellnoTF;
private Container container;
private PrintWriter pwriter;
//Constructor
public SignUp()
{
setTitle("Form");
setSize(500,500);
setResizable(false);
setDefaultCloseOperation(this.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(null);
container = this.getContentPane();
container.setBackground(Color.GRAY);
enter = new JButton("Enter");
clear = new JButton("Clear Data");
header = new JLabel("Form");
name = new JLabel("Name: ");
age = new JLabel("Age: ");
email = new JLabel("Email Address: ");
nationality = new JLabel("Nationality: ");
cellno = new JLabel("Cellphone #: ");
nameTF = new JTextField(20);
ageTF = new JTextField(20);
emailTF = new JTextField(20);
nationalityTF = new JTextField(20);
cellnoTF = new JTextField(20);
nameTF.addActionListener(this);
ageTF.addActionListener(this);
emailTF.addActionListener(this);
nationalityTF.addActionListener(this);
cellnoTF.addActionListener(this);
enter.addActionListener(this);
clear.addActionListener(this);
//Add section
this.add(header);
this.add(name);
this.add(age);
this.add(email);
this.add(nationality);
this.add(cellno);
this.add(header);
this.add(nameTF);
this.add(ageTF);
this.add(emailTF);
this.add(nationalityTF);
this.add(cellnoTF);
this.add(clear);
this.add(enter);
//SetBounds
enter.setBounds(180,270,80,40);
clear.setBounds(270,270,100,40);
header.setBounds(230,30,80,50);
header.setFont(new Font("Arial",Font.BOLD,25));
header.setForeground(Color.WHITE);
name.setBounds(80,90,40,40);
age.setBounds(80,120,40,40);
email.setBounds(80,150,110,40);
nationality.setBounds(80,180,100,40);
cellno.setBounds(80,210,100,40);
nameTF.setBounds(180,95,190,25);
ageTF.setBounds(180,125,190,25);
emailTF.setBounds(180,155,190,25);
nationalityTF.setBounds(180,185,190,25);
cellnoTF.setBounds(180,215,190,25);
name.setForeground(Color.WHITE);
age.setForeground(Color.WHITE);
email.setForeground(Color.WHITE);
nationality.setForeground(Color.WHITE);
cellno.setForeground(Color.WHITE);
//Setting Up Text File
try
{
File data = new File("StoredInfo.txt");
pwriter = new PrintWriter(new FileWriter(data,false));
if(data.exists())
{
}else
{
data.createNewFile();
}
}catch(Exception e)
{
e.printStackTrace();
}
setVisible(true);
}
//Actions
public void actionPerformed(ActionEvent e)
{
Object action = e.getSource();
if(action.equals(enter))
{
pwriter.println("Name: " + nameTF.getText());
pwriter.println("Age: " + ageTF.getText());
pwriter.println("Email: " + emailTF.getText());
pwriter.println("Nationality: " + nationalityTF.getText());
pwriter.println("CellNo #: " + cellnoTF.getText());
pwriter.println("---------------------------");
pwriter.flush();
pwriter.close();
}else if(action.equals(clear))
{
}
}
///Main
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new SignUp();
}
});
}
}
Generally speaking new FileWriter(file); will overwrite the file leaving it empty.
In your case,
else if (action.equals(clear)) {
// Need to close this first to avoid resource leak
pw.close();
File data = new File("StoredInfo.txt");
// I believe you will need pw later
pw = new PrintWriter(new FileWriter(data, false));
}
Hope that helped.

Buffered Reader

I have a program which asks you for your first name and second name. I used OutputStream to save the first name in a file stored in the workspace. I use a BufferedReader to read the file but I'm trying to get it so if the person clicks yes on the JOptionPane.YES_NO_DIALOG, it uses the name in the file! I've tried doing and if Statement that said if JOptionPane... then text.setText(savedName), but it just comes out as "Welcome null null"
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class BingoHelper extends JFrame implements WindowListener, ActionListener{
JTextField text = new JTextField();
//JLabel bg = new JLabel("helo");
private JButton b; {
b = new JButton("Click to enter name");
}
JPanel pnlButton = new JPanel();
public static String fn;
public static String sn;
public static int n;
File f = new File("test.txt");
public void actionPerformed (ActionEvent e){
Object[] yesNo = {"Yes",
"No",};
n = JOptionPane.showOptionDialog(null,"Would you like to use previously entered data?","Welcome Back?",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null, yesNo,yesNo[1]);
if (n == JOptionPane.NO_OPTION){
for(fn=JOptionPane.showInputDialog("What is your first name?");!fn.matches("[a-zA-Z]+");fn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
fn=JOptionPane.showInputDialog("What is your first name?");
}
for(sn=JOptionPane.showInputDialog("What is your second name?");!sn.matches("[a-zA-Z]+");sn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
sn=JOptionPane.showInputDialog("What is your second name?");
}
}
//JOptionPane.showMessageDialog(null, "Welcome " + fn + " " + sn + ".", "", JOptionPane.INFORMATION_MESSAGE);
text.setText("Welcome " + fn + " " + sn + ".");
b.setVisible(false);
b.setEnabled(false);
text.setVisible(true);
text.setBounds(140,0,220,20);
text.setHorizontalAlignment(JLabel.CENTER);
text.setEditable(false);
text.setBackground(Color.YELLOW);
pnlButton.setBackground(Color.DARK_GRAY);
writeToFile();
//bg.setVisible(true);
}
private void writeToFile() {
String nameToWrite = fn;
OutputStream outStream = null;
try {
outStream = new FileOutputStream(f);
outStream.write(nameToWrite.getBytes());
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String savedName = br.readLine();
//System.out.println(savedName);
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != outStream) {
try {
outStream.close();
} catch (IOException e) {
// do nothing
}
}
}
}
When you use JOptionPane with your own options JOptionPane will return the index of the option select by the user...
That is, in your case, if the user selects "Yes", then JOptionPane will return 0 or if the user selects "No", it will return 1
So, instead of using JOptionPane.NO_OPTION you need use 1, for example...
Object[] yesNo = {"Yes",
"No",};
n = JOptionPane.showOptionDialog(null,"Would you like to use previously entered data?","Welcome Back?",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null, yesNo,yesNo[1]);
if (n == 1){
//...
}
I would also, strongly, encourage you to avoid using static field references in this context as it may result in unexpected behaviour if you ever get more then one instance of the class running ;)

How to make a Dropdown list of every String separated by a line from a file

How to put a dropdown list that has the list of every string, and when I select a item on that list then push the load button it will only show up what's on that String. Here's my code, I actually put the number of the string and and show the String's data using while statements.
How can I actually put a Dropdown list and it's content will be a number registered on every string. Just like this
1 231231
2 123124
3 123124
4 232312
If I select 4 and press "Load" it will show "232312"
and everytime I save a data a unique number will be registered in every line, just like
"4" is the unique no. and 232312 is it's data
package datasaving;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
public class Datasaving {
/**
* #param args the command line arguments
* #throws FileNotFoundException
* #throws IOException
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
final JTextField input0 = new javax.swing.JTextField(20);
final JTextField input1 = new javax.swing.JTextField(20);
final JTextField out = new javax.swing.JTextField(20);
final JTextField line = new javax.swing.JTextField(20);
JButton save = new javax.swing.JButton("Save");
JButton load = new javax.swing.JButton("Load");
frame.add(panel);
frame.setSize(240,200);
panel.add(input0);
panel.add(input1);
panel.add(save);
panel.add(line);
panel.add(out);
panel.add(load);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
File file = new File("data.dat");
try {
try (FileWriter writer = new FileWriter(file, true)) {
String data0 = input0.getText();
String data1 = input1.getText();
writer.write(data0+":"+data1+"\n");
}
System.out.println("Data Saved");
} catch (IOException | HeadlessException z) {
JOptionPane.showMessageDialog(null, e);
}
}
});
load.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int lines = Integer.parseInt(line.getText());
try {
FileInputStream fs= new FileInputStream("data.dat");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
for(int i = 0; i < lines; ++i) {
br.readLine();
}
out.setText(br.readLine());
JOptionPane.showMessageDialog(null, "Loaded");
} catch ( IOException | HeadlessException es) {
JOptionPane.showMessageDialog(null, e);
}
}
});
}
}
for example:
John blahblahblahblah
Keith blahblahblahblah
Joe blahblahblahblah
Kenneth blahblahblahblah
Christian blahblahblahblah
The first word "Names" will be added to JList or JComboBox
how to make the names a Array. I know how to use .split(); but I don't know how to make that happen in every lines in the file
1) JTextField doesn't support multi-line. Try JTextArea instead. With text areas, you can use myTextArea.append() to add lines as you read them.
2) But actually, it sounds like a JComboBox or a JList might be what you're really looking for:
http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html
3) Your basic program looks OK
'Hope that helps!

How to properly load a JFrame from a file?

I'm making this grade keeping program for my computer science class and the one thing I haven't gotten to work is saving/loading sessions. As I have it set up now it automatically saves when you exit and loads when you start if there is a file to load. However, I feel I'm loading or saving it incorrectly; there's one main JFrame that holds all the data, and that's the one object that is saved. When it's loaded, well, it'd be easier to show you.
If it looks like this when I close it::
Then it'll look like this when I start it up again:
Also, the "Enter Student" button, as well as the ActionListener on the JTextField used for input, cease to work when the program loads the JFrame. The program is split into 3 class files:
Gradebook:
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class GradeBook implements java.io.Serializable {
private static JFrame frame;
public static void main(String[] args) throws Exception{
try{
FileInputStream fis = new FileInputStream("t.tmp");
ObjectInputStream ois = new ObjectInputStream(fis);
frame = (JFrame) ois.readObject();
ois.close();
} catch(Throwable t) {
frame = new JFrame("Course Grades");
}
frame.addWindowListener(new closing());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new CourseGrade());
frame.pack();
frame.setVisible(true);
}
closing:
private static class closing extends WindowAdapter {
public void windowClosing(WindowEvent e) {
try {
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(frame);
oos.close();
} catch(Throwable t){System.out.println(t.getMessage());}
}
}
}
CourseGrade:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.FlowLayout;
import java.util.Random;
import javax.swing.table.*;
import java.io.*;
public class CourseGrade extends JPanel implements java.io.Serializable {
private JLabel entername;
private JTextField in;
private JTextArea list;
private JScrollPane scroll;
private String[] students = new String[1000];
private JButton enter;
private JButton[] studentbuttons = new JButton[1000];
private JButton[] delete=new JButton[1000];
private int numstudents;
private JFrame[] studentframes=new JFrame[1000];
private static JTable[] tables=new JTable[1000];
private static DefaultTableModel[] model=new DefaultTableModel[1000];
private static int[] numass=new int[1000];
public CourseGrade() {
String[][] data = {{"", "", "", ""}};
String[] headers = {"Assignment", "Date Assigned", "Score", "Percentage"};
for(int i=0; i<tables.length; i++){
model[i] = new DefaultTableModel(data, headers);
tables[i] = new JTable(model[i]){
public boolean isCellEditable(int rowIndex, int colIndex) {
return false;
}
};
}
numstudents=0;
in=new JTextField(13);
in.addActionListener(new enterListener());
list=new JTextArea();
scroll=new JScrollPane(list);
list.setEditable(false);
entername=new JLabel("Enter a student's name");
enter=new JButton("Enter Student");
enter.addActionListener(new enterListener());
setPreferredSize(new Dimension(260, 300));
setBackground(Color.green);
add(entername);
add(in);
add(enter);
add(scroll);
scroll.setPreferredSize(new Dimension(240, 200));
}
private class enterListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String x=in.getText();
String y="";
String z="";
in.setText("");
int a=numstudents+1;
if(x.length()>0) x=a+". " + x + "\n";
students[numstudents] = x;
if(x.length()>0)numstudents++;
for(int i=0; i<numstudents; i++){
x=students[i];
if(x.length()>13)x=x.substring(0,11)+"...\n";
y+=x;
}
studentbuttons[numstudents]=new JButton("Edit");
studentbuttons[numstudents].addActionListener(new grades());
delete[numstudents]=new JButton("Delete");
delete[numstudents].addActionListener(new del());
list.setText(y);
list.add(studentbuttons[numstudents]);
studentbuttons[numstudents].setBounds(100,(numstudents-1)*16,55,15);
list.add(delete[numstudents]);
delete[numstudents].setBounds(160,(numstudents-1)*16,70,15);
}
}
private class grades implements ActionListener {
public void actionPerformed(ActionEvent event) {
Object obj = event.getSource();
if(obj instanceof JButton){
JButton clicked = (JButton)obj;
int x=clicked.getY()/16;
String y=students[x];
for(int i=0; i<y.length(); i++){
String q=y.substring(i,i+1);
if(q.equals(" ")) {
y=y.substring(i+1);
i=y.length()+1;
}
}
studentframes[x]=new JFrame(y+"'s Grades");
studentframes[x].setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try{studentframes[x].getContentPane().add(new GradePage(x, tables[x], numass[x]));}
catch(Exception e){}
studentframes[x].pack();
studentframes[x].setVisible(true);
}
}
}
private class del implements ActionListener {
public void actionPerformed(ActionEvent event) {
Object obj = event.getSource();
if(obj instanceof JButton){
JButton clicked = (JButton)obj;
int x=clicked.getY()/16;
String y="", z="";
studentbuttons[numstudents].setVisible(false);
delete[numstudents].setVisible(false);
numstudents--;
int q=3;
int w=0;
for(int i=x; i<=numstudents; i++){
if(i<10)q=1;
else if(i<100) q=2;
tables[i]=tables[i+1];
numass[i]=numass[i+1];
model[i]=model[i+1];
w=i+1;
try{if(!students[i+1].equals(null)){students[i]=w+students[i+1].substring(q);} else{students[i]=null;}}catch(Throwable t){}
}
for(int i=0; i<numstudents; i++){
y=students[i];
if(y.length()>13)y=y.substring(0,11)+"...\n";
z+=y;
}
list.setText(z);
}
}
}
public static void setTable(int numtable, JTable table){
tables[numtable]=table;
}
public static void newRow(int numtable){
model[numtable].addRow(new Object[]{"", "", "", ""});
}
public static void setNumEntries(int numtable, int num){
numass[numtable]=num;
}
}
The third class shouldn't have anything to do with this so I wont post it for now.
I realize the code is probably poorly written but I'm only in my second year of High School computer science and we haven't actually covered any of this. This program wasn't even supposed to be a GUI, and this is the first time I've even heard of Input or Output streams so I really don't know anything about them. I realize now that having the classes implement java.io.Serializable was probably unnecessary but when I was trying to research this I came across someone taking about how some objects can't be saved because they don't naturally implement it. So sorry if it's some stupid mistake, and thanks for your time.
You can store the data in a notepad file like this
try
{
FileWriter file = new FileWriter( "insert file name here" );
BufferedWriter buffer = new BufferedWriter( file ) ;
buffer.write( "insert file content here" ) ;
buffer.newLine();
buffer.close();
}
catch ( IOException e )
{
//Insert error message here
}
And then read it like this
try
{
FileReader file = new FileReader( "insert file name here" ) ;
BufferedReader buffer = new BufferedReader( file );
String line = "" ;
while( ( line = buffer.readLine() ) != null )
{
System.out.println( line ) ;
}
buffer.close() ;
}
catch( IOException e )
{
//Insert error message here
}
Hope that helps
i dont recomend that you save JFrame object. here is a better solution you can save the students name and there grades on a text file and each time your program loads it will load the information from the text file.
Hint : you can use Input & Output streams dirctly but it's maybe a little bit sonfusing so go and read about these two classes :
Scanner (and how to use it to read from file)
PrintWriter (and how to use it to write to file)
P.S.: i could'v given you the code but it is much better learning experience to suffer a little bit to find information, because while you are trying to figure it out you will learn a lot of other things.
The frame is not an integral part of your application's state, it's just a way of displaying the important information (names, grades, etc). If you want to save your session, save the information the is currently on the screen and then re-create the JFrame with the deserialized information. An ObjectOutputStream is a reasonable way of writing things to disk, and and ObjectInputStream is good for reading the data back in. The documentation contains good examples. Also, your classes would need to implement Serializable.

Categories