saving and opening objects from a menu - java

here is my application. I'm having a problem saving objects and opening them. When I try to save it tells me the variable in the save.writeObject(firstName) cannot be resolved to a variable.
The problem is in the ActionPeformed block:
import java.awt.*;
import java.awt.event.*;
import java.io.File;
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.io.Serializable;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.util.*;
public class ClassRoomFrameTest
{
public static void main(String[] args)
{
ClassRoomFrame frame = new ClassRoomFrame();
frame.setSize(600,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
}
}
class ClassRoomFrame extends JFrame implements ActionListener
{
private JPanel mainPanel = new JPanel();
private JPanel deptPanel = new JPanel(new GridLayout(2,3));
private JPanel studentPanel = new JPanel(new GridLayout(2,5));
private JPanel displayPanel = new JPanel(new BorderLayout());
private JPanel buttonPanel = new JPanel(new GridLayout(1,2));
private JPanel menuBar = new JPanel();
private JTextArea textArea = new JTextArea();
private JScrollPane scrollPane = new JScrollPane(textArea);
private JLabel classLocationLabel = new JLabel("Class Location");
private JLabel classRoomLabel = new JLabel("Class Room Number");
private JLabel classCapacityLabel = new JLabel("Class Capacity");
private JTextField classLocationField = new JTextField();
private JTextField classRoomField = new JTextField();
private JTextField classCapacityField = new JTextField();
private JLabel studentFNameLabel = new JLabel("First name");
private JLabel studentLNameLabel = new JLabel("Last name");
private JLabel studentIDLabel = new JLabel("ID Number");
private JLabel studentMajorLabel = new JLabel("Major");
private JLabel studentCreditsLabel = new JLabel("Credits");
private JTextField studentFNameField = new JTextField();
private JTextField studentLNameField = new JTextField();
private JTextField studentIDField = new JTextField();
private JTextField studentMajorField = new JTextField();
private JTextField studentCreditsField = new JTextField();
private JButton addButton = new JButton("Add");
private JButton displayButton = new JButton("Display");
private JMenuBar menu = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem save = new JMenuItem("Open");
private JMenuItem open = new JMenuItem("Save");
private JFileChooser chooser = new JFileChooser();
Classroom room = null;
public ClassRoomFrame()
{
deptPanel.setPreferredSize(new Dimension(600,50));
deptPanel.setBorder(new EmptyBorder(new Insets(5,15,5,15)));
deptPanel.add(classLocationLabel);
deptPanel.add(classRoomLabel);
deptPanel.add(classCapacityLabel);
deptPanel.add(classLocationField);
deptPanel.add(classRoomField);
deptPanel.add(classCapacityField);
fileMenu.add(fileMenu);
fileMenu.add(open);
fileMenu.add(save);
menu.add(fileMenu);
studentPanel.setBorder(new EmptyBorder(new Insets(5,15,5,15)));
studentPanel.setPreferredSize(new Dimension(600,50));
studentPanel.setBorder(new EmptyBorder(new Insets(5,15,5,15)));
studentPanel.add(studentFNameLabel);
studentPanel.add(studentLNameLabel);
studentPanel.add(studentIDLabel);
studentPanel.add(studentMajorLabel);
studentPanel.add(studentCreditsLabel);
studentPanel.add(studentFNameField);
studentPanel.add(studentLNameField);
studentPanel.add(studentIDField);
studentPanel.add(studentMajorField);
studentPanel.add(studentCreditsField);
scrollPane.setBorder(new BevelBorder(BevelBorder.LOWERED));
scrollPane.setPreferredSize(new Dimension(600,450));
textArea.setBorder(new EmptyBorder(new Insets(5,15,5,15)));
buttonPanel.setBorder(new BevelBorder(BevelBorder.RAISED));
buttonPanel.setPreferredSize(new Dimension(600, 50));
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
addButton.addActionListener(this);
addButton.setActionCommand("Add");
displayButton.addActionListener(this);
displayButton.setActionCommand("Display");
open.addActionListener(this);
open.setActionCommand("Open");
save.addActionListener(this);
save.setActionCommand("Save");
mainPanel.add(deptPanel);
mainPanel.add(studentPanel);
mainPanel.add(scrollPane);
add(menu, BorderLayout.NORTH);
add(mainPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
}
#SuppressWarnings("unused")
public void actionPerformed(ActionEvent e)
{
/*---> HERE */if(e.getActionCommand().equals("Save"));
{
FileOutputStream saveFile = null;
ObjectOutputStream save = null;
try
{
saveFile = new FileOutputStream("ObjectData.txt");
save = new ObjectOutputStream(saveFile);
/*--->Error*/ save.writeObject(index);
save.writeObject(new Classroom());
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
} catch (IOException e1)
{
e1.printStackTrace();
}
finally
{
try {saveFile.close();
}catch(Exception exc){
System.out.println(exc.getMessage());
}
}
}
/*---> Here*/if (e.getActionCommand().equals("Open"))
{
ObjectInputStream in = null;
int returnVal = chooser.showOpenDialog(ClassRoomFrame.this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
try {
in = new ObjectInputStream(new FileInputStream(file));
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
} catch (IOException e1)
{
e1.printStackTrace();
}
}
try {
Student st = (Student)in.readObject();
Classroom cs = (Classroom)in.readObject();
System.out.println(st);
System.out.println(cs);
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
try{in.close();}
catch(Exception err){err.getMessage();}
}
if(e.getActionCommand().equals("Add"))
{
if(room == null)
{
room = new Classroom(classLocationField.getText(),
Integer.parseInt(classRoomField.getText()),
Integer.parseInt(classCapacityField.getText()));
room.addStudent(
new Student(studentFNameField.getText(),
studentLNameField.getText(),
studentIDField.getText(),
studentMajorField.getText(),
Integer.parseInt(studentCreditsField.getText())));
classLocationField.setEditable(false);
classRoomField.setEditable(false);
classCapacityField.setEditable(false);
studentFNameField.setText("");
studentLNameField.setText("");
studentIDField.setText("");
studentMajorField.setText("");
studentCreditsField.setText("");
textArea.setText("Class and first student added.");
}
else
{
room.addStudent(
new Student(studentFNameField.getText(),
studentLNameField.getText(),
studentIDField.getText(),
studentMajorField.getText(),
Integer.parseInt(studentCreditsField.getText())));
textArea.setText("Next student added.");
studentFNameField.setText("");
studentLNameField.setText("");
studentIDField.setText("");
studentMajorField.setText("");
studentCreditsField.setText("");
}
}
else if(e.getActionCommand().equals("Display"))
{
if (room != null)
{
textArea.setText(room.toString());
}
else
{
textArea.setText("Nothing to display");
}
}
}
}
class Student implements Serializable
{
public String firstName, lastName, studentIdNumber, studentMajor;
public int totalCourseCredits;
//-----------------------------------------------------------------
// Create an empty studentusing a default constructor.
//-----------------------------------------------------------------
public Student ()
{
}
//-----------------------------------------------------------------
// Creates a Student with the specified information.
//-----------------------------------------------------------------
public Student (String name1, String name2, String identification,
String myMajor, int myTotalCredits)
{
firstName = name1;
lastName = name2;
studentIdNumber = identification;
studentMajor = myMajor;
totalCourseCredits = myTotalCredits;
}
//-----------------------------------------------------------------
// Gets and sets first name.
//-----------------------------------------------------------------
public void setFirstName()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter your First Name: ");
firstName = scan.nextLine();
}
//-----------------------------------------------------------------
// Gets and sets last name.
//-----------------------------------------------------------------
public void setLastName()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter your Last Name: ");
lastName = scan.nextLine();
}
//-----------------------------------------------------------------
// Gets and sets Total Course Credits.
//-----------------------------------------------------------------
public void setTotalCredits()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter your Total Credits: ");
totalCourseCredits = scan.nextInt();
}
//-----------------------------------------------------------------
// Gets and sets Student ID Number.
//-----------------------------------------------------------------
public void setIdNumber()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter your ID Number: ");
studentIdNumber = scan.nextLine();
}
//-----------------------------------------------------------------
// Gets and sets Student Major.
//-----------------------------------------------------------------
public void setMajor()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter your Major: ");
studentMajor = scan.nextLine();
}
public String toString()
{
String s = "First name: " + firstName + "\n" +
"Last name: " + lastName + "\n" +
"StudentID: " + studentIdNumber + "\n" +
"Student Major: " + studentMajor + "\n" +
"Course Creidts: " + totalCourseCredits + "\n";
return s;
}
}
class Classroom implements Serializable
{
private Student[] classRoster;
private int index = 0;
private int capacityStudents, roomNumber;
private String buildingLocation;
//-----------------------------------------------------------------
// Creates an empty Classroom.
//-----------------------------------------------------------------
public Classroom()
{
capacityStudents = 0;
roomNumber = 0;
buildingLocation = "";
}
//-----------------------------------------------------------------
// Creates a Classroom with the specified information.
//-----------------------------------------------------------------
public Classroom(String location, int room, int cap)
{
capacityStudents = cap;
roomNumber = room;
buildingLocation = location;
classRoster = new Student[capacityStudents];
}
//-----------------------------------------------------------------
// Gets and sets Building Location.
//-----------------------------------------------------------------
public void setBuilding()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter the Building Location: ");
buildingLocation = scan.next();
}
//-----------------------------------------------------------------
// Gets and sets Room Number.
//-----------------------------------------------------------------
public void setRoomNumber()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter the Room Number: ");
roomNumber = scan.nextInt();
}
//-----------------------------------------------------------------
// Sets Capacity of Students.
//-----------------------------------------------------------------
public void setCapacityStudents()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter The Capacity of the Classroom: ");
capacityStudents = scan.nextInt();
classRoster = new Student[capacityStudents];
}
//-----------------------------------------------------------------
// Gets Capacity of Students.
//-----------------------------------------------------------------
public int getCapacityStudents()
{
return capacityStudents;
}
//-----------------------------------------------------------------
// Adds an Individual Student to the Classroom, checking if the
// capacity of the clasroom is full.
//-----------------------------------------------------------------
public void addStudent (Student student)
{
if(index < capacityStudents)
{
classRoster[index] = student;
index++;
}
else
{
System.out.println("Capacity exceeded! - Student cannot be added.");
}
}
//-----------------------------------------------------------------
// Adds an Individual Student to the Classroom, checking if the
// capacity of the clasroom is full.
//-----------------------------------------------------------------
public String toString()
{
StringBuffer sb = new StringBuffer
("Building: " + buildingLocation +
"\nClass room: " + roomNumber +
"\nCapacity: " + capacityStudents + "\n\n"
);
for(int i = 0; i < classRoster.length; i++)
{
if(classRoster[i] != null)
sb.append(classRoster[i].toString() + "\n");
}
return sb.toString();
}
}

