Save From buffered reader to JTextArea - java

I want to make the result of my buffered reader to appear in a text area, but It doesn't work for me.
I want the text area to get the result exactly as the system out print do, it is for more than one line, I tried to set the text area with string s but didn't work, just give me the result of one line.
Here is my Code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.ScrollPane;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Window extends JFrame {
/**
* Launch the application.
* #throws FileNotFoundException
*/
public static void main(String[] args) {
Window frame = new Window();
frame.setTitle("SWMA Extractor");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setBounds(50, 50, 665, 550);
//frame.setLocation(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.getContentPane().setLayout(null);
}
/**
* Create the frame.
*/
public Window() {
setResizable(false);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel path = new JLabel("File Location");
path.setHorizontalAlignment(SwingConstants.CENTER);
path.setBounds(20, 11, 74, 23);
contentPane.add(path);
final JTextField location = new JTextField();
location.setBounds(104, 12, 306, 20);
contentPane.add(location);
location.setColumns(10);
final JTextArea textArea = new JTextArea();
ScrollPane scrollPane = new ScrollPane();
scrollPane.setBounds(20, 80, 605, 430);
contentPane.add(scrollPane);
scrollPane.add(textArea);
JButton btn = new JButton("Get Info.");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
File output = null;
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s;
int lineNumber = 1;
while((s = br.readLine()) != null) {
if (s.contains("System")) {
System.out.println(s);
String nextLine = br.readLine();
System.out.println(nextLine);
String nextLine1 = br.readLine();
System.out.println(nextLine1);
String nextLine2 = br.readLine();
System.out.println(nextLine2);
String nextLine3 = br.readLine();
System.out.println(nextLine3);
System.out.println();
}
}
lineNumber++;
} catch (IOException e2) {
e2.printStackTrace();
}
}
});
btn.setBounds(433, 11, 192, 23);
contentPane.add(btn);
JButton clr = new JButton("Clear");
clr.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String getLocation = location.getText();
String s;
try {
textArea.setText("");
location.setText("");
} catch (Exception e1) {
}
}
});
clr.setBounds(20, 45, 605, 23);
contentPane.add(clr);
}
}

I see you say you tried setting the text, but the setText method actually replaces the whole current text with the new one:
JTextComponent #1669:
((AbstractDocument)doc).replace(0, doc.getLength(), t,null);
You should use insert or append methods:
Replace
System.out.println(s);
with
textArea.append(s);
Also, check the following question for a better way of doing this:
Opening, Editing and Saving text in JTextArea to .txt file
private void fileRead(){
try{
FileReader read = new FileReader("filepath");
Scanner scan = new Scanner(read);
while(scan.hasNextLine()){
String temp = scan.nextLine() + System.lineSeparator();
storeAllString = storeAllString + temp;
}
}
catch (Exception exception) {
exception.printStackTrace();
}
}
#Hovercraft's suggestion is very good. If you don't want to process the file in any way, you could directly read it into the JTextArea:
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
textArea.read(br, "Stream description");
} catch (IOException e2) {
e2.printStackTrace();
}

Related

java gui if else does no work with arraylist

