Why is my quizzcount doubling its value - java

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.

Related

Passing data between class and running thread

Using code examples from stockoverflow I made a class to receive data over TCP/IP.
Class code below. It is working OK and I do receive data from other PC.
recPositions Map is build correctly. After transmission is finished I can display all data I received using getRecPositions()
This thread is started in other class that build simple HMI screen.
Thread runs and display data received from other PC.
Problem is I would like to access same data in MainWindow class (HMI)
but it always show that nothing was received.
Class MainWindow below (not all of it since there is lots of useless pushbuttons and so on)
At the very bottom I have pushbutton that should display how many positions were recorded (elements in Map) but it always show 0.
Code snippet from push button update.
System.out.println(dataServer.getRecPositions().size())
So at some point I am doing something wrong.
Thread starts and runs and I can see incoming positions. At some point after I received "EOT" I display received positions stored in Map. But when I tried to display the size of Map in main window it always show 0.
/*
* Simple data server for receiving string data from IIWA robot
*/
public class SimpleDataServer implements Runnable {
Map<Integer, String> recPositions = new HashMap<>();
Server1Connection oneconnection;
ServerSocket echoServer = null;
Socket clientSocket = null;
int port;
boolean reset = false;
public SimpleDataServer( int port ) {
this.port = port;
}
public void stopServer() {
System.out.println( "Simple data server stopped" );
}
public void startServer() {
// Try to open a server socket on the given port
// Note that we can't choose a port less than 1024 if we are not
// privileged users (root)
try {
echoServer = new ServerSocket(port);
}
catch (IOException e) {
System.out.println(e);
}
System.out.println( "Waiting for connections. Only one connection is allowed." );
// Create a socket object from the ServerSocket to listen and accept connections.
// Use Server1Connection to process the connection.
while ( true ) {
try {
clientSocket = echoServer.accept();
oneconnection = new Server1Connection(clientSocket, this);
oneconnection.run();
if(isReset()) {
setReset(false);
System.out.println("Recording finished");
System.out.println("DEBUG:" + this.getRecPositions().size() + " positions recorded: " + this.getRecPositions());
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
#Override
public void run() {
int port = this.port;
SimpleDataServer server = new SimpleDataServer( port );
server.startServer();
}
public Map<Integer, String> getRecPositions() {
return recPositions;
}
public void setRecPositions(Map<Integer, String> recPositions) {
this.recPositions = recPositions;
}
public boolean isReset() {
return reset;
}
public void setReset(boolean reset) {
this.reset = reset;
}
}
class Server1Connection {
BufferedReader is;
PrintStream os;
Socket clientSocket;
SimpleDataServer server;
public Server1Connection(Socket clientSocket, SimpleDataServer server) {
this.clientSocket = clientSocket;
this.server = server;
System.out.println( "Connection established with: " + clientSocket );
try {
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public Map<Integer, String> getPositions() {
return server.getRecPositions();
}
public void run() {
String line; //whole line recevied
String segment = null; //single segment from line using comma delimiter
List<String> stringsList;
try {
boolean serverStop = false;
//server runs here
while (true)
{
line = is.readLine();
System.out.println( "DEBUG Server Received: " + line );
//check is string is not empty
if (line.equals(null)) {
System.err.println("Empty String received");
break;
}
stringsList = new ArrayList<String>(Arrays.asList(line.split(";")));
if (!stringsList.isEmpty()) {
stringsList.set(0, stringsList.get(0).replaceAll("\\s+",""));
stringsList.set((stringsList.size()-1), stringsList.get(stringsList.size()-1).replaceAll("\\s+",""));
String lastSegment = stringsList.get((stringsList.size()-1));
if (lastSegment.equals("ETX") || lastSegment.equals("EOT")) {
switch (stringsList.get(0)) {
case "MSG":
stringsList.remove(0);
stringsList.remove(stringsList.size()-1);
System.out.println("Message: " + stringsList.toString());
break;
case "POS":
// for (String blah : stringsList) {
// System.out.println("DEBUG" + blah);
// }
iiwaPosfromString iiwaPos = new iiwaPosfromString(stringsList.get(1), stringsList.get(2));
System.out.println("DEBUG Position number: " + iiwaPos.posNum + " ; " + iiwaPos.toString());
if (iiwaPos.getPosNum() > 0) {
server.getRecPositions().put(iiwaPos.getPosNum(), iiwaPos.toString());
}
break;
case "EOT":
case "EXT":
//ignore handled later
break;
default:
System.err.println("Ausgebombt!");
break;
}
}
//ETX End Of Text - dump data to screen - close current connection
if(lastSegment.equals("ETX")) {
System.out.println("End of Text received");
break;
}
//EOT End Of Transmission - shuts down server
if(lastSegment.equals("EOT")) {
System.out.println("End of Transmission received");
serverStop = true;
server.setReset(true);
break;
}
System.err.println("No correct end string!");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
} else {
System.out.println("Empty String received");
break;
}
}
System.out.println( "Connection closed." );
is.close();
os.close();
clientSocket.close();
if ( serverStop ) server.stopServer();
} catch (IOException e) {
System.out.println(e);
}
}
public class iiwaPosfromString {
private double posX;
private double posY;
private double posZ;
private double posA;
private double posB;
private double posC;
private int posNum;
public iiwaPosfromString(String posNum, String posString) {
List <String>stringsList = new ArrayList<String>(Arrays.asList(posString.split(" ")));
for (int i = 0; i < stringsList.size(); i++) {
String newElement = stringsList.get(i);
newElement = newElement.replaceAll("[^\\d.]", "");
stringsList.set(i, newElement);
}
this.setPosNum(Integer.parseInt(posNum));
this.setPosX(Double.parseDouble(stringsList.get(1)));
this.setPosY(Double.parseDouble(stringsList.get(2)));
this.setPosZ(Double.parseDouble(stringsList.get(3)));
//this is stupid and don't do that
//from right to left, string to double, change radians to degrees, format to two decimals(string), string to double again
this.setPosA(Double.parseDouble(String.format("%.2f",(Math.toDegrees(Double.parseDouble(stringsList.get(4)))))));
this.setPosB(Double.parseDouble(String.format("%.2f",(Math.toDegrees(Double.parseDouble(stringsList.get(4)))))));
this.setPosC(Double.parseDouble(String.format("%.2f",(Math.toDegrees(Double.parseDouble(stringsList.get(4)))))));
}
public double getPosX() {
return posX;
}
public void setPosX(double posX) {
this.posX = posX;
}
public double getPosY() {
return posY;
}
public void setPosY(double posY) {
this.posY = posY;
}
public double getPosZ() {
return posZ;
}
public void setPosZ(double posZ) {
this.posZ = posZ;
}
public double getPosA() {
return posA;
}
public void setPosA(double posA) {
this.posA = posA;
}
public double getPosB() {
return posB;
}
public void setPosB(double posB) {
this.posB = posB;
}
public double getPosC() {
return posC;
}
public void setPosC(double posC) {
this.posC = posC;
}
#Override
public String toString() {
return "<" +
"X: " + getPosX() + ", " +
"Y: " + getPosY() + ", " +
"Z: " + getPosZ() + ", " +
"A: " + getPosA() + ", " +
"B: " + getPosB() + ", " +
"C: " + getPosC() +
">";
}
public int getPosNum() {
return posNum;
}
public void setPosNum(int posNum) {
this.posNum = posNum;
}
}
}
public class MainWindow {
private Thread dataServerThread;
private SimpleDataServer dataServer;
private XmlParserGlobalVarsRD globalVarPLC, globalVarKRC;
private JFrame frame;
private JTextField simpleWorkingDirStiffness;
private JTextField simpleWorkingDirAdditionalForce;
private JTextField simpleTravelDistance;
private JTextField simpleTravelVelocity;
private JTextField simpleTotalTime;
private JTextField simpleTheoreticalDepth;
private JTextField simpleZProgress;
private JComboBox oscillationMode;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
final JCheckBox emptyScanCycle = new JCheckBox("VRSI Scan Cycle Plain Fasteners");
//set data server thread and start it
dataServer = new SimpleDataServer(30008);
dataServerThread = new Thread(dataServer);
dataServerThread.setDaemon(true);
dataServerThread.start();
...
JButton pbUpdate = new JButton("UPDATE");
pbUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println(dataServer.getRecPositions().size())
}
});
pbUpdate.setBounds(210, 176, 90, 28);
frame.getContentPane().add(pbUpdate);
}
I believe the issue is in your SimpleDataServer.run method. You are creating a separate instance of SimpleDataServer from WITHIN your SimpleDataServer instance. Therefore, all of the communication is taking place in an object that your MainWindow has no direct reference to. I believe your SimpleDataServer.run method should look like this:
#Override
public void run() {
this.startServer();
}

Date and time not updating

My program uses dates to check when an engineer has visited a machine. The only problem with this is that the date does not remain up to date. The date and time that the machine displays is the exact time that the machine was started. Not when the button was clicked. Any assistance would be helpful.
Code:
package com.perisic.beds.peripherals;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import org.apache.xmlrpc.WebServer;
import org.apache.xmlrpc.XmlRpcClient;
import com.perisic.beds.machine.CustomerPanel;
/**
* A Simple Graphical User Interface for the Recycling Machine.
* #author Group M
*
*/
public class RecyclingGUI extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -5772727482959492839L;
//CustomerPanel myCustomerPanel = new CustomerPanel(new Display());
Display myDisplay = new Display();
ReceiptPrinter printer = new ReceiptPrinter();
ReceiptPrinter printer2 = new ReceiptPrinter();
CustomerPanel myCustomerPanel = new CustomerPanel(myDisplay);
CustomerPanel machineScreen = new CustomerPanel(printer2);
CustomerPanel theConsole = new CustomerPanel(printer);
CustomerPanel thePanel = new CustomerPanel(myDisplay);
private String storedPasswd = "123"; // needs some thinking with encryption etc
private String storedCookie = null; // some random string to be used for authentication
private String sessionCookie = "";
private int numberOfVisits;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = new Date();
Date storedDate = date;
/**
* Web service to provide number of items in the machine.
* #param myCookie
* #return
*/
public int numberOfItems(String myCookie) {
if( storedCookie == null ) {
return -1;
} else if( myCookie.equals(storedCookie)) {
return myCustomerPanel.getNumberOfItems();
}
else {
return -1;
}
}
public int empty (String myCookie){
if(storedCookie == null){
return -1;
}else if(myCookie.equals(storedCookie)){
return myCustomerPanel.empty();
}else{
return -1;
}
}
/**
* Web service to authenticate the user with proper password.
* #param passwd
* #return
*/
public String login(String passwd) {
if( passwd.equals(storedPasswd)) {
storedCookie = "MC"+Math.random();
System.out.println("Engineer has logged in on: " + dateFormat.format(date));
storedDate = date;
numberOfVisits ++;
return storedCookie;
} else {
return "Incorrect Password";
}
}
public String visits(String myCookie){
if(numberOfVisits == 0){
return "Engineer has not visited this machine";
}else if(myCookie.equals(storedCookie)){
for(int i = 0; i < numberOfVisits; i++){
System.out.println("Engineer has visited on these dates: " + dateFormat.format(storedDate));
}
return storedCookie;
}else{
return "Engineer has visited on these date: " + dateFormat.format(storedDate);
}
}
/**
* Web service to logout from the system.
*/
public String logout(String myCookie ) {
if( storedCookie == null ) {
return "(no cookie set)";
} else if( myCookie.equals(storedCookie)) {
System.out.println("Engineer has logged out on: " + dateFormat.format(date));
storedCookie = null;
return "cookie deleted: OK";
}
else {
return "could not delete anything; authentication missing";
}
}
public static final String SUN_JAVA_COMMAND = "sun.java.command";
//This method is used to restart the application.
//It uses code that basically stores all of the necessary code it will need to successfully restart the application.
//Rather then just using System.exit(0) which, by itself would simply close the entire application.
//Using dispose() and new RecyclingGUI also doesn't work as it does not reload the JPanel upon restarting.
public void restartApplication(Runnable runBeforeRestart) throws IOException{
try {
String java = System.getProperty("java.home") + "/bin/java";
List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
StringBuffer vmArgsOneLine = new StringBuffer();
for (String arg : vmArguments) {
if (!arg.contains("-agentlib")) {
vmArgsOneLine.append(arg);
vmArgsOneLine.append(" ");
}
}
final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine);
String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" ");
if (mainCommand[0].endsWith(".jar")) {
cmd.append("-jar " + new File(mainCommand[0]).getPath());
} else {
cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);
}
for (int i = 1; i < mainCommand.length; i++) {
cmd.append(" ");
cmd.append(mainCommand[i]);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
Runtime.getRuntime().exec(cmd.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (runBeforeRestart!= null) {
runBeforeRestart.run();
}
System.exit(0);
} catch (Exception e) {
throw new IOException("Error while trying to restart the machine", e);
}
}
public void actionPerformed(ActionEvent e) {
/* Differentiate between the different buttons pressed and initiate appropriate
* actions
*/
try{
XmlRpcClient server = new XmlRpcClient("http://localhost:100");
//This code allows the engineer to login to the machine and when they do it reveals new buttons that only the engineer can use.
if (e.getSource().equals(login)){
String message;
boolean loginSuccess = false;
while(loginSuccess == false && (message = JOptionPane.showInputDialog("Login please"))!= null){
Vector parms1 = new Vector();
parms1.add(message);
Object result3 = server.execute("recycling.login", parms1);
String loginRequest = result3.toString();
if(loginRequest.equals("Wrong password")){
System.out.println("Wrong Password. Try Again!");
} else {
sessionCookie = loginRequest;
System.out.println("You are now logged in");
login.setVisible(false);
logout.setVisible(true);
reset.setVisible(true);
empty.setVisible(true);
items.setVisible(true);
loginSuccess = true;
}
}
}else if(e.getSource().equals(visits)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.visits", params);
System.out.println(result);
//This logs the engineer out of the machine and hides some of the buttons
}else if( e.getSource().equals(logout)) {
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.logout", params );
System.out.println("Logout: "+result);
reset.setVisible(false);
empty.setVisible(false);
items.setVisible(false);
login.setVisible(true);
logout.setVisible(false);
//This code tells the engineer how many items are currently in the machine.
}else if(e.getSource().equals(items)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.numberOfItems", params );
int resultInt = new Integer(result.toString());
if( resultInt == -1 ) {
System.out.println("Sorry no authentication there.");
} else {
System.out.println("There are "+resultInt+" items in the machine");
}
//This if statement empties all items that have been put into the machine thus far and sets the item number property to 0
}else if(e.getSource().equals(empty)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.empty", params);
int resultInt = new Integer(result.toString());
if(resultInt == -1){
System.out.println("Sorry no authentication there.");
}else{
System.out.println("The machine has been emptied.");
}
//This method coded above is called here.
}else if(e.getSource().equals(reset)){
restartApplication(null);
}else if(e.getSource().equals(slot1)) {
myCustomerPanel.itemReceived(1);
}else if(e.getSource().equals(slot2)) {
myCustomerPanel.itemReceived(2);
}else if(e.getSource().equals(slot3)) {
myCustomerPanel.itemReceived(3);
}else if(e.getSource().equals(slot4)) {
myCustomerPanel.itemReceived(4);
}else if(e.getSource().equals(receipt)) {
myCustomerPanel.printReceipt();
}else if(e.getSource().equals(display)) {
this.myCustomerPanel = thePanel;
}else if(e.getSource().equals(console)){
myCustomerPanel = theConsole;
}else if(e.getSource().equals(onScreen)){
//once this button is clicked all output is linked back into the GUI
myCustomerPanel = machineScreen;
redirectSystemStreams();
}
}catch (Exception exception) {
System.err.println("JavaClient: " + exception);
}
// System.out.println("Received: e.getActionCommand()="+e.getActionCommand()+
// " e.getSource()="+e.getSource().toString() );
}
//This Adds the controls (buttons) to the GUI
JButton slot1 = new JButton("Can");
JButton slot2 = new JButton("Bottle");
JButton slot3 = new JButton("Crate");
JButton slot4 = new JButton("Paper Bag");
JButton receipt = new JButton("Print Receipt");
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JButton reset = new JButton("Reset");
JButton empty = new JButton("Empty");
JButton items = new JButton("#Items");
JButton visits = new JButton("visits");
JTextArea textArea = new JTextArea(20,30);
JScrollPane scroll = new JScrollPane(textArea);
JButton display = new JButton("Print to Display");
JButton console = new JButton("Print to GUI/Console");
JButton onScreen = new JButton("Show On Screen");
/** This creates the GUI using the controls above and
* adds the actions and listeners. this area of code also
* Contains the panel settings for size and some behaviours.
*/
public RecyclingGUI() {
super();
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(slot1);
panel.add(slot2);
panel.add(slot3);
panel.add(slot4);
slot1.addActionListener(this);
slot2.addActionListener(this);
slot3.addActionListener(this);
slot4.addActionListener(this);
panel.add(receipt);
receipt.addActionListener(this);
panel.add(display);
display.addActionListener(this);
panel.add(console);
console.addActionListener(this);
panel.add(onScreen);
onScreen.addActionListener(this);
/**Text Area controls for size, font style, font size
* the text area also has a scroll bar just in case the user enters
* a large number of items
*/
panel.add(scroll);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setFont(new Font("Ariel",Font.PLAIN, 14));
scroll.setPreferredSize(new Dimension(450, 450));
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(login);
login.addActionListener(this);
panel.add(logout);
logout.setVisible(false);
logout.addActionListener(this);
panel.add(reset);
reset.setVisible(false);
reset.addActionListener(this);
panel.add(items);
items.setVisible(false);
items.addActionListener(this);
panel.add(empty);
empty.setVisible(false);
empty.addActionListener(this);
panel.add(visits);
visits.addActionListener(this);
getContentPane().add(panel);
panel.repaint();
}
public static void main(String [] args ) {
RecyclingGUI myGUI = new RecyclingGUI();
myGUI.setVisible(true);
try {
System.out.println("Starting the Recycling Server...");
WebServer server = new WebServer(100);
server.addHandler("recycling", myGUI);
server.start();
} catch (Exception exception) {
System.err.println("JavaServer: " + exception);
}
}
/** This is the code that redirects where the code is displayed
* from the console to the textArea of the GUI. it does this by
* creating a new set of output streams (for text and errors) which
* are set as default when the redirectSystemStream method is called.
* (from a previous piece of work i did in my FDg, source = from a tutorial)
*/
public void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
}
public void redirectSystemStreams() {
OutputStream out = new OutputStream() {
#Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
public void print(String str) {
System.out.println(str);
}
}
You never re-initialize date, you're just updating storedDate with the existing date in login. You could change this line in login
storedDate = date;
to
storedDate = new Date();
And then (I think) you can remove date.
Date does not keep a persistent current time. Date is backed by a long that is set when the Date is instantiated and is never changed.
You can either make a new Date() in your logon method, so it would be created when the user logs on, or just use System.currentTimeMillis() to get the current time as a long.

How to display each instance of a user logging into a server with a button click?

I have been tasked with creating a recycling machine server which a engineer can log into empty, reset, etc. Each time the engineer logs into a machine it creates a string that says "Engineer has logged in on this (date)". I need to create a JButton that prints out each instance of this string being written.
So when pressed it prints out something like this:
"Engineer visited this machine on 01/01/2016"
"Engineer visited this machine on 02/01/2016"
"Engineer visited this machine on 05/04/2016"
The log in function is working and uses stored cookies to figure out if the user has input the correct information. I am however unable to figure out how to print out this summary of visits via one button click. Any help would be appreciated.
Code:
package com.perisic.beds.peripherals;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import org.apache.xmlrpc.WebServer;
import org.apache.xmlrpc.XmlRpcClient;
import com.perisic.beds.machine.CustomerPanel;
/**
* A Simple Graphical User Interface for the Recycling Machine.
* #author Group M
*
*/
public class RecyclingGUI extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -5772727482959492839L;
//CustomerPanel myCustomerPanel = new CustomerPanel(new Display());
Display myDisplay = new Display();
ReceiptPrinter printer = new ReceiptPrinter();
ReceiptPrinter printer2 = new ReceiptPrinter();
CustomerPanel myCustomerPanel = new CustomerPanel(myDisplay);
CustomerPanel machineScreen = new CustomerPanel(printer2);
CustomerPanel theConsole = new CustomerPanel(printer);
CustomerPanel thePanel = new CustomerPanel(myDisplay);
private String storedPasswd = "123"; // needs some thinking with encryption etc
private String storedCookie = null; // some random string to be used for authentication
private String sessionCookie = "";
private int numberOfVisits = 0;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = new Date();
Date storedDate = new Date();
/**
* Web service to provide number of items in the machine.
* #param myCookie
* #return
*/
public int numberOfItems(String myCookie) {
if( storedCookie == null ) {
return -1;
} else if( myCookie.equals(storedCookie)) {
return myCustomerPanel.getNumberOfItems();
}
else {
return -1;
}
}
public int empty (String myCookie){
if(storedCookie == null){
return -1;
}else if(myCookie.equals(storedCookie)){
return myCustomerPanel.empty();
}else{
return -1;
}
}
/**
* Web service to authenticate the user with proper password.
* #param passwd
* #return
*/
public String login(String passwd) {
if( passwd.equals(storedPasswd)) {
storedCookie = "MC"+Math.random();
System.out.println("Engineer has logged in on: " + dateFormat.format(date));
storedDate = date;
numberOfVisits ++;
return storedCookie;
} else {
return "Incorrect Password";
}
}
public String visits(String myCookie){
if(numberOfVisits == 0){
return "Engineer has not visited this machine";
}else if(myCookie.equals(storedCookie)){
for(int i = 0; i < numberOfVisits; i++){
System.out.println("Engineer has visited on these dates: " + dateFormat.format(storedDate));
}
return storedCookie;
}else{
return "Engineer has visited on these date: " + dateFormat.format(storedDate);
}
}
/**
* Web service to logout from the system.
*/
public String logout(String myCookie ) {
if( storedCookie == null ) {
return "(no cookie set)";
} else if( myCookie.equals(storedCookie)) {
System.out.println("Engineer has logged out on: " + dateFormat.format(date));
storedCookie = null;
return "cookie deleted: OK";
}
else {
return "could not delete anything; authentication missing";
}
}
public static final String SUN_JAVA_COMMAND = "sun.java.command";
//This method is used to restart the application.
//It uses code that basically stores all of the necessary code it will need to successfully restart the application.
//Rather then just using System.exit(0) which, by itself would simply close the entire application.
//Using dispose() and new RecyclingGUI also doesn't work as it does not reload the JPanel upon restarting.
public void restartApplication(Runnable runBeforeRestart) throws IOException{
try {
String java = System.getProperty("java.home") + "/bin/java";
List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
StringBuffer vmArgsOneLine = new StringBuffer();
for (String arg : vmArguments) {
if (!arg.contains("-agentlib")) {
vmArgsOneLine.append(arg);
vmArgsOneLine.append(" ");
}
}
final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine);
String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" ");
if (mainCommand[0].endsWith(".jar")) {
cmd.append("-jar " + new File(mainCommand[0]).getPath());
} else {
cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);
}
for (int i = 1; i < mainCommand.length; i++) {
cmd.append(" ");
cmd.append(mainCommand[i]);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
Runtime.getRuntime().exec(cmd.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (runBeforeRestart!= null) {
runBeforeRestart.run();
}
System.exit(0);
} catch (Exception e) {
throw new IOException("Error while trying to restart the machine", e);
}
}
public void actionPerformed(ActionEvent e) {
/* Differentiate between the different buttons pressed and initiate appropriate
* actions
*/
try{
XmlRpcClient server = new XmlRpcClient("http://localhost:100");
//This code allows the engineer to login to the machine and when they do it reveals new buttons that only the engineer can use.
if (e.getSource().equals(login)){
String message;
boolean loginSuccess = false;
while(loginSuccess == false && (message = JOptionPane.showInputDialog("Login please"))!= null){
Vector parms1 = new Vector();
parms1.add(message);
Object result3 = server.execute("recycling.login", parms1);
String loginRequest = result3.toString();
if(loginRequest.equals("Wrong password")){
System.out.println("Wrong Password. Try Again!");
} else {
sessionCookie = loginRequest;
System.out.println("You are now logged in");
login.setVisible(false);
logout.setVisible(true);
reset.setVisible(true);
empty.setVisible(true);
items.setVisible(true);
loginSuccess = true;
}
}
}else if(e.getSource().equals(visits)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.visits", params);
System.out.println(result);
//This logs the engineer out of the machine and hides some of the buttons
}else if( e.getSource().equals(logout)) {
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.logout", params );
System.out.println("Logout: "+result);
reset.setVisible(false);
empty.setVisible(false);
items.setVisible(false);
login.setVisible(true);
logout.setVisible(false);
//This code tells the engineer how many items are currently in the machine.
}else if(e.getSource().equals(items)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.numberOfItems", params );
int resultInt = new Integer(result.toString());
if( resultInt == -1 ) {
System.out.println("Sorry no authentication there.");
} else {
System.out.println("There are "+resultInt+" items in the machine");
}
//This if statement empties all items that have been put into the machine thus far and sets the item number property to 0
}else if(e.getSource().equals(empty)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.empty", params);
int resultInt = new Integer(result.toString());
if(resultInt == -1){
System.out.println("Sorry no authentication there.");
}else{
System.out.println("The machine has been emptied.");
}
//This method coded above is called here.
}else if(e.getSource().equals(reset)){
restartApplication(null);
}else if(e.getSource().equals(slot1)) {
myCustomerPanel.itemReceived(1);
}else if(e.getSource().equals(slot2)) {
myCustomerPanel.itemReceived(2);
}else if(e.getSource().equals(slot3)) {
myCustomerPanel.itemReceived(3);
}else if(e.getSource().equals(slot4)) {
myCustomerPanel.itemReceived(4);
}else if(e.getSource().equals(receipt)) {
myCustomerPanel.printReceipt();
}else if(e.getSource().equals(display)) {
this.myCustomerPanel = thePanel;
}else if(e.getSource().equals(console)){
myCustomerPanel = theConsole;
}else if(e.getSource().equals(onScreen)){
//once this button is clicked all output is linked back into the GUI
myCustomerPanel = machineScreen;
redirectSystemStreams();
}
}catch (Exception exception) {
System.err.println("JavaClient: " + exception);
}
// System.out.println("Received: e.getActionCommand()="+e.getActionCommand()+
// " e.getSource()="+e.getSource().toString() );
}
//This Adds the controls (buttons) to the GUI
JButton slot1 = new JButton("Can");
JButton slot2 = new JButton("Bottle");
JButton slot3 = new JButton("Crate");
JButton slot4 = new JButton("Paper Bag");
JButton receipt = new JButton("Print Receipt");
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JButton reset = new JButton("Reset");
JButton empty = new JButton("Empty");
JButton items = new JButton("#Items");
JButton visits = new JButton("visits");
JTextArea textArea = new JTextArea(20,30);
JScrollPane scroll = new JScrollPane(textArea);
JButton display = new JButton("Print to Display");
JButton console = new JButton("Print to GUI/Console");
JButton onScreen = new JButton("Show On Screen");
/** This creates the GUI using the controls above and
* adds the actions and listeners. this area of code also
* Contains the panel settings for size and some behaviours.
*/
public RecyclingGUI() {
super();
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(slot1);
panel.add(slot2);
panel.add(slot3);
panel.add(slot4);
slot1.addActionListener(this);
slot2.addActionListener(this);
slot3.addActionListener(this);
slot4.addActionListener(this);
panel.add(receipt);
receipt.addActionListener(this);
panel.add(display);
display.addActionListener(this);
panel.add(console);
console.addActionListener(this);
panel.add(onScreen);
onScreen.addActionListener(this);
/**Text Area controls for size, font style, font size
* the text area also has a scroll bar just in case the user enters
* a large number of items
*/
panel.add(scroll);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setFont(new Font("Ariel",Font.PLAIN, 14));
scroll.setPreferredSize(new Dimension(450, 450));
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(login);
login.addActionListener(this);
panel.add(logout);
logout.setVisible(false);
logout.addActionListener(this);
panel.add(reset);
reset.setVisible(false);
reset.addActionListener(this);
panel.add(items);
items.setVisible(false);
items.addActionListener(this);
panel.add(empty);
empty.setVisible(false);
empty.addActionListener(this);
panel.add(visits);
visits.addActionListener(this);
getContentPane().add(panel);
panel.repaint();
}
public static void main(String [] args ) {
RecyclingGUI myGUI = new RecyclingGUI();
myGUI.setVisible(true);
try {
System.out.println("Starting the Recycling Server...");
WebServer server = new WebServer(100);
server.addHandler("recycling", myGUI);
server.start();
} catch (Exception exception) {
System.err.println("JavaServer: " + exception);
}
}
/** This is the code that redirects where the code is displayed
* from the console to the textArea of the GUI. it does this by
* creating a new set of output streams (for text and errors) which
* are set as default when the redirectSystemStream method is called.
* (from a previous piece of work i did in my FDg, source = from a tutorial)
*/
public void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
}
public void redirectSystemStreams() {
OutputStream out = new OutputStream() {
#Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
public void print(String str) {
System.out.println(str);
}
}
So after working around with the code for a while I discovered that there was one simple piece of code that was causing it to not display the information I wanted.
private int numberOfVisits = 0;
Defining the int as a 0 to begin with caused the code to reset the value of the int every time I pressed the "visits" button.
Removing the 0 fixed this issue.
private int numberOfVisits;

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();
}
}

saving and opening objects from a menu

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

Categories