The error is telling you that index is not available in the scope of the save method. You would need to do something like save.writeObject( classroom.getIndex()) in the save method, if you want to save the index.

You have declared index variable in ClassRoom class. But you are trying to use it in method actionPerformed of ClassRoomFrame class.
Since scope of index is limited to it's enclosing class, it won't be visible in other classes without using instance on ClassRoom class. And that's what compiler error states: cannot find symbol

Related

Gui and binary files

I'm currently working on a project for a class I have, where we have to create a GUI that asks for a number, then read a binary files of 10,000 customers and return the other information on the one with the customer number entered. We also have to have an error that pops up as a JOptionPane when a number outside of 1-10,000 is entered. I'm having some problems with the error message, and my professor also said we need to have a method with this signature:
private Customer getCustomer(long custNumber) throws IOException
that searches the file and returns a customer object. I'm also not sure where exactly to do that. So I started with what I already know, and here's what I have:
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class CustomerLocator extends JFrame
{
private JPanel panel;
private JLabel custNumLabel;
private JLabel custNameLabel;
private JLabel custDisLabel;
private JLabel custBalLabel;
private JLabel custPrefLabel;
private JTextField custNumField;
private JTextField custNameField;
private JTextField custDisField;
private JTextField custBalField;
private JTextField custPrefField;
private JButton findCustBut;
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 500;
public CustomerLocator()
{
setTitle("Customer Locator");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel()
{
custNumLabel = new JLabel("Enter a valid Customer Number: ");
custNumField = new JTextField(10);
custNameLabel = new JLabel("Customer Name: ");
custNameField = new JTextField(10);
custNameField.setEditable(false);
custDisLabel = new JLabel("Customer Discount: ");
custDisField = new JTextField(10);
custDisField.setEditable(false);
custBalLabel = new JLabel("Customer Balance: ");
custBalField = new JTextField(10);
custBalField.setEditable(false);
custPrefLabel = new JLabel("Preferred? ");
custPrefField = new JTextField(10);
custPrefField.setEditable(false);
findCustBut = new JButton("Find this Customer!");
panel = new JPanel();
findCustBut.addActionListener(new ListenerToFindCustomer());
panel.add(custNumLabel);
panel.add(custNumField);
panel.add(findCustBut);
panel.add(custNameLabel);
panel.add(custNameField);
panel.add(custDisLabel);
panel.add(custDisField);
panel.add(custBalLabel);
panel.add(custBalField);
panel.add(custPrefLabel);
panel.add(custPrefField);
}
private class ListenerToFindCustomer implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String numEnteredStr;
long custNumEntered;
String custName;
boolean preferred;
String preferredDisplay;
double acctBal;
String acctBalDisplay;
double discount;
String discountDisplay;
numEnteredStr = custNumField.getText();
custNumEntered = Long.parseLong(numEnteredStr);
int ct=0;
try
{
FileInputStream inStream =
new FileInputStream("c:\\cps\\CustomerObjects.dat");
// DataInputStream inputFile = new DataInputStream(inStream);
ObjectInputStream objectInputFile =
new ObjectInputStream(inStream);
while(true)
{
ct++;
Customer obj = (Customer)objectInputFile.readObject();
//System.out.println(obj.getCustName());
if (custNumEntered == obj.getCustNum())
{
custName = obj.getCustName();
acctBal = obj.getBalance();
acctBalDisplay = Double.toString(acctBal);
discount = obj.getDiscount();
discountDisplay = Double.toString(discount);
preferred = obj.getPreferred();
preferredDisplay = Boolean.toString(preferred);
custNameField.setText(custName);
custBalField.setText(acctBalDisplay);
custPrefField.setText(preferredDisplay);
custDisField.setText(discountDisplay);
if (custNameField == null)
{
JOptionPane.showMessageDialog(null, "Error");
}
}
}
}
catch (Exception ex)
{
System.out.println(ex.toString());
}
}
}
public static void main(String[] args)
{
new CustomerLocator();
}
}
So, with this, the JOptionPane doesn't show up, so my questions are
1. How do I get the error message to pop up?
2. How do I incorporate the method my professor requested?
Your code
if (custNameField == null)
{
JOptionPane.showMessageDialog(null, "Error");
}
should read
if (custName == null)
{
JOptionPane.showMessageDialog(null, "Error");
}
It should also be moved outside of the while loop.
You also need a way to break the loop once you reach the end of the file.
Everything inside and including your try { ... } catch (Exception ex) { ... } can be moved to the method that your instructor suggests.
You should also change the try-catch to have another catch (IOException ioEx) { throw ioEx; }

