I am writing a program that has at least three JButtons and I have log file. Any
ID: 3572257 • Letter: I
Question
I am writing a program that has at least three JButtons and I have log file. Anytime a button is pressed I need it to record on the log file. So far the code I provided only records the last button pressed, and it does not record the previous ones. What can I do so that it records every time a button is pressed instead of the last action. This is part of my code:
JButton btn = new JButton("BUTTON");
btnVerify.setFont(new Font("Arial", Font.BOLD, 14));
btn.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent e)
{
if (btn.isEnabled())
{ String wrd = ""BUTTON " button was pressed."; try {
FileWriter fw = new FileWriter("LoggersFile.txt", true);
PrintWriter pwr = new PrintWriter(fw, true);
PrintWriter outFile = new PrintWriter("LoggersFile.txt");
outFile.println(wrd ); outFile.close();
} catch (IOException e1)
{ // TODO Auto-generated catch block e1.printStackTrace();
} } }});
This is also the code for the other buttons. Thank you in advance
Explanation / Answer
You are using PrintWriter object outFile for writing the logs to the log file. This PrintWriter object directly uses the file "LoggersFile.txt" without specifying the append mode true. So one thing you can do is that just use FileWriter fw inside PrintWriter outFile, note that the FileWriter fw is already opened in apend mode, so you can append the contents to the file instead of replcing the old contents. So the code changes you need to make is given below:
try {
FileWriter fw = new FileWriter("LoggersFile.txt", true);
PrintWriter outFile = new PrintWriter( fw );
outFile.println(wrd ); outFile.close();
} catch (IOException e1)
{ // TODO Auto-generated catch block e1.printStackTrace();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.