Parse Input from GUI instead of Console in Eclipse - java

I have a small GUI project with a text-box and submit button. What I want to do is for user to type into the text-box and submit an input that would move them through the program (ex. 1 to go to next menu). The program did not use to have a GUI and used console to enter input (as seen in the first code) and so I want to move the program away from console.
Right now my main is:
public static void main(String[] args) {
//Initialize menu variable
Menu menu = MainMenu.getInstance();
new Console();
while (true){
//Display current menu
menu.displayMenu();
while (menu.moreInputNeeded()){
menu.displayPrompt();
try {
// Process user input.
menu.parseInput(new BufferedReader(new InputStreamReader(System.in)).readLine());
} catch (IOException e) {
// printStackTrace();
System.out.println(Prompt.INVALID_INPUT);
}
}
menu = menu.getNextMenu();
}
}
and I use a text/submit button as followed:
//Create the Text Box
JTextField textField = new JTextField(20);
//Submit Button
JButton submit = new JButton("Submit");
//Submit Function
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
menuinput = textField.getText();
textField.setText("");
//
System.out.println(menuinput);
}
});
So is it possible to process user input from the GUI instead of the console?

I was able to figure out my own question. I implemented:
//Variables
JTextField tfIn;
JLabel lblOut;
private final PipedInputStream inPipe = new PipedInputStream();
private final PipedInputStream outPipe = new PipedInputStream();
PrintWriter inWriter;
String input = null;
Scanner inputReader = new Scanner(System.in);
//Variables
System.setIn(inPipe);
try {
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);
}
catch(IOException e) {
System.out.println("Error: " + e);
return;
}
tfIn = new JTextField();
tfIn.addActionListener(this);
frame.add(tfIn, BorderLayout.SOUTH);
With Method:
public synchronized void actionPerformed(ActionEvent evt)
{
textArea.setText("");
String text = tfIn.getText();
tfIn.setText("");
inWriter.println(text);
}
There might be some other little aspects I missed but that's the most important parts.

Related

How to set JavaFX TextField to wrap text inside field

I need hlep with figuring out how to wrap the text in the JavaFX TextField object.
So my code gets a file name from the user, opens the file by pasting the contents of the text file into the text field. Then the user can edit the text and save it into the same file.
My code does all of the above so that's not what I need help with. The JavaFX TextField object does not seem to have a way to wrap the text in the text box. It ends up looking like this:
Alt Image Link: https://drive.google.com/open?id=1q2yU5ox6WA5EwS3YSxaKoqUDpCxpbPmu
I want to wrap the text for obvious reasons. Below is my code (minus the import statements)
public class TextEditor extends Application
{
private Button button = new Button();
private TextField text = new TextField();
private Label label = new Label("Enter filename:");
private String filename = "";
String filetext = "";
Scanner file = new Scanner("");
PrintWriter pw = null;
FileOutputStream fos = null;
#Override
public void start(Stage primaryStage) throws Exception
{
GridPane myPane = new GridPane();
myPane.setHgap(10);
myPane.setVgap(10);
Scene myScene = new Scene(myPane, 500, 500);
primaryStage.setScene(myScene);
primaryStage.show();
primaryStage.setTitle("Find File");
myPane.setAlignment(Pos.BASELINE_CENTER);
label.setAlignment(Pos.BASELINE_CENTER);
myPane.add(label, 0, 0, 3, 1);
text.setAlignment(Pos.TOP_LEFT);
text.setPrefWidth(480);
text.setPrefHeight(400);
myPane.add(text, 0, 1);
button = new Button("Submit Filename");
button.setPrefSize(180, 50);
button.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
if(button.getText().equals("Save Changes"))
{
try
{
fos = new FileOutputStream(filename);
pw = new PrintWriter(fos);
System.out.println("Saving changes in " + filename);
pw.println(text.getText());
pw.close();
primaryStage.close();
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(button.getText().equals("Submit Filename"))
{
filename = text.getText();
try
{
file = new Scanner(new FileInputStream(new File(filename)));
while(file.hasNextLine())
{
String line = file.nextLine();
System.out.println(line);
filetext += line + "\n";
}
System.out.println("File text: " + filetext);
text.setText(filetext);
button.setText("Save Changes");
}
catch(FileNotFoundException exc)
{
System.out.println("Cannot find file. Program aborted.");
primaryStage.close();
}
}
}
});
myPane.add(button, 0, 2);
}
public static void main(String[] args)
{
Application.launch(args);
}
}
Would love some assistance getting the text to wrap. Do I need to not use a JavaFX TextField? Should I use something else?
Thanks in advance!
EDIT
SOLUTION FOUND
I changed the TextField text to a TextArea, removed the text.setAlignment(Pos.TOP_LEFT) line and added a text.setWrapText(true) (as suggested below) and now the program works great. Thanks Fabian and Zephyr!