JComboBox Null pointer Exception. Need to get Int from box and set int as selected int from box

My program right now needs to load up two text files and I'm sorting them by string of words. JcomboxBox is supposed to allow you to select int between 1 and 4 (the size of the string to compare)
so 2 would return "I am" whereas 1 would return "I"
I'm getting null pointed exception and I have never used combo boxes before. Please help/
import java.awt.GridLayout;
import javax.swing.JFrame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JComboBox;
public class Lab8 extends JPanel
{
private JPanel text;
private JComboBox input;
private JLabel label;
private JButton load, go,go2;
private CountList<SuperString> words;
private String filename;
private int width = 400;
private int height = 600;
private TextArea textarea,textarea2;
Scanner scan;
public Lab8()
{
Integer [] select = {1,2,3,4};
JComboBox input = new JComboBox(select);
text = new JPanel(new GridLayout(1,2));
go = new JButton("Select Text File");
go2 = new JButton("Select 2nd Text File");
label = new JLabel("How many sequenced words would you like to analyze? (Must be => 1)" );
input.setSelectedIndex(0);
ButtonListener listener = new ButtonListener();
go.addActionListener(listener);
go2.addActionListener(listener);
input.addActionListener(listener);
textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea2 = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea2.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea.setPreferredSize(new Dimension(width,height));
textarea2.setPreferredSize(new Dimension(width,height));
setPreferredSize(new Dimension(900,600));
text.add(textarea);
text.add(textarea2);
add(input);
add(go);
add(go2);
add(text);
textarea.setText("No File Selected");
textarea2.setText("No File Selected");
}
public class ButtonListener implements ActionListener //makes buttons do things
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex();
if(event.getSource() == go)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","");
SuperString ss = new SuperString(storage);
// System.out.println(ss);
words.add(ss );
}
scan.close();
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
SuperString[] ss = new SuperString[words.size()];
int i=0;
for(SuperString word: words)
{
ss[i] = word;
i++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
textarea.append(" "+word+"\n");
}
}
if(event.getSource() == go2)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","");
SuperString ss = new SuperString(storage);
words.add(ss );
}
scan.close();
textarea2.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
SuperString[] ss = new SuperString[words.size()];
int i=0;
for(SuperString word: words)
{
ss[i] = word;
i++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
textarea2.append(" "+word+"\n");
}
}
}
}
public static void main(String[] arg)
{
JFrame frame = new JFrame("Lab 8");
frame.getContentPane().add(new Lab8());
frame.pack();
frame.setVisible(true);
}
}
You're re-declaring your JComboBox variable in the constructor and thus shadowing the field found in the class. By doing this the field remains null:
public class Lab8 extends JPanel
{
private JPanel text;
private JComboBox input; // this guy remains null
// .... etc ....
public Lab8()
{
Integer [] select = {1,2,3,4};
// the line below initializes a local input variable.
// this variable is visible only inside of the constructor
JComboBox input = new JComboBox(select); // ***** here ****
Don't re-declare the variable:
public class Lab8 extends JPanel
{
private JPanel text;
private JComboBox input;
// .... etc ....
public Lab8()
{
Integer [] select = {1,2,3,4};
// JComboBox input = new JComboBox(select); // ***** here ****
input = new JComboBox(select); // ***** note difference? *****

Error Writing Object's Attributes to File from GUI java

I have a problem with my GUI code that I just can't get my head around it and it concerns file writing with GUI Frames.
You see with my code below, I can Add, Remove and Display person Objects with a JTable. The problem I have is writing each attribute of each object to a file named "PersonList.txt".
The annoying thing about this is that supposing I manually put values into the file, my code is able to read each line and create person objects with the values from the files. But if I wanted to add more person objects to the file, the data in the file is overriden and the file will be empty.
My Code follows.
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class GUIstoringObjects extends JFrame implements ActionListener{
private JFrame frame;
private JButton button1, button2, button3, button4, button5, button6;
private JTextField box1, box2, box3;
private JLabel label1, label2, label3;
private JTable table;
private ArrayList<Person> pList = new ArrayList<Person>();
private ArrayList<Object[]> list;
private File f1, f2;
private PrintWriter pWriter;
private Scanner pReader;
public static void main(String[] args) throws FileNotFoundException{
// TODO Auto-generated method stub
GUIstoringObjects gui = new GUIstoringObjects();
gui.frame.setVisible(true);
}
public GUIstoringObjects()
{
initialize();
}
public void initialize()
{
frame = new JFrame("Adding and Saving Person Objects");
frame.setBounds(75,75,813,408);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
label1 = new JLabel("First Name:");
label1.setBounds(32,27,60,25);
frame.getContentPane().add(label1);
label2 = new JLabel("Last Name:");
label2.setBounds(264,27,82,25);
frame.getContentPane().add(label2);
label3 = new JLabel("Phone Number:");
label3.setBounds(504,27,89,25);
frame.getContentPane().add(label3);
box1 = new JTextField();
box1.setBounds(102,26,140,27);
frame.getContentPane().add(box1);
box2 = new JTextField();
box2.setBounds(354,26,140,27);
frame.getContentPane().add(box2);
box3 = new JTextField();
box3.setBounds(599,26,140,27);
frame.getContentPane().add(box3);
button1 = new JButton("Add Person");
button1.addActionListener(this);
button1.setBounds(120,76,122,33);
frame.getContentPane().add(button1);
button2 = new JButton("Remove Person");
button2.addActionListener(this);
button2.setBounds(120,121,122,33);
frame.getContentPane().add(button2);
button3 = new JButton("Display Person List");
button3.addActionListener(this);
button3.setBounds(252,76,154,33);
frame.getContentPane().add(button3);
button4 = new JButton("Save Person List");
button4.addActionListener(this);
button4.setBounds(416,76,154,33);
frame.getContentPane().add(button4);
button5 = new JButton("Load Person List");
button5.addActionListener(this);
button5.setBounds(416,121,154,33);
frame.getContentPane().add(button5);
button6 = new JButton("Quit Program");
button6.addActionListener(this);
button6.setBounds(599,76,140,33);
frame.getContentPane().add(button6);
table = new JTable();
table.setBounds(0,176,797,194);
frame.getContentPane().add(table);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String action = (((JButton) e.getSource()).getActionCommand());
if(action.equals("Add Person"))
{
String fName = box1.getText();
String lName = box2.getText();
String pNo = box3.getText();
Person p = new Person(fName,lName,pNo);
pList.add(p);
JOptionPane.showMessageDialog(null, fName+" has been Added!");
box1.setText("");
box2.setText("");
box3.setText("");
}
if(action.equals("Remove Person"))
{
String nameChecker = box1.getText();
for(int i = 0; i<pList.size(); i++)
{
if(nameChecker.equals(pList.get(i).getFName()))
{
pList.remove(i);
JOptionPane.showMessageDialog(null, nameChecker+" has been deleted!");
}
}
}
if(action.equals("Display Person List"))
{
list = new ArrayList<Object[]>();
for (int i = 0; i < pList.size(); i++) {
list.add(new Object[] {
pList.get(i).getFName(),
pList.get(i).getLName(),
pList.get(i).getPNo()
});
}
table.setModel(new DefaultTableModel(list.toArray(new Object[][] {}),
new String[] {"First Name", "Surname", "Phone Number"}));
}
if(action.equals("Save Person List"))
{
f1 = new File("PersonList.txt");
try {
pWriter = new PrintWriter(f1);
for(Person p: pList)
{
pWriter.println(p.getFName());
pWriter.println(p.getLName());
pWriter.println(p.getPNo());
}
JOptionPane.showMessageDialog(null, "Person List Stored in File 'PersonList.txt'");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(action.equals("Load Person List"))
{
f2 = new File("PersonList.txt");
try {
pReader = new Scanner(f2);
while (pReader.hasNext())
{
String fName = pReader.nextLine();
String lName = pReader.nextLine();
String pNo = pReader.nextLine();
Person p = new Person(fName,lName,pNo);
pList.add(p);
}
JOptionPane.showMessageDialog(null, "Person List Loaded from 'PersonList.txt'");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(action.equals("Quit Program"))
{
System.exit(0);
}
}
}
And This is my person object below
public class Person {
private String fName, lName, pNo;
public Person(String fName, String lName, String pNo)
{
setFName(fName);
setLName(lName);
setPNo(pNo);
}
public void setFName(String fName)
{
this.fName = fName;
}
public void setLName(String lName)
{
this.lName = lName;
}
public void setPNo(String pNo)
{
this.pNo = pNo;
}
public String getFName()
{
return fName;
}
public String getLName()
{
return lName;
}
public String getPNo()
{
return pNo;
}
public String toString()
{
return getFName()+" "+getLName()+" "+getPNo();
}
public void print()
{
System.out.println(toString());
}
}
As I already said above, for argument sake we had
Bill
Gates
088491038
Cristiano
Ronaldo
0048103874
The Code would be able to read from the file, but once I tried to add more people from the arraylist, it just wouldn't work, can someone help me out?
But if i wanted to add more person objects to the file, the data in the file is overriden and the file will be empty.
Whenever you create an object of PrintWriter, it clear the data of the existing file.
pWriter = new PrintWriter(f1);
You should use append mode property of FileWriter to append the data in the existing file.
FileWriter fileWriter = new FileWriter(f1, true);
^--------- Append Mode
pWriter = new PrintWriter(fileWriter, true);
^----------- Auto Flush
You should close to stream after finishing all the read/writer operation. Better use auto flush property of PrintWriter to avoid manually calling flush() method.
Handle the resources carefully using Java 7- The try-with-resources Statement or finally block.

Why is my quizzcount doubling its value

I'm having a problem with this code in that the quizzcount variable is not outputting the correct value, it doubles the value.
I found a work around by diving the quizzcount by 2 and it works but i would really like to figure out why its doubling the value.
So for example, without dividing quizzcount by 2, if the user gets 7 out of the 10 questions correct the messagedialog will display that the user got 14 out of 10 correct.
What is causing this?
Thanks guys, any help would be appreciated.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InvalidClassException;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.*;
import java.util.*;
import java.awt.* ;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.Image;
import java.lang.*;
public class MathFiles extends JFrame implements ActionListener
{
private ObjectOutputStream toFile;
private String name;
private boolean open;
private static String response;
private static int menuOption = 0;
private static int numberOfMaths = 0;
private FileInputStream fis;
private ObjectInputStream fromFile;
Math aMath = null;
private int quizcount =0;
String checkbutton = "";
private static int tracker =1;
int count = 0;
int fimage =0;
JRadioButton questA, questB, questC, questD, questE;
ButtonGroup questGroup;
JPanel questPanel;
JLabel question;
JPanel questionPanel;
JTextField resultText;
JLabel resultLabl;
JPanel resultPanel;
JButton nextButton;
JPanel quizPanel;
ImageIcon image;
JLabel imageLabl;
JPanel imagePanel;
JTextArea questionText;
JScrollPane scrollPane;
Random rand;
/** #param fileName is the desired name for the binary file. */
public MathFiles()
{
setTitle( "Math Quiz Competition" );
rand = new Random();
toFile = null;
//tracker = rand.nextInt(5)+1;
tracker = 1;
name = "Quiz"+tracker+".txt";
open = false;
//openFile(); //Use only when creating file
//writeMathsToTextFile(name);
setLayout( new FlowLayout() );
inputFile();
beginquiz();
showquestions();
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
} // end MathFiles constructor
/** Writes all Maths from a text file and writes them to a binary file.
#param fileName the text file */
public void writeMathsToTextFile(String fileName)
{
Scanner inputFile = null;
Math nextMath = null;
String question_num;
String question;
String answera;
String answerb;
String answerc;
String answerd;
String answer_cor;
String file_name;
String SENTINEL ="DONE";
try
{
inputFile = new Scanner(new File(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Text file " + fileName + " not found.");
System.exit(0);
}
Scanner keyboard = new Scanner(System.in);
System.out.print("Question number: ");
question_num = keyboard.nextLine();
while (!question_num.equalsIgnoreCase(SENTINEL))
{
System.out.print("Question: ");
question = keyboard.nextLine();
System.out.print("Answer A: ");
answera = keyboard.nextLine();
System.out.print("Answer B: ");
answerb = keyboard.nextLine();
System.out.print("Answer C: ");
answerc = keyboard.nextLine();
System.out.print("Answer D: ");
answerd = keyboard.nextLine();
fimage = rand.nextInt(30)+1;
file_name = "image"+fimage+".gif";
System.out.print(file_name);
System.out.print("Correct Answer: ");
answer_cor = keyboard.nextLine();
nextMath = new Math(question_num, question, answera, answerb,
answerc, answerd, answer_cor, file_name);
writeAnObject(nextMath);
numberOfMaths++;
System.out.print("\nQuestion number: ");
question_num = keyboard.nextLine();
} // end while
System.out.println("successfully created = " + name);
} // end readMathsFromTextFile
/** Opens the binary file for output. */
public void openFile()
{
try
{
FileOutputStream fos = new FileOutputStream(name);
toFile = new ObjectOutputStream(fos);
open = true;
}
catch (FileNotFoundException e)
{
System.out.println("Cannot find, create, or open the file " + name);
System.out.println(e.getMessage());
open = false;
}
catch (IOException e)
{
System.out.println("Error opening the file " + name);
System.out.println(e.getMessage());
open = false;
}
//System.out.println("successfully opened = " + name);
} // end openFile
/** Writes the given object to the binary file. */
public void writeAnObject(Serializable anObject)
{
try
{
if (open)
toFile.writeObject(anObject);
}
catch (InvalidClassException e)
{
System.out.println("Serialization problem in writeAnObject.");
System.out.println(e.getMessage());
System.exit(0);
}
catch (IOException e)
{
System.out.println("Error writing the file " + name);
System.out.println(e.getMessage());
System.exit(0);
}
} // end writeAnObject
public void result()
{
System.out.println("Your score is");
}
public void inputFile()
{
try
{
fromFile = new ObjectInputStream(new FileInputStream(name));
}
catch(StreamCorruptedException e)
{
System.out.println("Error in input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error reading input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
} // end displayFile
/** Closes the binary file. */
public void closeFile()
{
System.out.println("closed name = " + name);
try
{
toFile.close();
open = false;
}
catch (IOException e)
{
System.out.println("Error closing the file " + name);
System.out.println(e.getMessage());
System.exit(0);
}
} // end closeFile
/** #return the fileís name as a string */
public String getName()
{
return name;
} // end getName
/** #return true if the file is open */
public boolean isOpen()
{
return open;
} // end isOpen
public void beginquiz()
{
try
{
aMath = (Math)fromFile.readObject();
}
catch (ClassNotFoundException e)
{
System.out.println("The class Math is not found.");
System.out.println(e.getMessage());
System.exit(0);
}
catch(StreamCorruptedException e)
{
System.out.println("Error in input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error reading input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
}
void showquestions()
{
//question group
/*question = new JLabel();
question.setText(aMath.getquestion());
question.setFont(new Font("Arial", Font.BOLD, 20));
question.setForeground(Color.BLUE);
questionPanel = new JPanel();
questionPanel.add( question );*/
questionText = new JTextArea(5,20);
questionText.setWrapStyleWord(true);
questionText.setLineWrap(true);
questionText.setText(aMath.getquestion());
questionText.setFont(new Font("Arial", Font.BOLD, 20));
questionText.setForeground(Color.BLUE);
questionPanel = new JPanel();
questionPanel.setLayout(new BoxLayout(questionPanel, BoxLayout.PAGE_AXIS));
questionPanel.add( questionText );
// quest group
questA = new JRadioButton(aMath.getanswera(), false );
questB = new JRadioButton(aMath.getanswerb(), false );
questC = new JRadioButton(aMath.getanswerc(), false );
questD = new JRadioButton(aMath.getanswerd(), false );
questGroup = new ButtonGroup();
questGroup.add( questA );
questGroup.add( questB );
questGroup.add( questC );
questGroup.add( questD );
questPanel = new JPanel();
questPanel.setLayout( new BoxLayout( questPanel, BoxLayout.Y_AXIS ) );
questPanel.add( new JLabel("Choose the Correct Answer") );
questPanel.add( questA );
questPanel.add( questB );
questPanel.add( questC );
questPanel.add( questD );
// result panel
//resultText = new JTextField(20);
//resultText.setEditable( false );
//resultLabl = new JLabel("Result");
//resultPanel = new JPanel();
//resultPanel.add( resultLabl );
//resultPanel.add( resultText );
//button
nextButton = new JButton("Next");
quizPanel = new JPanel();
quizPanel.add(nextButton);
//Image image1 = new ImageIcon("image/image1.gif").getImage();
image = new ImageIcon("image1.gif");
imageLabl=new JLabel(image);
imagePanel = new JPanel();
imagePanel.add(imageLabl);
// frame: use default layout manager
add( imagePanel);
add( questionPanel);
add( questPanel);
//add( resultPanel);
questA.setActionCommand(aMath.getanswera());
questB.setActionCommand(aMath.getanswerb());
questC.setActionCommand(aMath.getanswerc());
questD.setActionCommand(aMath.getanswerd());
questA.addActionListener(this);
questB.addActionListener(this);
questC.addActionListener(this);
questD.addActionListener(this);
nextButton.setActionCommand( "next" ); // set the command
// register the buttonDemo frame
// as the listener for both Buttons.
nextButton.addActionListener( this );
add(quizPanel);
}
public void actionPerformed( ActionEvent evt)
{
//evt.getActionCommand() = aMath.getanswer_cor();
if (questA.isSelected()&&
aMath.getanswera().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if (questB.isSelected()&&
aMath.getanswerb().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if (questC.isSelected()&&
aMath.getanswerc().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if (questD.isSelected()&&
aMath.getanswerd().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if(questA.isSelected() || questB.isSelected() || questC.isSelected() || questD.isSelected())
if ( evt.getActionCommand().equals( "next" ))
{
try
{
aMath = (Math)fromFile.readObject();
questionText.setText(aMath.getquestion());
questA.setText(aMath.getanswera());
questB.setText(aMath.getanswerb());
questC.setText(aMath.getanswerc());
questD.setText(aMath.getanswerd());
imageLabl.setIcon(new ImageIcon(aMath.getfile()));
questGroup.clearSelection();
repaint();
}
catch (ClassNotFoundException e)
{
System.out.println("The class Math is not found.");
System.out.println(e.getMessage());
System.exit(0);
}
catch(StreamCorruptedException e)
{
System.out.println("Error in input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
catch(IOException e)
{
if (count<=0)
count = 0;
else
count--;
JOptionPane.showMessageDialog(null,"Your score is "+quizcount/2 +" out of 10");
try{
Thread.sleep(2000);
System.exit(0);
}catch (InterruptedException em) { }
}
}
}
public static void main ( String[] args )
{
MathFiles mat = new MathFiles();
mat.setSize( 450, 550 );
mat.setLocationRelativeTo(null);
mat.setResizable( false );
mat.setVisible( true );
}
} // end MathFiles
class Math implements java.io.Serializable
{
private String question_num;
private String question;
private String answera;
private String answerb;
private String answerc;
private String answerd;
private String answer_cor;
private String file_name;
public Math(String quesno, String quest, String ansa, String ansb, String ansc,
String ansd, String ans_cor, String file)
{
question_num = quesno;
question = quest;
answera = ansa;
answerb = ansb;
answerc = ansc;
answerd = ansd;
answer_cor = ans_cor;
file_name = file;
}
public void setquestion(String lName)
{
question = lName;
} // end setquestion
public void setquestion_num(String fName)
{
question_num = fName;
} // end setquestion_num
public void setanswera(String add)
{
answera = add;
} // end setanswera
public void setanswerb(String cty)
{
answerb = cty;
} // end setanswerb
public void setanswerc(String st)
{
answerc = st;
} // end setanswerc
public void setanswerd(String z)
{
answerd = z;
} // end setanswerd
public void setanswer_cor(String phn)
{
answer_cor = phn;
} // end setanswer_corr
public String getquestion_num()
{
return question_num;
} // end getquestion_num
/** #return the question */
public String getquestion()
{
return question;
} // end getquestion
/** #return the answera*/
public String getanswera()
{
return answera;
} // end getanswera
/** #return the answerb */
public String getanswerb()
{
return answerb;
} // end getanswerb
public String getanswerc()
{
return answerc;
} // end getanswerc
public String getanswerd()
{
return answerd;
} // end getanswerd
public String getanswer_cor()
{
return answer_cor;
} // end getanswer_corr
public String getfile()
{
return file_name;
} // end getanswer_corr
/** #return the Math information */
public String toString()
{
String myMath = getquestion_num() + " " + getquestion() + "\n";
myMath += getanswera() + "\n";
myMath += getanswerb() + " " + getanswerc() + " " + getanswerd() + "\n";
myMath += getanswer_cor() + "\n";
myMath += getfile() + "\n";
return myMath;
} // end toString
} // end Math
It looks like your problem is that you've registered ActionListeners on the radio buttons. This means the event fires when you select an answer as well as clicking the 'next' button. With that in mind it should be obvious why your score is doubling itself.
As far as I can tell you don't need ActionListeners for the radio buttons. You should only be checking the answer when the user has indicated they are done with their selection. That the score is exactly doubling itself also suggests that you basically haven't tested the program besides naively selecting a radio button and clicking 'next'. Before commenting out the lines where you add the listeners to the radio buttons, try changing your answer. Open the program, select the correct answer, then select an incorrect answer, then select the correct answer again and click 'next'. See what happens.
This kind of error can also be easily found with a debugger. Just insert a breakpoint inside actionPerformed and it will be obvious it's being called by more than one action.

reading from file and showing in textarea java

I have the following code which reads names from the test file, which works fine
public class Names {
Scanner scan;
static String Firstname;
static String Surname;
static String Fullname;
public void OpenFile()
{
try
{
scan = new Scanner(new File("test.txt"));
System.out.println("File found!");
}
catch(Exception e)
{
System.out.println("File not found");
}
}
public void ReadFile()
{
while(scan.hasNext())
{
Firstname = scan.next();
Surname = scan.next();
Fullname = Firstname + " " + Surname;
System.out.println(Fullname);
}
}
public void CloseFile()
{
scan.close();
}
}
Then I have this main class which calls the Names class. it works fine apart from it only shows the last names from the test file.
public class NameSwing implements ActionListener {
private JTextArea tf = new JTextArea(20,20);
private JFrame f = new JFrame("names");
private JButton b = new JButton("view");
static String fullName;
public NameSwing(){
f.add(new JLabel("Name"));
tf.setEditable(true);
f.add(tf);
b.addActionListener(this);
f.add(b);
f.setLayout(new FlowLayout());
f.setSize(300,100);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
tf.setText(fullName);
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
NameSwing nameSwing = new NameSwing();
Names t = new Names();
t.OpenFile();
t.ReadFile();
t.CloseFile();
fullName = Names.Fullname;
}
}
This is the test file content.
Nick Harris
Olly Dean
Emma Sammons
Henry Blackwell
How can I get the textarea to show all of the names from the reader, and not just the last name?
Throw out your Names class as it isn't very helpful and over-uses static fields to its detriment. The best solution in my mind is to:
Create a File that holds your text file
Create a FileReader object with this File
Use this to create a BufferedReader object
call the JTextArea's read(...) method passing in the BufferedReader
And your done.
i.e., in actionPerformed:
BufferedRead buffReader = null;
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
buffReader = new BufferedReader(fileReader);
tf.read(buffReader, "file.txt");
} catch (WhateverExceptionsNeedToBeCaught e) {
e.printStackTrace();
} finally {
// close your BufferedReader
}
You are using too many static fields for no good reasons. Always use
static fields if you intend to make your class a Factory Class, which
in this case is not appropriate.
You are breaking the fundamental rule of encapsulation, by providing each method with a public Access Specifier, without the need of it.
Instead of calling setSize(), you can simply use pack(), which can determine the dimensions of the Container, in a much better way, than the arbitrary values you had specified.
Please do read about Concurrency in Swing, since appears to me your knowledge is a bit short on that front.
Please do learn Java Naming Conventions.
Moreover, you can simply use a StringBuilder Class, to do this thingy for you. Have a look at the modified code of yours. Do ask anything that is beyond your grasp, I be happy to help on that.
MODIFIED CODE :
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NameSwing implements ActionListener {
private Names t;
private JTextArea tf = new JTextArea(20,20);
private JFrame f = new JFrame("names");
private JButton b = new JButton("view");
public NameSwing(){
performFileRelatedTask();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JScrollPane scroller = new JScrollPane();
scroller.setBorder(BorderFactory.createLineBorder(Color.BLUE.darker(), 5));
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout(5, 5));
centerPanel.add(new JLabel("Name", JLabel.CENTER), BorderLayout.PAGE_START);
tf.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
tf.setEditable(true);
centerPanel.add(tf, BorderLayout.CENTER);
scroller.setViewportView(centerPanel);
JPanel footerPanel = new JPanel();
b.addActionListener(this);
footerPanel.add(b);
contentPane.add(scroller, BorderLayout.CENTER);
contentPane.add(footerPanel, BorderLayout.PAGE_END);
f.setContentPane(contentPane);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
private void performFileRelatedTask()
{
t = new Names();
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
tf.setText(t.getFullNames().toString());
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new NameSwing();
}
});
}
}
class Names {
private Scanner scan;
private String firstname;
private String surname;
private StringBuilder fullnames;
public Names()
{
fullnames = new StringBuilder();
openFile();
readFile();
closeFile();
}
public StringBuilder getFullNames()
{
return fullnames;
}
private void openFile()
{
try
{
scan = new Scanner(new File("test.txt"));
System.out.println("File found!");
}
catch(Exception e)
{
System.out.println("File not found");
}
}
private void readFile()
{
while(scan.hasNext())
{
firstname = scan.next();
surname = scan.next();
fullnames.append(firstname + " " + surname + "\n");
}
}
private void closeFile()
{
scan.close();
}
}
The problem is at line
Fullname = Firstname + " " + Surname;.
Make it
Fullname += Firstname + " " + Surname; + "\n"
You problem is solved :)
Here you need the change
while(scan.hasNext())
{
Firstname = scan.next();
Surname = scan.next();
//Assigning each time instead of append
Fullname = Firstname + " " + Surname;
}
Here is complete fix:
public class NameSwing implements ActionListener {
private JTextArea textArea = new JTextArea(20, 20);
private JFrame frame = new JFrame("Names");
private JButton btnView = new JButton("View");
private Scanner scanner;
private String firstName;
private String surName;
private String fullName;
public NameSwing() {
frame.add(new JLabel("Name"));
textArea.setEditable(true);
frame.add(textArea);
btnView.addActionListener(this);
frame.add(btnView);
frame.setLayout(new FlowLayout());
frame.setSize(300, 100);
frame.setVisible(true);
}
public void OpenFile() {
try {
scanner = new Scanner(new File("test.txt"));
System.out.println("File found!");
} catch (Exception e) {
System.out.println("File not found");
}
}
public void ReadFile() {
while (scanner.hasNext()) {
firstName = scanner.next();
surName = scanner.next();
// assign first time
if( fullName == null ) {
fullName = firstName + " " + surName;
} else {
fullName = fullName + "\n" + firstName + " " + surName;
}
System.out.println(fullName);
}
}
public void CloseFile() {
scanner.close();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnView) {
textArea.setText(fullName);
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
NameSwing nameSwing = new NameSwing();
nameSwing.OpenFile();
nameSwing.ReadFile();
nameSwing.CloseFile();
}
}

Categories