I have created a program where I can input data in JTextField and on hitting save button I use a JFileChooser to save the data in a .txt file where each JTextField is in a new line. I also created a button that pops up a JFileChooser to browse for that file and populate its corresponding cells.
I am new to GUIs, the code I wrote is not working. I tried different variations and cannot seem to get it. Can someone point me in the right direction please.
The input is
john
Doe
st. Jude
100
Here is the code
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import java.util.Scanner
import java.util.Vector;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.io.*;
//import javax.swing.filechooser;
import javax.swing.filechooser.FileFilter;
public class Charity
{
#SuppressWarnings("deprecation")
public static void main(String[] args)
{
JFrame frame = new JFrame("Learning Team Charity Program");
Container cp = frame.getContentPane();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Charities
final String[] charityArray = {"St.Jude", "CHOC", "Cancer Research", "AIDs Foundation", "Crohns Foundation"};
final JComboBox selector = new JComboBox(charityArray);
JPanel first = new JPanel();
first.setLayout(new FlowLayout());
first.add(selector);
// User input JLabels and JTextFields
JLabel nameLabel = new JLabel("First Name: ");
final JTextField name = new JTextField();
JLabel lastLabel = new JLabel("Last Name: ");
final JTextField lastname = new JTextField();
JLabel donationAmount = new JLabel("Donation Amount: ");
final JTextField donation = new JTextField();
JPanel second = new JPanel();
second.setLayout(new GridLayout(4,2));
second.add(nameLabel); second.add(name);
second.add(lastLabel); second.add(lastname);
second.add(donationAmount); second.add(donation);
// Donate & Exit Buttons
JButton donateButton = new JButton("Donate");
JButton saveButton = new JButton("Save");
JButton exitButton = new JButton("Exit");
JButton openButton= new JButton("Open File");
JPanel third = new JPanel();
third.setLayout(new FlowLayout());
third.add(donateButton);
third.add(saveButton);
third.add(openButton);
third.add(exitButton);
// JTable display
final DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("First Name");
model.addColumn("Last Name");
model.addColumn("Charity");
model.addColumn("Donation");
table.setShowHorizontalLines(true);
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(true);
JScrollPane scrollPane = JTable.createScrollPaneForTable(table);
JPanel fourth = new JPanel();
fourth.setLayout(new BorderLayout());
fourth.add(scrollPane, BorderLayout.CENTER);
// Button Events
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(1);
}
});
openButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser openChooser = new JFileChooser();
int openStatus = openChooser.showOpenDialog(null);
if(openStatus == JFileChooser.APPROVE_OPTION){
try{
File myFile = openChooser.getSelectedFile();
BufferedReader br = new BufferedReader(new FileReader(myFile));
String line;
while((line = br.readLine())!= null){
model.addRow(line.split(","));
}//end while
br.close();
}//end try
catch(Exception e2){
JOptionPane.showMessageDialog(null, "Buffer Reader Error");
}//end catch
}
}
private void setValueAt(String line, int row, int col) {
// TODO Auto-generated method stub
}
});
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser fileChooser = new JFileChooser();
int status = fileChooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
{
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text", ".txt", "txt"));
//fileChooser.setFileFilter(new FileFilter("txt"));
PrintWriter output;
try {
File file = fileChooser.getSelectedFile();
output = new PrintWriter(file +".txt");
for(int row = 0; row<table.getRowCount(); row++){
for(int col = 0; col<table.getColumnCount();col++){
output.println(table.getValueAt(row, col).toString());
}
output.println();
}
output.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
donateButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
DecimalFormat df = new DecimalFormat("##,###.00");
try
{
Object[] rows = new Object[]{name.getText(), lastname.getText(), selector.getSelectedItem(),
donation.getText()};
model.addRow(rows);
name.setText("");
lastname.setText("");
donation.setText("");
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Enter a Dollar Amount", "Alert", JOptionPane.ERROR_MESSAGE);
return;
}
}
});
// Frame Settings
frame.setSize(470,300);
//frame.setLocation(300,200);
cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS));
cp.add(first);
cp.add(second);
cp.add(third);
cp.add(fourth);
frame.setVisible(true);
}
}
I understand I have to pass a value in the parenthesis after the addRow.
People don't know what that means because the code you posted here doesn't have an addRow(...) method.
I see you posted a second question 2 hours later: https://stackoverflow.com/questions/30951407/how-to-properly-read-a-txt-file-into-a-a-row-of-a-jtable.
Keep all the comments in one place so people understand what is going on.
Also, posting a few random lines of code doesn't help us because we don't know the context of how the code is used. For example, I have no idea what how you created the "model" variable. I don't know if you ever added the model to the table.
Post a proper SSCCE when posting a question so we have the necessary information. The file chooser is irrelevant to the problem because we don't have access to your real file. So instead you need to post hard coded data. An easy way to do this is to use a StringReader.
Here is a working example that shows how to read/parse/load a file into a JTable:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.io.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
try
{
DefaultTableModel model = new DefaultTableModel(0, 4);
String data = "1 2 3 4\na b c d\none two three four";
BufferedReader br = new BufferedReader( new StringReader( data ) );
String line;
while ((line = br.readLine()) != null)
{
String[] split = line.split(" ");
model.addRow( split );
}
JTable table = new JTable(model);
add( new JScrollPane(table) );
}
catch (IOException e) { System.out.println(e); }
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
All you need to do is change the code to use a FileReader instead of the StringReader.
I figured it out. Thanks for all those that tried to help.
openButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser openChooser = new JFileChooser();
int openStatus = openChooser.showOpenDialog(null);
if(openStatus == JFileChooser.APPROVE_OPTION){
try{
File myFile = openChooser.getSelectedFile();
//BufferedReader br = new BufferedReader(new FileReader(myFile));
Scanner br = new Scanner(new FileReader(myFile));
String line;
while((line = br.nextLine())!= null){
Object[] myRow = new Object[]{line,br.nextLine(), br.nextLine(), br.nextLine()};
model.addRow(myRow);
// line = br.readLine();
if(br.nextLine()== " "){
line=br.nextLine();
}
}//end while
br.close();
}//end try
catch(Exception e2){
return;
}//end catch
}
}
});
Related
How do I add,remove and search for items in an arraylist when using GUI? I would like to add user input into the programs arraylist.
Also how do I CHECK TO SEE IF A FILE CALLED INFO.TXT EXISTS -- IF IT DOES -- SET ALL INFO IN info.txt FILE INTO TEXTAREA -- See below:
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import javax.swing.*;
import java.io.File;
import java.io.*;
import static java.lang.System.out;
public class FinalMainFrame extends
JFrame {
BufferedReader br = null;
private Container pane;
private JTextField textField;
public FinalMainFrame() {
pane=getContentPane();
pane.setLayout(null);
JMenuBar menuBar = new JMenuBar();
JMenu menuFile = new JMenu();
JMenuItem menuFileExit = new
JMenuItem();
menuFile.setText("File");
menuFileExit.setText("Exit");
menuFileExit.addActionListener
( (ActionEvent e) -> {
FinalMainFrame.this.windowClosed();
});
menuFile.add(menuFileExit);
menuBar.add(menuFile);
setTitle("Final Project...");
setJMenuBar(menuBar);
setSize(new Dimension(250, 200));
JLabel label = new JLabel("Enter Info:");
label.setFont(new Font("Serif",
Font.PLAIN, 18));
pane.add(label);
label.setLocation(0, 10);
label.setSize(100, 30);
textField = new JTextField(20);
pane.add(textField);
textField.setSize(100, 30);
textField.setLocation(120, 10);
JButton button1 = new JButton("Save");
pane.add(button1);
button1.setLocation(30, 70);
button1.setSize(150, 50);
button1.addActionListener
(
new ActionListener() {
public void
actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(
null,"You pressed: " +
e.getActionCommand() );
try{
FileReader read = new
FileReader("info.txt");
BufferedReader br = new
BufferedReader(read);
String txt = "";
String line = br.readLine();
while (line != null){
txt += line;
line = br.readLine();
out.println(line);
}
String text = textField.getText();
FileWriter stream = new
FileWriter("info.txt");
try (BufferedWriter out = new
BufferedWriter(stream)) {
out.write(text);
}
JOptionPane.showMessageDialog(
null,"You entered: " + text );
}
catch (Exception ex) {}
}
}
);
this.addWindowListener
(
new WindowAdapter() {
public void
windowClosing(WindowEvent e) {
FinalMainFrame.this.windowClosed();
}
}
);
}
protected void windowClosed() {
System.exit(0);
}
}
When talking about GUI you should think of events. So add user input to your arraylist on a click event or etc.
Can someone tell me how to modify below program? Program's data is passed by object[][] - instead of that will just give file name which is having data should be print in a table.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SimpleTableDemo extends JPanel {
private boolean DEBUG = false;
public SimpleTableDemo() {
super(new GridLayout(1,0));
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
Object[][] data = {
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
};
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
if (DEBUG) {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
printDebugData(table);
}
});
}
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
add(scrollPane);
}
private void printDebugData(JTable table) {
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();
System.out.println("Value of data: ");
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
}
System.out.println();
}
System.out.println("--------------------------");
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
SimpleTableDemo newContentPane = new SimpleTableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
If I understood question correct, you can replace Object[][] data with something like this:
String line;
ArrayList<String[]> toData = new ArrayList<String[]>();
File file = new File("\\file path");
try{
BufferedReader reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
String[] lineElements = line.split(",");
toData.add(lineElements);
}
}catch (Exception ex){
ex.printStackTrace();
System.out.println("File not found");
}
String[][] data = new String[toData.size()][];
int index = 0;
for(String[] a: toData){
data[index]=a;
index++;
}
In this exemple, it will work if data in file is formatted as:
name, surname, sportage, is Vegetarian. However you can change that easily, but remember to also change symbol in brackets in line.split().
EDIT:
I don't fully understand what you want to achieve, however I would do it like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
public class Project {
private JScrollPane scrollPane;
private JFrame frame;
private JTable table;
public static void main (String[] args){
Project project = new Project();
project.createGUI();
}
public void createGUI(){
frame = new JFrame();
scrollPane = new JScrollPane();
JPanel panel = new JPanel();
JButton open = new JButton("Open");
open.addActionListener(new OpenListener());
JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitListener());
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new CancelListener());
panel.add(open);
panel.add(submit);
panel.add(cancel);
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.getContentPane().add(BorderLayout.SOUTH,panel);
frame.setSize(500,500);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void createAndDisplayList(String[][] data){
String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"};
table = new JTable(data, columnNames);
frame.setVisible(false);
frame.remove(scrollPane);
scrollPane = new JScrollPane(table);
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.revalidate();
frame.setVisible(true);
}
private class OpenListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
String line;
ArrayList<String[]> toData = new ArrayList<String[]>();
fileChooser.showOpenDialog(frame);
try{
BufferedReader reader = new BufferedReader(new FileReader(fileChooser.getSelectedFile()));
while ((line = reader.readLine()) != null) {
String[] lineElements = line.split(",");
toData.add(lineElements);
}
reader.close();
}catch (Exception ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, "File not found", "Error", JOptionPane.ERROR_MESSAGE);
}
String[][] data = new String[toData.size()][];
int index = 0;
for(String[] a: toData){
data[index]=a;
index++;
}
createAndDisplayList(data);
}
}
private class CancelListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
frame.remove(scrollPane);
scrollPane = new JScrollPane();
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.revalidate();
frame.setVisible(true);
}
}
private class SubmitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showSaveDialog(frame);
try{
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()));
for(int i = 0; i<table.getRowCount(); i++){
for(int j = 0; j<table.getColumnCount(); j++){
System.out.println(i + "," + table.getRowCount());
bufferedWriter.write(table.getValueAt(i, j).toString() + ",");
}
bufferedWriter.newLine();
}
bufferedWriter.close();
}catch (IOException ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(frame,"File not found","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}
However be aware it is a primitive and amateur written code, but it works to some extent. You can open, change content and save file(submit), but you cannot add rows in table, you need to do it in .txt file (but you cannot leave any empty space at the end of file).
Anyway, I hope you will find something usufull here.
i am trying to implement GUI features to my java coding which i am trying out for the first time. But i tried a "Create Player Feature" in my code but it is not writing to file can someone help? thanks
private class createListener implements ActionListener{
public void actionPerformed(ActionEvent event){
JFrame frame = new JFrame("Create Player");
JPanel panel = new JPanel();
JPanel mainpanel = new JPanel();
JButton create;
JLabel welcome = new JLabel("Create Player");
JLabel name = new JLabel("Enter Player Name");
nameP = new JTextField();
JLabel pass = new JLabel("Enter Player Password");
password = new JTextField();
JLabel chips = new JLabel("Enter Player Chips");
chipsP = new JTextField();
buttonCreate = new JButton("Create Player");
setSize(400,350);
setLocation(500,280);
panel.setLayout(new GridLayout(0,1,10,10));
panel.add(name);
panel.add(nameP);
panel.add(pass);
panel.add(password);
panel.add(chips);
panel.add(chipsP);
panel.add(buttonCreate);
mainpanel.add(panel);
getContentPane().removeAll();
getContentPane().add(mainpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
buttonCreate.addActionListener(new createListener());
}
}
private class playerListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String username = nameP.getText();
String userpass = password.getText();
String hasheduserP = Utility.getHash(userpass);
String userchip = chipsP.getText();
String userContent = username + "|" + hasheduserP + "|" + userchip;
File file = new File("players.dat");
try{
//adding of user details
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("players.dat", true)));
out.println(userContent);
out.close();
JOptionPane.showMessageDialog(null,"User Created");
} catch (IOException ex){
System.out.println("Error Writing to File");
}
}
}
The file related part of your code works without any problem.
Hint: Improve it like this:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class SOPlayground {
public static void main(String[] args) throws Exception {
String userContent = "foo";
try {
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("/tmp/players.dat", true)))) {
out.println(userContent);
}
} catch (IOException ex) {
System.err.println("Error Writing to File: " + ex.getMessage());
}
}
}
The content of /tmp/players.dat now is
foo
I'm reading from a text file a long quote, so all the labels are set but the button will not display a JLabel of the thing. I can get the system print to display but the labels wouldn't come out so the button seems to be fine. To be very specific the quote is an "html formatted text document of chris tucker's version of martin luther king speech.
Here's what I've tried so far:
package MenuBoxes;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class quoteReader extends JFrame{
private JFrame frame;
public quoteReader(){
initUI();
}
public final void initUI(){ {
String listArray[] = null;
JButton click = new JButton("click me");
click.setLocation(120,30);
click.setSize(100,100);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(click);
add(panel);
setTitle("Quote Reader");
setSize(500,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
click.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
//nameLabel = name.getText();
//use .= for comparing strings
String[] listArray = new String [2];
try{
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Chrt\\workspace\\Finals\\Quotes.txt"));
int index = 0;
String line = "";
while((line = br.readLine()) != null) {
listArray[index] = line;
index++;
JLabel read = new JLabel(line);
System.out.println(line);
read.setLocation(120,90);
read.setSize(300,200);
read.setFont(new Font("Calibri",Font.BOLD,13));
panel.add(read);
add(panel);
setVisible(true);
}
br.close();
} catch (IOException ioe){
System.out.println("Cannot read");
System.exit(0);
}
}
}
);
}}}
You need to repaint after adding text to the label.
this.repaint();
Also, per your code, you aren't making the JFrame visoble until AFTER you add text to the JLabel. you should add
setVisible(true);
to your initUI() method.
so I am trying to have my program read a list of lines from a txt file. This is then displayed in a JTextArea. The user can input data using the JTextField and the goal is to display "Hooray" if the user matches the text in the JArea and "Wrong!" if they do not. Any help is appreciated.
public class TextArea1 {
JTextArea text;
JFrame frame;
JTextField textField;
public int k;
public ArrayList aList;
public String correctAnswer;
public static void main(String[] args) {
TextArea1 gui = new TextArea1();
gui.go();
}
private String textLine;
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
textField = new JTextField("");
textField.addActionListener(new startTextFieldListener("correct answer"));
JButton startButton = new JButton("Start!");
startButton.addActionListener(new startButtonListener(aList));
text = new JTextArea(30, 60);
text.setLineWrap(true);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.WEST, startButton);
frame.getContentPane().add(BorderLayout.SOUTH, textField);
frame.setSize(350, 300);
frame.setVisible(true);
}
class startButtonListener implements ActionListener {
ArrayList aList;
startButtonListener(ArrayList passedInList) {
aList = passedInList;
}
#Override
public void actionPerformed(ActionEvent event) {
String fileName = "test.txt";
String line;
ArrayList aList = new ArrayList();
try {
try (BufferedReader input = new BufferedReader(new FileReader(fileName))) {
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(line);
}
}
} catch (IOException e) {
System.out.println(e);
}
int sz = aList.size();
for (int k = 0; k < sz; k++) {
String correctAnswer = aList.get(k).toString();
text.append(aList.get(k).toString());
text.append("\n");
}
}
}
class startTextFieldListener implements ActionListener {
String correctAnswer;
startTextFieldListener(String answer) {
correctAnswer = answer;
}
#Override
public void actionPerformed(ActionEvent event) {
if (text.getText().equals(correctAnswer)) {
JOptionPane.showMessageDialog(null, "Hooray!");
} else {
JOptionPane.showMessageDialog(null, "Wrong!");
}
}
}
}
Ok Try this one:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class TextArea1{
JTextArea text;
JFrame frame;
JTextField textField;
public int k;
public ArrayList aList;
public String correctAnswer;
public static void main (String [] args) {
TextArea1 gui = new TextArea1();
gui.go();
}
private String textLine;
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
textField = new JTextField("");
JButton startButton = new JButton ("Start!");
startButton.addActionListener(new startButtonListener());
text = new JTextArea (30, 60);
text.setLineWrap(true);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.WEST, startButton);
frame.getContentPane().add(BorderLayout.SOUTH, textField);
frame.setSize(350, 300);
frame.setVisible(true);
}
class startButtonListener implements ActionListener {
ArrayList aList;
public void actionPerformed(ActionEvent event) {
String fileName = "test.txt";
String line;
ArrayList <String>aList = new ArrayList<>();
try {
try (BufferedReader input = new BufferedReader (new FileReader(fileName))) {
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) !=null) {
aList.add(line);
}
}
} catch (IOException e) {
System.out.println(e);
}
int sz = aList.size();
boolean result=false;
for(String t:aList){
if (t.equalsIgnoreCase(textField.getText())) {
JOptionPane.showMessageDialog(null, "Hooray! Loading File contents....");
int count=0;
for (int k = 0; k< sz; k++) {
text.append(aList.get(k).toString());
System.out.println(count);
count++;
// if(k<sz-1)
// text.append(", ");
text.append("\n");
}
result=true;
break;
}
else {
result=false;
}
}
if(!result){
JOptionPane.showMessageDialog(null, "Wrong!");
}
}
}
}
In this it will look for you text enter in textfield and if it matches it will add entire file content line by line. i have already tested. But remember i am not having sufficient time so ,i have not done regex pattern matching it is simple equal comparison with one line in you text file with text entered in textbox exactly.
Well, I have just modified your code so that you will get proper message when value in contain in list. look and modify accordingly.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class TextArea1{
JTextArea text;
JFrame frame;
JTextField textField;
public int k;
public String correctAnswer;
public static void main (String [] args) {
TextArea1 gui = new TextArea1();
gui.go();
}
private String textLine;
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
textField = new JTextField("");
//textField.addActionListener(new startTextFieldListener("correct answer"));
JButton startButton = new JButton ("Start!");
startButton.addActionListener(new startButtonListener());
text = new JTextArea (30, 60);
text.setLineWrap(true);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.WEST, startButton);
frame.getContentPane().add(BorderLayout.SOUTH, textField);
frame.setSize(350, 300);
frame.setVisible(true);
}
class startButtonListener implements ActionListener {
ArrayList aList;
startButtonListener()
{
}
public void actionPerformed(ActionEvent event) {
String fileName = "test.txt";
String line;
ArrayList aList = new ArrayList();
try {
try (BufferedReader input = new BufferedReader (new FileReader(fileName))) {
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) !=null) {
aList.add(line);
}
System.out.println("List ready to check. values in list are :"+aList);
}
} catch (IOException e) {
System.out.println(e);
}
if (aList.contains(text.getText())) {
JOptionPane.showMessageDialog(null, "Hooray!");
}
else {
JOptionPane.showMessageDialog(null, "Wrong!");
}
}
}
}
if this is correct then mark it as correct.
Minor mistake you added a new line each time you append to the textArea.. that why its not comparing due to the extra new line
if you have new line in you file no problem the arrayList has it already when you parse the file so no need to add new line.
solution:
public class TextArea1{
JTextArea text;
JFrame frame;
JTextField textField;
public int k;
public String correctAnswer;
public static void main (String [] args) {
TextArea1 gui = new TextArea1();
gui.go();
}
private String textLine;
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
textField = new JTextField("");
//textField.addActionListener(new startTextFieldListener("correct answer"));
JButton startButton = new JButton ("Start!");
startButton.addActionListener(new startButtonListener());
text = new JTextArea (30, 60);
text.setLineWrap(true);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.WEST, startButton);
frame.getContentPane().add(BorderLayout.SOUTH, textField);
frame.setSize(350, 300);
frame.setVisible(true);
}
class startButtonListener implements ActionListener {
ArrayList aList;
startButtonListener()
{
}
public void actionPerformed(ActionEvent event) {
String fileName = "test.txt";
String line;
String string = "";
try {
try (BufferedReader input = new BufferedReader (new FileReader(fileName))) {
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) !=null) {
string += line;
//aList.add(line);
}
System.out.println("List ready to check. values in list are :"+aList);
}
} catch (IOException e) {
System.out.println(e);
}
if (string.equals(textField.getText())) {
JOptionPane.showMessageDialog(null, "Hooray!");
}
else {
JOptionPane.showMessageDialog(null, "Wrong!");
}
}
}
}