How to access another object from within a listener in Java

I have a listener on one of the elements of the menu class GraphMenu() in my program that that needs to call a method of an existing object created outside that class and I can't seem to find a way to implement this.
I'm defining the method of the panel I need to call in the GraphPanel() class:
public class GraphPanel extends JPanel {
private JLabel textLabel, graphicLabel;
private JTextArea textArea;
private JPanel graphPanel;
public void appendTextArea(String s) {
textArea.append(s + '\n');
}
The listener of the GraphMenu() I need to call that method in is:
public class GraphMenu {
...
// Add the action listeners that identify the code to execute when the options are selected.
menuItemLoad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final JFileChooser fc = new JFileChooser();
// you can set the directory with the setCurrentDirectory method.
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
// User has selected to open the file.
File file = fc.getSelectedFile();
try {
// Open the selected file
BufferedReader reader = new BufferedReader(new FileReader(file));
// Output the contents to the console.
String nextLine = reader.readLine();
while ( nextLine != null ) {
panel.appendTextArea(nextLine);
System.out.println(nextLine);
nextLine = reader.readLine();
}
reader.close();
} catch (IOException e1) {
System.err.println("Error while reading the file");
}
};
}
});
...
Is there a way I can call the appendTextArea() on the panel object as in the example above?
I'm creating the two objects of class GraphPanel() and GraphMenu() in the main function:
GraphPanel panel = new GraphPanel();
frame.getContentPane().add(panel);
GraphMenu menu = new GraphMenu();
frame.setJMenuBar(menu.setupMenu());

Why my JTextArea is not displaying properly from the while loop?

My GUI application allows users to type into a JTextField object stating the name of a file to open and display its contents onto a JTextArea object. If the entered information consists of the file name then it shall retrieve its contents otherwise, in other case, it shall be a directory then it shall display the files and folders. Right now, I'm stuck as in the setText() of my JTextArea does not display contents correctly. It only display once which means to say there's some problem with my while loop. Could you guys help me out here please?
Please note the code below has been altered to the correct working version provided all the helpful contributors below.
Main class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
class MyFileLister extends JPanel implements ActionListener {
private JLabel prompt = null;
private JTextField userInput = null;
private JTextArea textArea = null;
public MyFileLister()
{
prompt = new JLabel("Enter filename: ");
prompt.setOpaque(true);
this.add(prompt);
userInput = new JTextField(28);
userInput.addActionListener(this);
this.add(userInput);
textArea = new JTextArea(10, 30);
textArea.setOpaque(true);
JScrollPane scrollpane = new JScrollPane(textArea);
this.add(textArea, BorderLayout.SOUTH);
}
Scanner s = null;
File af = null;
String[] paths;
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
while(s.hasNextLine())
{
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(truea);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath = "";
for(String path: paths)
{
tempPath += path + "\n";
}
textArea.setText(tempPath);
}
}
}
Driver class:
import java.util.*;
import java.awt.*;
import javax.swing.*;
class TestMyFileLister {
public static void main(String [] args)
{
MyFileLister thePanel = new MyFileLister();
JFrame firstFrame = new JFrame("My File Lister");
firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstFrame.setVisible(true);
firstFrame.setSize(500, 500);
firstFrame.add(thePanel);
}
}
Here's one of the screenshot which I have to achieve. It shows that when the user's input is on a directory it displays the list of files and folders under it.
I tried to put in an if statement to see if I can slot in a show message dialog but I seriously have no idea where to put it.
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
if(af == null)
{
System.out.println("Error");
}
while(s.hasNextLine())
{
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(true);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath = "";
for(String path: paths)
{
tempPath += path + "\n";
}
textArea.setText(tempPath);
}
}
You're outputting text to textArea based on the Last File on the list !!! ( don't set your text to JTextArea directly inside a loop, the loop is fast and the UI can't render it, so concatenate the string then set it later after the loop finishes ).
// These lines below are causing only last file shown.
for(String path: paths)
{
textArea.setText(path);
}
Here is your modified version for MyFileLister class :
public class MyFileLister extends JPanel implements ActionListener {
private JLabel prompt = null;
private JTextField userInput = null;
private JTextArea textArea = null;
public MyFileLister()
{
prompt = new JLabel("Enter filename: ");
prompt.setOpaque(true);
this.add(prompt);
userInput = new JTextField(28);
userInput.addActionListener(this);
this.add(userInput);
textArea = new JTextArea(10, 30);
textArea.setOpaque(true);
JScrollPane scrollpane = new JScrollPane(textArea);
this.add(scrollpane, BorderLayout.SOUTH);
}
Scanner s = null;
File af ;
String[] paths;
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
while(s.hasNext())
{
String as = s.next();
textArea.setText(as);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath="";
for(String path: paths)
{
tempPath+=path+"\n";
}
textArea.setText(tempPath);
}
}
}
Output :
Code:
public void actionPerformed(ActionEvent ae) {
try (Scanner s = new Scanner(new File(userInput.getText()))) {
while (s.hasNextLine()) {
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(true);
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this,
"File not found",
"No File Error",
JOptionPane.ERROR_MESSAGE);
}
}
Notes:
Just try to read your file line by line so you can copy the same structure from your file into your JTextArea.
Use setLineWrap method and set it to true
read here http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#setLineWrap(boolean)
use append method in order to add text to end of your JTextArea
read here
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#append(java.lang.String)
Use JOptionPane to show error message to an user

