Write user input to a text file in Java [duplicate] - java

I want to create a simple stand-alone application that will take some input from user (some numbers and mathematical functions f(x,y...)) and write them to a file. Then with the help of this file I will run a command.
Basic ingredients that I need:
-- JTextArea for users input.
-- ButtonHandler/ActionListener and writing of the input to a (txt) file
-- ButtonHandler/ActionLister to execute a command
What is the best way to do it?
A current running code that I have (basically a toy) - which does not write anything, just executes - is:
import java.applet.*;
import java.lang.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dialog;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;
import java.util.*;
import java.io.BufferedWriter;
public class Runcommand3
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
//JApplet applet = new JApplet();
//applet.init();
final JFrame frame = new JFrame("Change Backlight");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
frame.add(panel);
JButton button = new JButton("Click me to Run");
button.setBounds(55,100,160,30);
panel.add(button);
frame.setSize(260,180);
frame.setVisible(true);
//This is an Action Listener which reacts to clicking on the button
button.addActionListener(new ButtonHandler());
}
}
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
double value = Double.parseDouble(
JOptionPane.showInputDialog("please enter backlight value"));
//File theFile = new File("thisfile.txt");
//theFile.write(value);
String command = "xbacklight -set " + value;
try{Runtime run = Runtime.getRuntime();
Process pr = run.exec(command);}
catch(IOException t){t.printStackTrace();}
}
}
In the above example how can I write 'value' to a file? Then, how can I add more input (more textfields)? Can I do it in the same class or I need more?
My confusion comes (mainly but not only) from the fact that inside the ButtonHandler class I can NOT define any other objects (ie, open and write files etc).

This is the way I would write to a file. I will let you convert this code into your GUI for practice. See more on BufferedWriter and FileWriter
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
public class Files {
public static void main(String args[]){
System.out.print("Enter Text: ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("text.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.newLine();
writer.close();
System.err.println("Your input of " + text.length() + " characters was saved.");
} catch (Exception e) {
System.out.println("Error!");
}
}
}

For your second question, you may like to consider having a JTextField on your JFrame for the user to enter lines into instead of a JOptionPane. It's just a simple text box, and you can add the box's contents to the file every time the button is pressed:
public static void main(String[] args) {
JTextField myTextField = new JTextField();
// Your code, set size and position of textfield
panel.add(myTextField);
}
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String text = myTextField.getText();
myTextField.setText("");
new BufferedWriter(new FileWriter("text.txt")).write(text).newLine().close();
// the rest of your code
}
}

Related

Block input while JDialog is open

I've a program that, when I open an image with JDialog, the consoles freezes, as expected, but if I write on the console while frozen, the scanner will catch what I typed, after I close the image, the scanner will give me what I typed earlier. I tried to reset the scanner but it didn't work.
Here's an example:
import java.util.Scanner;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Program
{
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
File file = new File("example.png");
try{
BufferedImage img = ImageIO.read(file);
ImageIcon icon=new ImageIcon(img);
JLabel lbl=new JLabel();
lbl.setIcon(icon);
JFrame frame=new JFrame();
JDialog jdialog = new JDialog(frame, name, true);
jdialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
jdialog.setSize(img.getWidth(), img.getHeight());
jdialog.setModal(true);
jdialog.add(lbl);
jdialog.setVisible(true);
}
catch (IOException e){
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
e.printStackTrace();
}
System.out.print("Type something: ");
String line = stdin.nextLine();
System.out.println("You typed "+line+", right?");
}
}
What I wanted to do:
(Show image)
User type: hello
(User closes image)
Type something:
User type: bye
You typed bye, right?
What happens:
(Show image)
User type: hello
(User closes image)
Type something: hello
You typed hello, right?

Importing a whole text file in a JFrame

