2

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?

Kyle
  • 1,463
  • 1
  • 15
  • 40
  • 2
    Instead `output = sc.next();` use `output = sc.nextLine();`. – SatyaTNV Feb 18 '16 at 10:57
  • @Satya it worked, thanks dude/dudette +1 – Kyle Feb 18 '16 at 11:01
  • 2
    Avoid using `null` layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify – MadProgrammer Feb 18 '16 at 11:01
  • 1
    `KeyListener` is not your best choice with text components, instead, you should use a `ActionListener` to monitor for the [Enter] key or a `DocumentLstener` to listen for changes to the document or a `DocumentFilter` to filter what the field will accept – MadProgrammer Feb 18 '16 at 11:03
  • 1
    While this doesn't have to do anything with the problem, I suggest you to read http://www.oracle.com/technetwork/java/codeconventions-135099.html - your methods should start with a lowercase letter. – neuromouse Feb 18 '16 at 11:04
  • @MadProgrammer oh that's awesome, thanks for all the amazing advice, I'm gonna fix them right now – Kyle Feb 18 '16 at 11:04
  • @MadProgrammer what do you mean by "an illusion within modern ui design"? – Kyle Feb 18 '16 at 11:08
  • 1
    @Mr.Derpinthoughton Because, to put it frankly, there are so many factors which affect a components size, you "might" think that you're getting control and it "looks" nice, but the moment the screen and/or the video card and/or resolution and/or the font size and/or DPI changes, all that "pretty" layout goes to garbage. Efficient UI layout is actually quite complex with no "real" solution, but many possibilities, the layout manager API supplied by Swing is just one. iOS just when through 4 years of "redesign", introducing auto layouts, because they originally only had two screen sizes :P – MadProgrammer Feb 18 '16 at 11:12
  • On a minor issue, you should close your Scanners instead of suppressing warnings, and it's better to let exceptions bubble up to the calling methods instead of putting printStackTrace everywhere. – Klitos Kyriacou Feb 18 '16 at 11:16
  • @MadProgrammer So, just to clarify, I should detect the screen's properties like width and height and then base my JFrame on that, making my JFrame kind of "Responsive"? – Kyle Feb 18 '16 at 11:17
  • @Mr.Derpinthoughton More to the point, you should rely on the workings of the layout management API, which Swing has been designed to work around, to make many of these decisions for you. Using `JFrame#pack` will, taking into consideration the requirements of the contents frame (as described by the various layout managers you might be using) and the frame decorations been used, pack the window "around" the content. This is a good start – MadProgrammer Feb 18 '16 at 11:21
  • @MadProgrammer Oh that would come in handy, I'm gonna do some research, thanks for helping and advising really :P – Kyle Feb 18 '16 at 11:23

1 Answers1

4

Instead

output = sc.next(); 

use

output = sc.nextLine();

Reference: Scanner#next() vs Scanner#nextLine()

Community
  • 1
  • 1
SatyaTNV
  • 4,053
  • 3
  • 13
  • 30