Deleting a set of data in text file

I'm creating a program in Java(GUI) that when you fill out the TextFields and click enter; the name,age,email,nationality and cell number will be saved in a textfile named StoredInfo.txt . The program I created didn't delete the data you entered if you fill out the textfields again.
What I want want to do is to use the Clear Data button I created and it will delete all the data stored in the text file (StoredInfo.txt).
Here's my program:
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SignUp extends JFrame implements ActionListener
{
//Variables
private JButton enter,clear;
private JLabel header,name,age,email,nationality,cellno;
private JTextField nameTF,ageTF,emailTF,nationalityTF,cellnoTF;
private Container container;
private PrintWriter pwriter;
//Constructor
public SignUp()
{
setTitle("Form");
setSize(500,500);
setResizable(false);
setDefaultCloseOperation(this.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(null);
container = this.getContentPane();
container.setBackground(Color.GRAY);
enter = new JButton("Enter");
clear = new JButton("Clear Data");
header = new JLabel("Form");
name = new JLabel("Name: ");
age = new JLabel("Age: ");
email = new JLabel("Email Address: ");
nationality = new JLabel("Nationality: ");
cellno = new JLabel("Cellphone #: ");
nameTF = new JTextField(20);
ageTF = new JTextField(20);
emailTF = new JTextField(20);
nationalityTF = new JTextField(20);
cellnoTF = new JTextField(20);
nameTF.addActionListener(this);
ageTF.addActionListener(this);
emailTF.addActionListener(this);
nationalityTF.addActionListener(this);
cellnoTF.addActionListener(this);
enter.addActionListener(this);
clear.addActionListener(this);
//Add section
this.add(header);
this.add(name);
this.add(age);
this.add(email);
this.add(nationality);
this.add(cellno);
this.add(header);
this.add(nameTF);
this.add(ageTF);
this.add(emailTF);
this.add(nationalityTF);
this.add(cellnoTF);
this.add(clear);
this.add(enter);
//SetBounds
enter.setBounds(180,270,80,40);
clear.setBounds(270,270,100,40);
header.setBounds(230,30,80,50);
header.setFont(new Font("Arial",Font.BOLD,25));
header.setForeground(Color.WHITE);
name.setBounds(80,90,40,40);
age.setBounds(80,120,40,40);
email.setBounds(80,150,110,40);
nationality.setBounds(80,180,100,40);
cellno.setBounds(80,210,100,40);
nameTF.setBounds(180,95,190,25);
ageTF.setBounds(180,125,190,25);
emailTF.setBounds(180,155,190,25);
nationalityTF.setBounds(180,185,190,25);
cellnoTF.setBounds(180,215,190,25);
name.setForeground(Color.WHITE);
age.setForeground(Color.WHITE);
email.setForeground(Color.WHITE);
nationality.setForeground(Color.WHITE);
cellno.setForeground(Color.WHITE);
//Setting Up Text File
try
{
File data = new File("StoredInfo.txt");
pwriter = new PrintWriter(new FileWriter(data,false));
if(data.exists())
{
}else
{
data.createNewFile();
}
}catch(Exception e)
{
e.printStackTrace();
}
setVisible(true);
}
//Actions
public void actionPerformed(ActionEvent e)
{
Object action = e.getSource();
if(action.equals(enter))
{
pwriter.println("Name: " + nameTF.getText());
pwriter.println("Age: " + ageTF.getText());
pwriter.println("Email: " + emailTF.getText());
pwriter.println("Nationality: " + nationalityTF.getText());
pwriter.println("CellNo #: " + cellnoTF.getText());
pwriter.println("---------------------------");
pwriter.flush();
pwriter.close();
}else if(action.equals(clear))
{
}
}
///Main
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new SignUp();
}
});
}
}
Generally speaking new FileWriter(file); will overwrite the file leaving it empty.
In your case,
else if (action.equals(clear)) {
// Need to close this first to avoid resource leak
pw.close();
File data = new File("StoredInfo.txt");
// I believe you will need pw later
pw = new PrintWriter(new FileWriter(data, false));
}
Hope that helped.