I am kinda new to Java. I am creating a simple program to read a text file and put its contents into text area in a java swing frame. My file looks like this
Hello World!
What a beautiful World!
For the java frame I created a button and an action for the button to import the text from the text file into the text area when clicked. The problem is that the program only reads the second line of the text file "What a beautiful world!" I know it is probably a tiny stupid mistake, but I couldn't figure it out. here is my code for the class
import java.io.*;
import java.util.*;
public class JavaGui {
Scanner scnr;
static String fileText;
public void openfile(){
try{
scnr = new Scanner(new File("C:\\Users\\13195\\New JavaGui\\abc.txt"));
}
catch (FileNotFoundException e){
System.out.println("File Not Found. Try Again!");
}
}
public void readfile(){
while (scnr.hasNextLine()){
fileText = scnr.nextLine();
System.out.println(fileText);
}
scnr.close();
}
}
And here is the class with main method:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GuiFrame implements ActionListener {
private JTextArea jtxt = new JTextArea(30, 30);
private JFrame fr = new JFrame("Framework");
private JButton btn = new JButton("View Text");
static String t;
public GuiFrame(){
fr.add(jtxt);
btn.addActionListener(this);
fr.add(btn);
//Frame
fr.setLayout(new FlowLayout());
fr.setSize(50,50);
fr.setVisible(true);
}
public static void main(String[] args) {
new GuiFrame();
JavaGui fr = new JavaGui();
fr.openfile();
fr.readfile();
t = JavaGui.fileText;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn){
jtxt.setText(t);
}
}
}

Display file contents in a TextArea

Ok so I will try to make this as understandable as possible.
I have created a simple GUI with an "open" button and a textArea (along with other stuff but that's not important right now). Basically I am creating a method that when I click the Open button it displays the contents of the file in the textArea.
I believe 99% of the method I have written is correct but I keep getting a NullPointerException and I don't quite understand why. Hopefully my code will clear up any confusion on what I am asking, I will comment on the line of code where I get the exception. Here is my code:
Application class (Basic setup of my GUI):
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
public class Application extends JFrame {
public OutputPanel outPanel = new OutputPanel();
public BarcodePanel barPanel = new BarcodePanel();
public ButtonPanel btnPanel = new ButtonPanel();
public ReferencePanel refPanel = new ReferencePanel();
public Application() {
super("Book Processor");
this.setLayout(new BorderLayout());
btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
outPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
refPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
add(btnPanel, BorderLayout.NORTH);
add(outPanel, BorderLayout.WEST);
add(refPanel,BorderLayout.SOUTH);
}//end constructor
public static void main(String[] args) {
Application frame = new Application();
frame.setSize(1000,500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}//end main
}//end class
The next set of code is my ButtonPanel class(this is where I am having an issue) So I have an openFile method, that when I click the button it should display the contents of the file in the textArea. Again I receive a NullPointerException and I do not understand why. Here is the code for this class:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class ButtonPanel extends JPanel{
JButton btnOpen = new JButton("Open");
OutputPanel outPanel = new OutputPanel();
Scanner input;
public ButtonPanel() {
ButtonHandler handler = new ButtonHandler();
add(btnOpen);
btnOpen.addActionListener(handler);
}//end constructor
/**
* Method for displaying the file onto the textArea.
*
*/
private void openFile() {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result = chooser.showOpenDialog(this);
String fileName;
fileName = chooser.getSelectedFile().getAbsolutePath();
try {
Scanner input = new Scanner(Paths.get(fileName));
StringBuilder sb = new StringBuilder();
while(input.hasNextLine()) {
sb.append(input.nextLine()+ "\n");
}
outPanel.txtOutput.setText(sb.toString());//my issue is with this line right here
} catch (IOException e) {
e.printStackTrace();
}
finally {
input.close();
}
}//end readFile
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource()== btnOpen) {
openFile();
}
}//end actionPerformed
}//end actionlistener
}//end class
Here is my last class, OutputPanel, this class contains the JTextArea:
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class OutputPanel extends JPanel{
public JTextArea txtOutput = new JTextArea(20,50);
public OutputPanel() {
add(txtOutput);
}//end constructor
}//end class
How do I get the textArea to display the contents of the file? More importantly, why am I getting this exception and what can I do to fix it? Hopefully this makes as much sense as possible, and I really appreciate any and all input from you guys.
Your NullPointerException is actually been caused by
} finally {
input.close();
}
Because input is null (well, obviously). This is because you're shadowing the variable in the try-catch block
try {
Scanner input = new Scanner(Paths.get(fileName));
//...
} finally {
// This is null because the instance field has not been initialised
input.close();
}
A better solution would be to make use of the try-with-resources statement
try (Scanner input = new Scanner(Paths.get(fileName))) {
StringBuilder sb = new StringBuilder();
while (input.hasNextLine()) {
sb.append(input.nextLine() + "\n");
}
outPanel.txtOutput.setText(sb.toString());//my issue is with this line right here
} catch (IOException e) {
e.printStackTrace();
}
An even better solution would be to make use of JTextArea's ability to read the contents of a Reader, for example...
try (FileReader reader = new FileReader(chooser.getSelectedFile())) {
outPanel.txtOutput.read(reader, fileName);
} catch (IOException e) {
e.printStackTrace();
}
Now, before you ask why there's no content in your text area, the reason is because you create a new instance of OutputPanel in your ButtonPanel class, this has no relationship to the instance you created in your Application and added to the screen.
You will need to pass an instance of the OutputPanel to the ButtonPanel (via the constructor) so the references match up.
Personally, a better solution would be define an interface which had a read method which took a File. OutputPanel would implement this interface and ButtonPanel would require a reference to an instance of this interface. This decouples the code and prevents ButtonPanel from making unnecessary changes to the OutputPanel - because it's really not it's responsibility to do so - it's the OutputPanels responsibility to load the file and display it