My code with java GUI adds to an arraylist from a file.txt I have in a button the code that compares the code introduced in a textfield with the position in the araylist with an if else. But enter what you enter always goes through the else never through the if.
If I add the components manually as in Arraylist ArrayList <String> answer = new ArrayList <String> ();
then if else works.
But it seems that if I compare the text of the textfield with the
ArrayList <String> answer1 = new ArrayList <String> ();, the if does not work does not do well the comparison
The question is that I need to ask the user 266 questions The user must enter the answers, if the answer is not correct, an incorrect reply message should come out
but I can not get the if else to work with an arraylist loaded with a file.text here is my code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
public class question_answer extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnAnswer;
private JLabel lblNewLabelcuestion;
private JLabel LabelTextF;
private JLabel labelArraylistPos;
private JLabel lblNewLabelTF;
private JLabel lblNewLabelAL;
static int count = 0;
private JLabel lblNewLabel_1;
private static JTextArea textArea;
private JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
question_answer frame = new question_answer();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public question_answer() {
File archive = null;
FileReader fr = null;
//This works
/*
* ArrayList<String> question = new ArrayList<String>();
* question.add("What is your name?");
* question.add("What is your surname?");
* question.add("What is your age?");
* ArrayList<String> answer = new ArrayList<String>();
* answer.add("Pedro");
* answer.add("Rodriguez");
* answer.add("46");
*/
ArrayList<String> answer1 = new ArrayList<String>();
try {
archive = new File("C:\\answer.txt");
String line;
fr = new FileReader(archive);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
answer1.add(line);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
finally {
try {
if (fr != null) {
fr.close();
}
} catch (IOException e) {
}
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 567, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
lblNewLabelcuestion = new JLabel("New label");
lblNewLabelcuestion.setBounds(60, 56, 360, 24);
contentPane.add(lblNewLabelcuestion);
lblNewLabelTF = new JLabel("New label");
lblNewLabelTF.setBounds(60, 292, 56, 16);
contentPane.add(lblNewLabelTF);
LabelTextF = new JLabel("TextField");
LabelTextF.setBounds(60, 263, 56, 16);
contentPane.add(LabelTextF);
lblNewLabelAL = new JLabel("New label");
lblNewLabelAL.setBounds(170, 292, 56, 16);
contentPane.add(lblNewLabelAL);
labelArraylistPos = new JLabel("Arraylist Position");
labelArraylistPos.setBounds(170, 263, 110, 16);
contentPane.add(labelArraylistPos);
textField = new JTextField();
textField.setBounds(340, 139, 116, 22);
contentPane.add(textField);
textField.setColumns(10);
lblNewLabelcuestion.setText(answer1.get(count));
btnAnswer = new JButton("answer");
lblNewLabelAL.setText(answer1.get(count));
btnAnswer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String line1;
for (int j = 0; j < answer1.size(); j++) {
line1 = answer1.get(j);
textArea.append(line1);
}
lblNewLabelcuestion.setText(answer1.get(count));
lblNewLabelAL.setText(answer1.get(count));
lblNewLabelTF.setText(textField.getText());
String c = answer1.get(count);
String Tf = textField.getText();
if (Tf.equals(c)) {
lblNewLabel_1.setText("Good");
} else {
lblNewLabel_1.setText("Wrong");
}
count += 1;
}
});
btnAnswer.setBounds(340, 198, 97, 25);
contentPane.add(btnAnswer);
lblNewLabel_1 = new JLabel("New label");
lblNewLabel_1.setBounds(45, 153, 256, 16);
contentPane.add(lblNewLabel_1);
textArea = new JTextArea();
textArea.setBounds(345, 273, 181, 67);
contentPane.add(textArea);
lblNewLabel = new JLabel("achive.text content");
lblNewLabel.setBounds(340, 244, 116, 16);
contentPane.add(lblNewLabel);
}
}
`
In any text editor, when you press enter, the the editor enters what is called a line break. This character is invisible but it tells the editor where to make a new line. You need to remove these characters from your lines. Good news is you only have to add one line of code to achieve this! Where you have:
while ((line = br.readLine()) != null) {
answer1.add(line);
}
Replace it with:
while ((line = br.readLine()) != null) {
line = line.replace(System.getProperty("line.separator"), “”);
answer1.add(line);
}
The above code will replace any line separator defined by the OS with an empty string, thereby making your compared strings equal.
The solution was String c = answer1.get(count).trim();

JScrollPane and JTextArea scrolling

I am outputting some logs into the a JTextArea enclosed in JScrollPane but the auto scrolling functionality when the output reaches the bottom of the textArea is not working. I have attempted several methods that I saw online but none works. Below is my part of my code so far.
JTextArea ouputLogPane = new JTextArea();
JScrollPane outputPane = new JScrollPane(ouputLogPane);
outputPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
outputPane.setBounds(75, 501, 746, 108);
contentPane.add(outputPane);
Now I in another class am reading from a source file and appending log details to the textArea using the code below.
public void readFile(JTextArea outputLog, JScrollPane scrollPane){
count = 0;
while(moreLinesToRead){
if(count % 100 == 0){
outputLog.update(outputLog.getGraphics());
outputLog.append("Completed Reading"+ count + " Records "\n");
DefaultCaret caret = (DefaultCaret)outputLog.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
outputLog.update(outputLog.getGraphics());
//tried the one below but did not work either
//outputLog.setCaretPosition(outputLog.getDocument().getLength());
}
count++;
}
}
Finally I am calling this method in the when a button is clicked as below.
JButton btnNewButton = new JButton("Start Reading");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
migrationUtil.readFile(ouputLogPane,outputPane);
}
});
So basically the complete output prints only after the execution finished. I read that I might have to use a separate thread to handle it but not very sure on how to proceed.
EDIT
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class ReadingExample extends JFrame {
private JPanel contentPane;
private Connection conn;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ReadingExample frame = new ReadingExample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ReadingExample() {
//setResizable(false);
setFont(new Font("Dialog", Font.BOLD, 13));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 936, 720);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new LineBorder(new Color(0, 0, 0), 2));
setContentPane(contentPane);
contentPane.setLayout(null);
final JTextArea ouputLogPane = new JTextArea();
final JScrollPane outputPane = new JScrollPane(ouputLogPane);
//outputPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
outputPane.setBounds(67, 189, 746, 108);
contentPane.add(outputPane);
JButton btnNewButton = new JButton("Start Reading");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File file = new File("file.txt");
FileReader fileReader = null;
try {
fileReader = new FileReader(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
try {
while((line = bufferedReader.readLine()) != null) {
ouputLogPane.append(line + "\n");
ouputLogPane.setCaretPosition(ouputLogPane.getDocument().getLength());
try {
Thread.sleep(200);
} catch (InterruptedException ee) {
ee.printStackTrace();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 14));
btnNewButton.setBounds(358, 620, 167, 29);
contentPane.add(btnNewButton);
//JPanel panel_3 = new JPanel();
//panel_3.setBorder(new TitledBorder(null, "Process Log", TitledBorder.LEADING, TitledBorder.TOP, null, null));
//panel_3.setBounds(57, 173, 769, 132);
//contentPane.add(panel_3);
}
}
What you want to do is read the file in a separate thread, so that your Swing thread is not blocked by it, allowing you to update the text area at the same time.
You still need to update the GUI on the Swing thread however, so you do this by calling SwingUtilities.invokeLater(runnable).
Here is a working example (Note I added a Thread.sleep(200) so you can see it being updated):
import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class ReadingExample {
public static void main(String[] args) {
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jFrame.setLocationRelativeTo(null);
JPanel mainPanel = new JPanel(new BorderLayout());
JTextArea jTextArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(jTextArea);
scrollPane.setPreferredSize(new Dimension(300, 300));
mainPanel.add(scrollPane, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Start Reading");
mainPanel.add(btnNewButton, BorderLayout.SOUTH);
jFrame.setContentPane(mainPanel);
jFrame.pack();
jFrame.setVisible(true);
btnNewButton.addActionListener(e -> {
new Thread(() -> {
File file = new File("file.txt");
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while((line = bufferedReader.readLine()) != null) {
final String fLine = line;
SwingUtilities.invokeLater(() -> {
jTextArea.append(fLine + "\n");
jTextArea.setCaretPosition(jTextArea.getDocument().getLength());
});
Thread.sleep(200);
}
} catch (Exception e1) {
e1.printStackTrace();
}
}).start();
});
}
}
There are two ways to scroll to the bottom. You can manipulate the scroll bar:
JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
scrollBar.setValue(scrollBar.getMaximum());
Or, you can use the more reliable scrollRectToVisible method:
try {
textArea.scrollRectToVisible(
textArea.modelToView(
textArea.getDocument().getLength()));
} catch (BadLocationException e) {
throw new RuntimeException(e);
}

How to get a specific data from a look up website

I'm totally new to this section of networking with java.
What I'm trying to do is that, I want the user to add machine type and serial and when he press a button, this will extract the machine expiration date, model and country from a website and then put this data in a txt file automatically.
I'd like as well that the browser to be hidden but don't know how to do it.
I will really appreciate your help.
As well I would prefer to use JTextArea with a vertically only scroll pane to allow the user adding more than one machine (let's say 50 machines) at once , but as well, I don't know how to make the program read the type and serial from this JTextArea separatly
Here is my current code
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.net.URI;
public class PEW_Frame extends JFrame {
private JPanel contentPane;
private JTextField type;
private JTextField serial;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PEW_Frame frame = new PEW_Frame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public PEW_Frame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
type = new JTextField();
type.setBounds(121, 27, 86, 20);
contentPane.add(type);
type.setColumns(10);
serial = new JTextField();
serial.setBounds(121, 72, 86, 20);
contentPane.add(serial);
serial.setColumns(10);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(34, 30, 46, 14);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("New label");
lblNewLabel_1.setBounds(34, 75, 46, 14);
contentPane.add(lblNewLabel_1);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Desktop d = Desktop.getDesktop();
String getType = type.getText();
String getSerial = serial.getText();
//String getType1 = type1.getText();
//String getSerial1 = serial1.getText();
String url = "https://www-947.ibm.com/support/entry/portal/wlup?type="+getType+"&serial="+getSerial;
//String url1 = "https://www-947.ibm.com/support/entry/portal/wlup?type="+getType1+"&serial="+getSerial1;
try {
if (getType.isEmpty() || getSerial.isEmpty()) {
throw new Exception();
}
d.browse(new URI(url));
//d.browse(new URI(url1));
} catch (Exception e1) {
JOptionPane.showMessageDialog(null,"You must select SLA and period","Error !", JOptionPane.ERROR_MESSAGE);
}
}
});
btnNewButton.setBounds(176, 189, 89, 23);
contentPane.add(btnNewButton);
//type1 = new JTextField();
//type1.setBounds(229, 27, 86, 20);
//contentPane.add(type1);
//type1.setColumns(10);
//serial1 = new JTextField();
//serial1.setBounds(229, 72, 86, 20);
//contentPane.add(serial1);
//serial1.setColumns(10);
}
}
You can get some help from the following example:
https://github.com/dotKom/OnlineGuru/blob/master/onlineguru/src/main/java/no/ntnu/online/onlineguru/plugin/plugins/middag/UpdateMenu.java#L40
public void run() {
StringBuilder sb = new StringBuilder();
// This posts the required fields to the sit.no RESTful menu api.
try {
// Prepare post data
String postData = "diner="+ kantine.toLowerCase() +"&trigger=single";
// Open connection
java.net.URL url = new URL(URLTEXT);
URLConnection conn = url.openConnection();
// Write the post data
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(postData);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
wr.close();
rd.close();
} catch (IOException e) {
logger.error("Failed to get JSON data from "+URLTEXT, e.getCause());
}
// Get the html content into a clean string
String json = new String(sb);
json = StringEscapeUtils.unescapeJava(json);
String html = json.split(":")[1].replaceAll("^\"|\"}$", "");
// Traverse html with Jsoup
String menu = findMenuItems(html);
setMenu(kantine, menu);
}

Not getting whole string when string has space in java

I'm still new to java, so dumb question is coming. I've been working on a simple software using JFrame, PrintWriter, File, and Scanner to create and read a text file, I save the file with the name you typed and then with the data you input into a JTextField, the problem is: As soon as you type one space it doesn't save the text after the space to the .txt file:
Input
waitFor it
WriteToFile(textarea.getText(), name.getText());
// my function input text name
Output:
waitFor
But if I input the text manually this way:
WriteToFile("waitFor it", name.getText());
// my function input text name
Output:
waitFor it
Which leads me to think that my function might not be causing this, but again I'm a noob.
Main.java
package creator;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import library.Database;
public class Main extends Database{
public static void main(String[] args) {
JFrame frame = new JFrame();
JButton button = new JButton("Erase");
JButton button2 = new JButton("Add");
JButton button3 = new JButton("Save to Database");
Font font = new Font("Courier", Font.BOLD, 12);
Font font2 = new Font("Courier", Font.BOLD, 14);
final JTextField name = new JTextField();
final JTextField editorPane = new JTextField();
final JTextField textarea = new JTextField();
final JScrollPane scroll = new JScrollPane (textarea,
JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.setTitle("Array Creator");
frame.setSize(401, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setLayout(null);
frame.add(button);
frame.add(name);
frame.add(button2);
frame.add(button3);
frame.add(editorPane);
frame.add(scroll);
button.setBounds(0, 200, 80, 22);
name.setBounds(82, 200, 80, 22);
button2.setBounds(164, 200, 80, 22);
button3.setBounds(246, 200, 148, 22);
editorPane.setBounds(100,175,200,18);
scroll.setBounds(50, 10, 300, 160);
textarea.setEditable(false);
button.setFont(font);
name.setFont(font);
button2.setFont(font);
button3.setFont(font);
editorPane.setFont(font);
textarea.setFont(font2);
textarea.setText("[");
frame.setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textarea.setText("[");
editorPane.setText("");
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textarea.setText(textarea.getText()+"["+editorPane.getText()+"],");
editorPane.setText("");
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String temp = textarea.getText();
temp = temp.substring(0, temp.length()-1);
textarea.setText(temp+"]");
editorPane.setText("");
WriteToFile(textarea.getText(), name.getText());
}
});
name.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent arg0) {
}
public void keyReleased(KeyEvent arg0) {
textarea.setText(readFile(name.getText()));
}
public void keyPressed(KeyEvent arg0) {
}
});
}
}
Database.java
package library;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
public class Database {
public static String WriteToFile(String data, String name){
String output = "ERROR";
PrintWriter writer = null;
try {
writer = new PrintWriter(name+".txt", "UTF-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
writer.println(data);
writer.close();
File file = new File(name+".txt");
try {
#SuppressWarnings("resource")
Scanner sc = new Scanner(file);
output = sc.next();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return output;
}
public static String readFile(String name){
String output = "[";
File file = new File(name+".txt");
try {
#SuppressWarnings("resource")
Scanner sc = new Scanner(file);
output = sc.next();
} catch (FileNotFoundException e) {
}
return output;
}
}
May someone provide me an explanation on why this is?
Instead
output = sc.next();
use
output = sc.nextLine();
Reference: Scanner#next() vs Scanner#nextLine()

Java JCheckBox ActionListener

I have a program that is a list of notes that can be added by the user. Every note is loaded through a for loop and given a JCheckBox on runtime from the notes.txt. How do I add an actionlistener for my JCheckBoxes when they are only instance based and not permanent code?
(e.g. they don't have their own variable names?)
I need to update notes.txt with a 0 or a 1 based on if the JCheckBox is checked or not. Here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SideNotes {
public static JPanel panel = new JPanel();
private static JButton add = new JButton("Add note");
JCheckBox[] notes;
public SideNotes() {
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(add);
loadNotes();
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
addNote();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
public void addNote() throws IOException {
String note = JOptionPane.showInputDialog("Enter note: ", null);
JCheckBox jcb = new JCheckBox(note, false);
panel.add(jcb);
panel.revalidate();
panel.repaint();
File file = new File("notes.txt");
FileWriter writer = new FileWriter(file, true);
BufferedWriter brw = new BufferedWriter(writer);
brw.write(note);
brw.newLine();
brw.close();
}
private void loadNotes() {
File file = new File("notes.txt");
if (file.exists()) {
try {
FileInputStream fs = new FileInputStream(file);
BufferedReader br = new BufferedReader(
new InputStreamReader(fs));
BufferedReader reader = new BufferedReader(new FileReader(
"notes.txt"));
int lines = 0;
while (reader.readLine() != null)
lines++;
reader.close();
notes = new JCheckBox[lines];
for (int i = 0; i < notes.length; i++) {
String note = br.readLine();
int checked = note.charAt(note.length() - 1);
System.out.println(checked);
if (checked == 49) {
note = note.substring(0, note.length() - 1);
notes[i] = new JCheckBox(note, true);
} else {
note = note.substring(0, note.length() - 1);
notes[i] = new JCheckBox(note, false);
}
panel.add(notes[i]);
panel.revalidate();
panel.repaint();
}
br.close();
} catch (Exception e1) {
}
} else {
System.out.println("File does not exist");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(200, 400);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(add);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
new SideNotes();
}
}
Create a generic ActionListener outside the loop where you create the checkboxes:
ActionListener al = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JCheckBox checkbox = (JCheckBox)e.getSource();
// do something with the checkbox
}
}
Then after you create the checkbox you add the ActionListener to the checkbox
notes[i].addActionListener(al);
panel.add(notes[i]);

Categories

Resources