Java cant write in a .txt

hello i desperately need your help,well i have a jframe with a jcombobox and 3 textfields i want anything i write in the textfields and the choice i make in the combobox to be written in a .txt i tried so many things but nothing , the file is being created as Orders.txt but remains blank :S this is my code i appreciate any help Thanks :)
public class addSalesMan extends JFrame {
private JComboBox namesJComboBox;
private JTextField text1;//gia to poso
private JTextField text2;//thn perigrafh
private JTextField text3;//kai to numero ths paragelias kai ola auta tha egrafontai sto Orders.txt
private JButton okJbutton;
private String names[] = {"Basilis Komnhnos", "Iwanna Papadhmhtriou"};
public String amount,name,description,number;
public addSalesMan() {
super("Προσθήκη παραγγελιών");
setLayout(new FlowLayout());//dialegoume to flowlayout
// TextFieldHandler handler = new TextFieldHandler(); writer.write(string);
//ftiaxonoume to combobox gia tn epilogi tou onomatos
namesJComboBox = new JComboBox(names);//orizmos JCOMBO BOX
namesJComboBox.setMaximumRowCount(2);//na emfanizei 2 grammes
add(namesJComboBox);
namesJComboBox.addItemListener(new ItemListener() {
//xeirozome to simvan edw dhladh tn kataxwrisei ston fakelo
public void itemStateChanged(ItemEvent event) {
//prosdiorizoyme an eina epilegmeno to plaisio elegxou
if (event.getStateChange() == ItemEvent.SELECTED) {
name = (names[namesJComboBox.getSelectedIndex()]);
// writer.newLine();
setVisible(true);
}
}
}); //telos touComboBOx
//dimioutgw pediou keimenou me 10 sthles gia thn kathe epilogh kai veveonomaste oti tha mporoume na ta epe3ergasoume kanontas ta editable
text1 = new JTextField("Amount",10);
add(text1);
text2 = new JTextField("Description",10);
add(text2);
text3 = new JTextField("Order Number",10);
add(text3);
TextFieldHandler handler = new TextFieldHandler();
text1.addActionListener(handler);
text2.addActionListener(handler);
text3.addActionListener(handler);
//private eswterikh clash gia ton xeirismo twn events twn text
//button kataxwrisis
okJbutton=new JButton("Καταχώρηση");
add(okJbutton);
ButtonHandler bhandler=new ButtonHandler();
okJbutton.addActionListener(bhandler);
Order order=new Order(name,amount,description,number);
Order.addOrders(name,amount,description,number);
}
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent bevent ){
JOptionPane.showMessageDialog(addSalesMan.this,String.format("Η Καταχωρηση ήταν επιτυχής",bevent.getActionCommand()));
}
}
private class TextFieldHandler implements ActionListener {
//epe3ergasia twn simvantwn me kathe enter t xrhsth
public void actionPerformed(ActionEvent evt) {
String amount,description,number;
amount=text1.getText();
description=text2.getText();
number=text3.getText();
text1.selectAll();
text2.selectAll();
text3.selectAll();
}
if(evt.getSource()==text1 && evt.getSource()==text2 && evt.getSource()==text3){
JOptionPane.showMessageDialog(addSalesMan.this,String.format("Η Καταχωρηση ήταν επιτυχής",evt.getActionCommand()));
}
}
//actionperformed telos
//ean o xrhsths patisei enter sthn kathe epilogh antistixi kataxwrisi sto
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new addSalesMan().setVisible(true);
}
});
}
}
The writers are in another class. Here is the relevant code:
public static void addOrders(String name,String amount,String description,String o_number){
FileOutputStream fout;
try {
FileWriter fstream = new FileWriter("Orders.txt");
if(name!=null){
BufferedWriter out = new BufferedWriter(fstream);
out.write(name);
out.write(amount);
out.write(description);
out.write(o_number);
out.write("\t\n");
out.close();
}
} catch (IOException e) {
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
It looks like the main problem is that you are calling Order.addOrders() in your constructor. Instead, you should call it when a user chooses to save it's selection. I assume you would like this to happen when the user presses the button. So the code should be added in the button's ActionListener.
What you might need to try is flushing and closing the writer when a user closes your frame.
Add the following to the constructor of your frame:
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
writer.flush();
writer.close();
}
});
The above code will flush and close the writer when a user closes the frame.
Your code is unclear, so I'm not sure where the writer variable is declared, I'm just assuming it is a class level variable.
Also, you need to open your file in 'append' mode if you want to add lines to the file instead of overwriting it every time. This can be achieved through the following:
new FileWriter(yourFilePath, true); // set append to true

Categories