jFileChooser to save file of selected tab

Ok so I have a text editor made that can so far create new files and open files using jFileChooser.
What I am trying to do is get the saving of files to work.
Everytime you add or open a few file it adds a new tab to the tabbedpane and the name will be either file 1 etc or the name of the file opened.
When you click the save button the save dialog opens up
int returnVal = fileChooser.showSaveDialog(this);
I want the name on the tab to be inserted to the name of file field.
Also how do I make a file of the current selected tabs textarea? I have tried this but its a no go:
int index = tabbedPane.getSelectedIndex();
Component c = tabbedPane.getComponentAt(index);
JTextArea a = (JTextArea) c;
System.out.println(a.getText());
File file = new File(a.getText());
fileChooser.setSelectedFile(file);
So I need to make a file of the string in the textArea I guess.
Following up #Andrew's answer, here is a snippet illustrating what he meant. I took the liberty to rather use a OutputStreamWriter than a FileWriter because this allows you to choose the charset used to write the file, which is something that you usually want to control and not rely on the "random" default platform charset.
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class TestTextArea {
private JTextArea textArea;
private JButton save;
protected void initUI() {
JFrame frame = new JFrame(TestTextArea.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea(24, 80);
save = new JButton("Save to file");
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
saveToFile();
}
});
frame.add(new JScrollPane(textArea));
JPanel buttonPanel = new JPanel();
buttonPanel.add(save);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setSize(500, 400);
frame.setVisible(true);
}
protected void saveToFile() {
JFileChooser fileChooser = new JFileChooser();
int retval = fileChooser.showSaveDialog(save);
if (retval == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file != null) {
if (!file.getName().toLowerCase().endsWith(".txt")) {
file = new File(file.getParentFile(), file.getName() + ".txt");
}
try {
textArea.write(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
Desktop.getDesktop().open(file);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestTextArea().initUI();
}
});
}
}
An easy way is to use JTextComponent.write(Writer). JTextArea extends JTextComponent.
For the Writer use a FileWriter.
You need to, some how associate the File that was opened with the tab. That way, you can look up the File associated based on the selected tab.
Something like HashMap<Component, File> for example

Java - JFrame not displaying its contents at all

First post for me. I'm a student in my first year of a comp science degree.
I was just building a basic GUI for an assignment and for some reason, which I cannot see for the life of me, one of the JFrames I have created, an instance of the Register Class displays completely blank when it is called from the Register buttons action listener in the Login Class...
I also have an individual main Class which contains the Main method and calls the Login Class. The Login Class JFrame works fine and as mentioned, the issues only occur with the Registration Class when it is called within the Login Class' Register button action listener. All other JFrames in the program work fine too.
I have attempted to call the Register Class direct from the main and it has the same issues, although I have attempted to reduce it to its most basic form and it still does not display anything aside from a blank uncolored JFrame.
Here is the code (Unfinished but working as is). I apologise for my sloppyness but I am a complete beginner.
Can anyone see what is wrong with it?
Thanks in advance!
package guitest;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class Register extends JFrame{
JButton regSubmit = new JButton("Submit");
JTextField email = new JTextField();
JTextField name = new JTextField();
JTextField Address1 = new JTextField();
JTextField Address2 = new JTextField();
JPasswordField password1 = new JPasswordField();
JPasswordField password2 = new JPasswordField();
String nameTxt = email.getText();
String passTxt = password1.getText();
String info = "";
FlowLayout layout1 = new FlowLayout();
public void Reg(){
this.setTitle("La Volpe Registration");
this.setLayout(layout1);
this.add(Address1);
this.add(Address2);
this.add(email);
this.add(password1);
this.add(password2);
this.add(name);
this.add(regSubmit);
this.getContentPane().setBackground(Color.green);
this.setSize(370, 160);
regSubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
regSubmitActionPerformed(evt);
}
private void regSubmitActionPerformed(java.awt.event.ActionEvent evt) {
String name = email.getText();
String pass = password1.getText();
String info = "";
System.out.println("registering...");
boolean eof;
try{
// Create file
FileWriter file = new FileWriter("\\regdata.txt");
BufferedWriter out = new BufferedWriter(file);
out.write("\n"+nameTxt+", "+passTxt);
}
catch (Exception e){
}
}
});
this.setVisible(true);
}
}
And the class that links to it...
package guitest;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
/**
* #author david
*/
public class Login {
JFrame loginFrame = new JFrame();
Register reg3 = new Register();
JButton submit = new JButton("Submit");
JButton clear = new JButton("Clear");
JButton register = new JButton ("Register with Us");
JPasswordField pass = new JPasswordField(20);
JTextField email = new JTextField(20);
JLabel em = new JLabel("Email Address: ");
JLabel pw = new JLabel("Password: ");
String pathname;
String line;
String [] records = new String [1000];
int count = 0;
FlowLayout layout1 = new FlowLayout();
public Login(){
//Adds Email label and text field
loginFrame.add(em);
loginFrame.add(email);
//Adds password label and field
loginFrame.add(pw);
loginFrame.add(pass);
//Adds buttons
loginFrame.add(submit);
loginFrame.add(clear);
loginFrame.add(register);
loginFrame.getContentPane().setBackground(Color.green);
loginFrame.setLayout(layout1);
loginFrame.setSize(370, 160);
loginFrame.setTitle("La Volpe - Login");
submit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitActionPerformed(evt);
}
private void submitActionPerformed(java.awt.event.ActionEvent evt){
String emailadd = email.getText();
String password = pass.getText();
pathname = "\\regdata.txt";
boolean eof;
try{
FileReader file = new FileReader(pathname);
BufferedReader buff = new BufferedReader(file);
eof = false; // set the eof boolean to false
while (!eof){
line = buff.readLine();
if (line == null){ // test to see if the end of file has been reached
eof = true; // if the end of file has been found set the eof Boolean to true
}
else{
// end of file not reached so move the contents of the line to the records
//array
records[count] = line;
count ++;
System.out.println(line); // print out the new line input for error checking
}
}
buff.close();
}
catch (IOException e){
System.out.println("Error -- "+ e.toString());
}
boolean notTrue = false;
for (int i = 0; i < count; i++) {
if ((!notTrue)&&((emailadd + "," + password).equals(records[i]))) {
FoodSelectionMain loggedIn = new FoodSelectionMain();
loggedIn.setVisible(true);
}
}
if (!notTrue){
JOptionPane.showInputDialog("Please check your login "
+ "and try again. If you are a new user, please "
+ "register by pressing the 'REGISTER' button");
}
}
});
// TODO add your handling code here:
clear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearActionPerformed(evt);
}
public void clearActionPerformed(java.awt.event.ActionEvent evt){
email.setText(null);
pass.setText(null);
}
});
register.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
registerActionPerformed(evt);
}
public void registerActionPerformed(java.awt.event.ActionEvent evt){
reg3.setVisible(true);
System.out.println("Register pressed");
}
});
loginFrame.setVisible(true);
}
}
Try this,
in Register class, correct the constructor name to Register() from Reg().
Keep these few Guidelines in your mind before constructing a gui app
Create an object of the subclass of the container .
Consider all the components which goes in the container as instance variables.
Set these instance variable and event handling outside the constructor in methods, (ie setComponent(), setHandler().etc) but do these method invocations from constructor.
Now in main use this...
.
EventQueue.invokeLater(new Runnable() {
public void run() {
Myframe f = new Myframe();
f.setVisible(true);
}
}

Categories

Resources