Violet_82 89 Posting Whiz in Training

HI guys, I'm redoing my old photography website and I'm still at the very beginning of the project. Somewhere I saw a jquery bounce functionality implemented and I thought I'd do it for my website as well, so I downloaded all I needed from the jquery ui website and got it work. The good news is that it seems to work OK in every browser except in IE - I have 11 installed.
Now, the actual animation works, but what it does is every time the animation restarts (it runs all the time) the page jumps a bit to the top, not all the way though, just the size of the height of the arrow being animated. If it makes no sense, here is the URL and you can check yourself in IE:
http://antonioborrillo.co.uk/new_photography/home.html
If you click the animated arrow, the page scrolls down all the way till the navigation is visible but in IE it then scrolls back up so that the arrow appears again.
Now, the way I've implemented the functionality is very simple:

$(document).ready(function(){
    //animateArrow();
    bounce();
    var $banner = $(".contentWrapper");
    ...
    });//end of doc ready
function bounce(){
    $(".arrow").effect( "bounce", 3500, bounce);
}   

I was thinking whether a preventDefault would help here, but I'm not sure it's the right thing to do, fact is I don't quite understand why it behaves like that in IE. Needless to say I had a look on the net first, but I couldn't quite come …

Violet_82 89 Posting Whiz in Training

HI guys, the tiems has come for me to renew my photography site as it's really "dated", so much so that's it's not even responsive...eh eh. In anycase, I'm still at the design really, but I was thinking to have some sort of lightbox/slideshow plugin to display the pictures rather than creating my own, so I was wondering if anybody knows of or has used a decent responsive free plugin that I can look at. I had a look around of course, but I'd like to hear from people so they could tell me why they decided to use a specific plugin and not the other.
Any advice?
thanks

Violet_82 89 Posting Whiz in Training

cool thanks for that (sorry for the slow response been really busy with work and other things!)

Violet_82 89 Posting Whiz in Training

Thanks for that. Yes the code is cleaner now, you're right, but it's kind of difficult for me to get that separation because I do a console program first and then turn that into the proper GUI application. Also, another thing to say is the way I was taught - which it was probably wrong I can see now :-) - which is, having a file (xxxTest.java) that takes care of the GUI window only and the rest goes into the other file

Violet_82 89 Posting Whiz in Training

OK cool, thanks for all your help and guidance with it, full source code here:
SentenceRecorder.java

/*SentenceRecorder.java
takes a sentence or word as input and saves it on text file. Every new word/sentence is appended at the end of the file
*/
import javax.swing.event.*;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import static java.awt.GridBagConstraints.*;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Dimension;
import java.io.File;


import java.nio.file.*;//for readAllLines()
import java.nio.file.Paths;//used to get the path of the file
import java.util.ArrayList;//to work with the array list to save the sentences in an ArrayList 
import java.util.List;
import java.util.Collection;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import java.util.Scanner;
import java.io.FileWriter;
import java.lang.SecurityException;//if no permission to write to file
import java.io.FileNotFoundException;//if the file can't be created
import java.io.IOException;
import java.util.Properties;//to get working directory
import java.io.BufferedWriter;

public class SentenceRecorder extends JFrame{   
    private JLabel instructions;
    private JLabel searchInstructions;
    private JButton submit;
    private JButton search;
    private GridBagLayout gbLayout;
    private JButton clear;
    private JTextArea input;
    private JTextArea searchResults;//displays the search results
    private String stringInput;
    private List< String > allSentences = new ArrayList< String >();//stores all the sentences in the file
    private String filePath;
    private String fileName;
    private JTextField searchCriterium;
    private File file;
    private BufferedWriter fileWriter;
    private String workingDir;
    private String separator;
    private Scanner scannerInput;//to input data into the file
    private Scanner scannerOutput;//to output data from the file
    private final static Charset ENCODING = StandardCharsets.UTF_8;
    public SentenceRecorder(){
        super("List of sentences to remember");
        searchCriterium = new JTextField();
        separator = System.getProperty("line.separator");//getting the system-dependent separator       
        workingDir = …
Violet_82 89 Posting Whiz in Training

OK I see, thanks for that. It works, but can I ask you, you used matchedSentences.add(" no matches found"); and it works, I attempted this instead searchResults.setText("No matching found"); and it doesn't work: why is that? all I was doing was attempting to change the text inside the textArea, is that because it gets cleared out just after the message is entered? It's not hugely important, just curious, because my first instinct was to add a message to the text box rather than adding it to the List

Violet_82 89 Posting Whiz in Training

OK that worked, thanks, getSentenceContaining now has a new return statement :

else{//necessary, otherwise compiler complains no return statement
            return new ArrayList< String >();
        }

and I'm clearing the text area before appending anything else.

And finally I'm going to have one last attempt to get you thinking about names.

Yep, sorry, name changed to displayMatchedSentences.
This is how my application looks like now:
with_search.jpg
and it all works.
Not sure whether it's a good idea or not, but I was thinking to perhaps add a message to the results textArea saying "No matches" if no matches are found. But that got me to look at the code a bit more carefully and I spotted something odd.

public SentenceRecorder(){      
        ...
        searchCriterium.getDocument().addDocumentListener(new DocumentListener(){
            public void changedUpdate(DocumentEvent e){
                //System.out.println("changedUpdate");
            }
            public void removeUpdate(DocumentEvent e){              
                displayMatchedSentences(getSentenceContaining(getKeyword()));
            }
            public void insertUpdate(DocumentEvent e){              
                displayMatchedSentences(getSentenceContaining(getKeyword()));               
            }
        });
    }//end of constructor
 public List<String> getSentenceContaining(String keyword){// search for keyword and return the whole string/s       
        if(keyword.length() > 3){
            System.out.printf("\n\nKeyword is %s. Sentence(s) containing the keyword:\n", keyword);
            List< String > matchedSentences = new ArrayList< String >();//stores all the matched sentences in the file            
            for(String toFind : allSentences){//loop thru all sentences
                if(toFind.contains(keyword)){//find the ones with matching the keyword              
                    matchedSentences.add(toFind);//add the found sentences to the List                                  
                }
            }           
            if(matchedSentences.size() == 0){//no matches
                System.out.println("None found matching the keyword");
                searchResults.setText("No matching found");
            }
            else if(matchedSentences.size() > 0){
                printSentenceArray(matchedSentences);
            }
            return matchedSentences;
        }
        else{//necessary, otherwise compiler complains no return statement
            return new ArrayList< String >(); …
Violet_82 89 Posting Whiz in Training

Eh eh, it's easy to do but a little more complicated to achieve :-).
The principle sort of works but it doesn't execute that well. So, let's look at some code. I've arranged everything into methods so I can call things when I need them.
First of all two extra functions, one just returning the content of the search box (where users type the keyword) and another one looping through the returned set of matched strings (this last functions you'll notice has some problems: I need to append sentences to the JTextArea and therefore I used the append method but because the function gets called at every character typed I end up with loads of results):

public String getKeyword(){//get keyword from input field
        String text = searchCriterium.getText();
        return text;
    }
    public void getMatchedSentence(List< String > matchedSent){//loops thru matched sentences
        for(String theSentence : matchedSent){
            searchResults.append(theSentence + separator);
        }

    }

Then this, which gets thing started:

searchCriterium.getDocument().addDocumentListener(new DocumentListener(){
            public void changedUpdate(DocumentEvent e){
                //System.out.println("changedUpdate");
            }
            public void removeUpdate(DocumentEvent e){
                //System.out.println("removeUpdate");               
                //searchResults.setText(getSentenceContaining(getKeyword()));
                getMatchedSentence(getSentenceContaining(getKeyword()));
            }
            public void insertUpdate(DocumentEvent e){
                //System.out.println("insertUpdate");
                getMatchedSentence(getSentenceContaining(getKeyword()));
                //searchResults.setText(getSentenceContaining(getKeyword()));
            }
        });

Now, other than the obvious problems, there is something really weird going on. I have a filter, let's call it like that, inside the getSentenceContaining function so that if the keyword is less than 4 it returns null:

public List<String> getSentenceContaining(String keyword){
        if(keyword.length() > 3){
        ...
        }
        else{//necessary, otherwise compiler complains no return statement
            return null;
        }
    }

But this is causing enormous issues, not sure …

Violet_82 89 Posting Whiz in Training

All right, I think I got it sorry, it should be something like the below (this seems to satisfy the abstract class at least) and apparently I have to use all the methods:

searchCriterium.getDocument().addDocumentListener(new DocumentListener(){
            public void changedUpdate(DocumentEvent e){
                System.out.println("changedUpdate");
            }
            public void removeUpdate(DocumentEvent e){
                System.out.println("removeUpdate");
            }
            public void insertUpdate(DocumentEvent e){
                System.out.println("insertUpdate");
            }
        });

Now, I think I can call my function from within those methods (by the way, not sure when changedUpdate is fired, the API is a bit cryptic saying that "Gives notification that an attribute or set of attributes changed.")
So no event handlers as I thought I had to do at the beginning

Violet_82 89 Posting Whiz in Training

Thanks, so is this implemented the usual way with a class and handler or by just creating a listener and adding to the field - which is what I've done?
Trouble is, shouldn't I instantiate a DocumentListener class?

...
import javax.swing.event.*;
...
public class SentenceRecorder extends JFrame{
    ...
    private JTextField searchCriterium;
    ...
        public SentenceRecorder(){
        super("List of sentences to remember");
        searchCriterium = new JTextField();
        ...
        DocumentListener typeListener = new DocumentListener();
        searchCriterium.getDocument().addDocumentListener(typeListener);
        }
}

Oh I looked at your application by the way, you're right, the live search is nice and it looks a bit like magic :-)

EDIT: ah wait, perhaps something like this instead:

searchCriterium.getDocument().addDocumentListener(new DocumentListener()){
    //my methods
}
Violet_82 89 Posting Whiz in Training

The document listener will be called whenever the user changes the contents of the entry field, reagrdless of how he did it.

OK, that's cool if you already have something in it, but what I think it's not clear to me, sorry for that, is what happens the first time you type something in. The first time there is an empty string in it, so, back to my "house" example again, I type "hous" and the event is fired (because I have a filter of minimum 4 words), correct? The I keep typing and add an "e" so that I have "house" and getSentenceContaining(String keyword) is called again and so on every time the string is modified. So basically the key listener, and mouse listeners (I know you pasted some pseudo code but I suppose I need to have a better look at lsteners again especially when it's key, mouse etc) need to be added to the input field where I type the search keyword in.

Violet_82 89 Posting Whiz in Training

getting the char and adding it to the search text won't work - consider backspace, or arrow keys for example. You have to use the current text in that field, which actually makes the code simpler.

Good point, but how does the application know that it is ready to process the text in that field unless I have a search button of some sort? Like, say I want to search for "house": whether I type "hou" or "hous" or "house" on way or another I need to tell the application to run the search. The more I think about the functionality, the more I'm getting persuaded that it might be better to type the search term, then have a search button you can hit when you typed your keyword and performed the search, rather than doing n automated thing as not only is simple, but also more intuitive as the user is in full control of what happens. What do you reckon?

Violet_82 89 Posting Whiz in Training

Thanks, I'implemented it, and seems to be working, but I think there are some mistakes in the code you pasted, as you said (String s : toPrint) { but your code at the bottom says for(List<String> sentence : toPrint) { :-)
Anyway, all good. Now, about the implementation of the search in the GUI, we said there won't be any search button. I'm thinking about having 2 more TextAreas ( in addition to the one I already have where I type the text that goes into the file of course): in the first one (let's call it searchCriterium) I can type the search criterium (word or sentence) and the second one (let's call it searchResult) will instead display the results in real time.
In terms of code this is roughly what I was thinking should happen:

if the focus is on the SearchCriterium TextArea{
    add a keyListener
    store keystroke text in String keyword
    String matchedResult = getSentenceContaining(keyword);
    copy matchedResult into TextArea        
}

I've added an if statement to the getSenteceContaining function as well, so that it reads:

public List<String> getSentenceContaining(String keyword){// search for keyword and return the whole string/s
        System.out.printf("\n\nKeyword is %s. Sentence(s) containing the keyword:\n", keyword);
        if(keyword.length() > 3){...}
}

And that should make sure that I don't return every single record on the file. How does that sound?

Violet_82 89 Posting Whiz in Training

If you're interested I have a few very small suggestions:

Sure I don't see why not.
-I've changed the name of the function from searchWord to getSentenceContaining;
-removed instanceFound and replaced it with size:
if(matchedSentences.size() == 0){//no matches

            System.out.println("None found matching the keyword");          
        }
        else if(matchedSentences.size() > 0){
            printSentenceArray(matchedSentences);
        }

-The print functionality, printSentenceArray that is, is not there to stay really, it's just a debugging tool, for me to see what gets printed, so it will go. I generally don't like for enhanced loops, it feels like they're hiding stuff from me as opposed to normal for loops, but again, I'm not knowledgeable enough to have a reason not to use them, so if you say they're better, fair enough. Still on the print method: I don't think I'll change it for the reason above, still, if I read correctly you're suggesting this:

public void printSentenceArray(List< String > toPrint){
    if(toPrint == null){
        return null;
    }
    else{
            System.out.println("Array contains: ");
            for(List<String> sentence : toPrint)         
                System.out.println(sentence.get(count));
            }
        }       
    }
Violet_82 89 Posting Whiz in Training

cool, thanks

Violet_82 89 Posting Whiz in Training

OK cool, so I quickly changed the function to have another List which I didn't bother declaring in the constructor but it's local to the function and contains a list of matches and that returns that list and I've modified the logic of printing information, so that now I call a printing function, like so:

public List<String> searchWord(String keyword){// search for keyword and return the whole string/s
        System.out.printf("\n\nKeyword is %s. Sentence(s) containing the keyword:\n", keyword);
        List< String > matchedSentences = new ArrayList< String >();//stores all the matched sentences in the file
        int instanceFound = 0;
        for(String toFind : allSentences){
            if(toFind.contains(keyword)){
                instanceFound++;
                matchedSentences.add(toFind);//add the found sentences to the List
                //System.out.println(toFind);               
            }
        }
        if(instanceFound == 0){//no matches
            System.out.println("None found matching the keyword");          
        }
        else if(instanceFound > 0){
            printSentenceArray(matchedSentences);
        }
        return matchedSentences;        
    }

    public void printSentenceArray(List< String > toPrint){
        if(!(toPrint == null)){//to avoid NPE
            System.out.println("Array contains: ");
            for(int count = 0; count < toPrint.size(); count++){
                //System.out.printf("%s", toPrint.get(count));
                System.out.println(toPrint.get(count));
            }
        }       
    }

I'll code the event handling in now, if we're all happy with the above

Violet_82 89 Posting Whiz in Training

I don't think I have a browser extension - not at my laptop at the moment - but I do have avast installed. Yeah, hopefully it's just nothing!
thanks

Violet_82 89 Posting Whiz in Training

That's cool, happy to follow your suggestion.
So, to do that the searchWord method needs some changes, like I need to create another array of strings that can take in the sentences that I want to display as results because the way I display them now is simply looping through the allSenteces List and then change the type from String to List<String> and return a List item :

public String searchWord(String keyword){// search for keyword and return the whole string/s
        System.out.printf("\n\nKeyword is %s. Sentence(s) containing the keyword:\n", keyword);
        int instanceFound = 0;
        for(String toFind : allSentences){
            if(toFind.contains(keyword)){
                instanceFound++;
                System.out.println(toFind);
            }
        }
        if(instanceFound == 0){//no matches
            System.out.println("None found matching the keyword");          
        }
        return allSentences;        
    }
Violet_82 89 Posting Whiz in Training

HI, yes you're right, I should do a bit of tidying up:
-I removed - to the best of my knowledge - needless code;
-changed findInArray to getSentenceList;
-parametized public List<String> getSentenceList(String theFileName) so fileName is passed to it;
-change the keyword string to test for:1) value that returns more than one sentence, and that works OK (I tried that before in fact); 2) value not found, and that prompted me to make some changes: I added an int control variable whose value is increased everytime there is a match. If there is no match its value remains 0 and the message "None found matching keyword" is printed. Update method here:

public String searchWord(String keyword){// search for keyword and return the whole string/s
        System.out.printf("\n\nKeyword is %s. Sentence(s) containing the keyword:\n", keyword);
        int instanceFound = 0;
        for(String toFind : allSentences){
            if(toFind.contains(keyword)){
                instanceFound++;
                System.out.println(toFind);
            }
        }
        if(instanceFound == 0){//no matches
            System.out.println("None found matching the keyword");          
        }
        return keyword;     
    }

Obviously you will want it to return a List or array of matching sentences

Just thinking, why would I return that? The GUI ill display the sentences in the textArea and I should be able to insert those in it directly from the method, like the List contains already all the sentences, so all I have to do, I would think, is to loop through it, as I do now, and insert those sentences into the textArea. So the current search method returns a String

public …
Violet_82 89 Posting Whiz in Training

OK done and it works nicely, and the search as well:

public SentenceRecorder(){
        super("List of sentences to remember");
        ...     
        fileName = "sample.txt";        
        file = new File(workingDir, fileName);
        allSentences = fileInArray();//copying content of file in arrayList
        printSentenceArray();
        searchWord("sentence");
        ...       
 }
public List<String> fileInArray(){//save file text into array        
        Path path = Paths.get(fileName);        
        if(!(Files.isReadable(path))){
            System.out.println("The file is empty. You need to save something in it first.");//to be printed in the textArea
            return null;            
        }       
        try{
            return Files.readAllLines(path, ENCODING);          
        }
        catch(IOException ioexception){
            System.err.println("General Error with IO");
            ioexception.printStackTrace();
            System.exit(1);
        }
        return null;        
    }
    public void printSentenceArray(){
        if(!(allSentences == null)){//to avoid NPE
            System.out.println("Array contains: ");
            for(int count = 0; count < allSentences.size(); count++){
                //System.out.printf("%s", allSentences.get(count));
                System.out.println(allSentences.get(count));
            }
        }       
    }
    public String searchWord(String keyword){// search for keyword and return the whole string/s
        System.out.printf("\n\nKeyword is %s. Sentence(s) containing the keyword:\n", keyword);
        for(String toFind : allSentences){
            if(toFind.contains(keyword)){
                System.out.println(toFind);
            }
        }       
        return keyword;     
    }

Now the searching functionality of course will change quite a bit when the GUI is implemented, but there is nothing I can do to emulate the functinality we discussed (the application starts returning results as soon as you begin typing), so I'll now create the GUI and implement the rest of the functionality

Violet_82 89 Posting Whiz in Training

Right, yes that makes more sense, here is the update method:

public List<String> fileInArray(){//save file text into array        
        Path path = Paths.get(fileName);        
        if(!(Files.isReadable(path))){
            System.out.println("The file is empty. You need to save something in it first.");//to be printed in the textArea
            return null;            
        }
        try{
            return Files.readAllLines(path, ENCODING);          
        }
        catch(IOException ioexception){
            System.err.println("General Error with IO");
            ioexception.printStackTrace();
            System.exit(1);
        }
        return null;        
    }

If there is no file in the folder, which would be when you run the application the first time, you get this in the console (and the application doesn't run at all): I believe that's correct

G:\JAVA\GUI\2015\createFrames\files\withSearch>java SentenceRecorderTest
The file is empty. You need to save something in it first.
Array contains:
Exception in thread "main" java.lang.NullPointerException
        at SentenceRecorder.printSentenceArray(SentenceRecorder.java:187)
        at SentenceRecorder.<init>(SentenceRecorder.java:72)
        at SentenceRecorderTest.main(SentenceRecorderTest.java:5)
G:\JAVA\GUI\2015\createFrames\files\withSearch>

The reason why you get "array contains:" is because the function that prints the array

public void printSentenceArray(){
        System.out.println("Array contains: ");
        for(int count = 0; count < allSentences.size(); count++){
            //System.out.printf("%s", allSentences.get(count));
            System.out.println(allSentences.get(count));
        }           
}

runs anyway as it is called from inside the constructor:

public SentenceRecorder(){
        ...
        fileName = "sample.txt";        
        file = new File(workingDir, fileName);
        allSentences = fileInArray();//copying content of file in arrayList
        printSentenceArray();
        setLayout(gbLayout);//set layout of jframe
        ...
}//end of constructor

You just need to load allSentences once, when you initialise the program.

yep that's done in the constructor above allSentences = fileInArray();

searching does not belong anywhere in that code.

I have a separate function for that, still haven't coded much as yet, but the idea …

Violet_82 89 Posting Whiz in Training

OK thanks

Violet_82 89 Posting Whiz in Training

eh, darn formatting! You're absolutely right, it's printing OK now :-), with System.out.println(allSentences.get(count));
I was also reflecting on something.
Basically, I've added the isReadable() method, but the compiler still wants me to have to exception as it came back with an error:

G:\JAVA\GUI\2015\createFrames\files\withSearch>javac *.java
SentenceRecorder.java:163: error: unreported exception IOException; must be caught or declared to be thrown
                        return Files.readAllLines(path, ENCODING);
                                                 ^
1 error

so, the code is quite clunky now:

public List<String> fileInArray(){//save file text into array            
        Path path = Paths.get(fileName);            
        if(Files.isReadable(path)){//if the file exists etc
            try{
                return Files.readAllLines(path, ENCODING);
                //searchWord("sentence");
            }
            catch(IOException ioexception){
                System.err.println("General Error with IO");
                ioexception.printStackTrace();
                System.exit(1);
            }

            return null;            
        }
        else{
            System.out.println("The file is empty. You need to save something in it first.");
            return null;
        }           
    }
    public void printSentenceArray(){
        System.out.println("Array contains: ");
        for(int count = 0; count < allSentences.size(); count++){
            //System.out.printf("%s", allSentences.get(count));
            System.out.println(allSentences.get(count));
        }           
    }

It seems overkill to have an if statement with a try/catch block and then an else statement

if(Files.isReadable(path)){
    try{...}
    catch{...}
}
else{...}

And moreover, I need to think how I'm gonna fit the keyword functionality in between. I was thinking to call a searchWord() method from somewhere there, but the structure is making it rather difficult, maybe I should call it inside the try block before return Files.readAllLines(path, ENCODING);

Violet_82 89 Posting Whiz in Training

Uhm, no when I print the list in the console there is no space:

G:\JAVA\GUI\2015\createFrames\files\withSearch>java SentenceRecorderTest
Array contains:
jojosentence 1This is another sentenceAnd another oneAnd more

That means that if you have written your sentences to the file with sensible separators then readAllLines will give you each sentence in it's own entry in the List

Well I have, if you remember I'm getting the system separator, but for some reasons it doesn't seem to be working in the console. I don't know whether when I print it inside a textfield it will make any difference though, maybe it will. Let's leave this now and see what happens when the file text is displayed in the text field.

use Files.isReadable to check that things are OK before trying to read the file. thus avoiding the exception.

Sounds good. Now I can code it in such a way that if Files.isReadable returns false will print a messagein the console, later I can display that message inside the textField.
I'll also try to implement the search now: pass a keyword and if found in the text return the sentence, will see how that goes

Violet_82 89 Posting Whiz in Training

readAllLines does indeed magically find the file, open it, read all its lines into a List, and closes the file again.

Ahah, I love that!

You get FileNotFound or NoSuchFileException because Java can't find your file. EIther it doesn't exist

Oh, that's it, the file doesn't exist! When I created the new folder for the version of the project "with search", I've copied the java files only and removed the generated text file instead, because it would be created when I run the application, well, that was the case when I run the old application without the search. In the new version, with the search, the application tries to access the file even if it hasn't been created as yet. Well, that might be a problem then, because it means that the first time you run the application, when the file still doesn't exist, if you press the search button (which I haven't added it as yet), it will try to find something in a file that doesn't exist. Now, as I haven't created the GUI as yet, I think it's OK now, in fact I've copied the old text file into the new folder and the application works (it returns the content of the file in the console as I wanted ) but I have to bear this in mind when the search button is in place.
One thing though, there is no line separator in the console output, everything runs together, and the …

Violet_82 89 Posting Whiz in Training

Right, thanks for the explanation. The trouble is that I must have read about 5-6 tutorials and all of them are different...I've created a brand new project now - let's forget for a minute the code in my previous post - I haven't added absolute anything to it and when I run I get already what I'd refer to as an empty GUI, presumably that is the "Scene", all stored inside an application package and a Main.java file. This one alone generates the GUI, so I presume this is the absolute minimum you get when you create any project

package application;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;


public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            BorderPane root = new BorderPane();
            Scene scene = new Scene(root,400,400);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Now, if I want to add anything to this application, like a proper GUI with a button for the sake of agument, do I create another package and inside that package a xxx.java with essentially pretty much the same content as above but with the extra code needed for the button, or do I add all that directly inside Main.java?

Violet_82 89 Posting Whiz in Training

Hi guys, so I'm starting with JavaFX using eclipse. I had a look at a few tutorials and the syntax seems quite different from other java projects I've done. Specifically, I'm a bit confused when it comes to add my code to the Eclipse project.
I've just started very soft, with a simple helloWorld, just to look at the syntax (this is the class I've created, all coming directly from eclipse ):

package myapp;
import javafx.application.Application;
import javafx.stage.Stage;
public class MyApplication extends Application {
    @Override
    public void start(Stage primaryStage) {     
    }
    public static void main(String[] args) {
        launch(args);
    }
}

Now, if I want to add just a statement, literally something as simple as like System.out.println("Hello world");, where is that supposed to go? Inside start presumably?
Also, there is another file in eclipse, called Main.java and that too has a main and a start methods?

Violet_82 89 Posting Whiz in Training

To get round that you can just stick a return null; after your System.exit. That will keep the compiler happy.

OK done.

ps What's that unused Scanner doing in there?

The idea was that, as I used a scannerInputto write to file, I'd use a scannerOutput to read from file, but it hasn't been necessary so far, so I'll comment that out for now, might be useful later, not sure. To be completely honest with you, I don't understand how we've opened the file and copied the info over to the List. I thought that this Path path = Paths.get(fileName); was just retrieving the file name and this return Files.readAllLines(path, ENCODING);merely reading through the files, so evidently this line opens also the files magically, or I simply missed it altogether, which, you know, it might be entirely possible since the compiler now is throwing an awful lot of runtime errors at me:

G:\JAVA\GUI\2015\createFrames\files\withSearch>java SentenceRecorderTest
General Error with IO
java.nio.file.NoSuchFileException: sample.txt
        at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
        at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
        at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
        at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
        at java.nio.file.Files.newByteChannel(Unknown Source)
        at java.nio.file.Files.newByteChannel(Unknown Source)
        at java.nio.file.spi.FileSystemProvider.newInputStream(Unknown Source)
        at java.nio.file.Files.newInputStream(Unknown Source)
        at java.nio.file.Files.newBufferedReader(Unknown Source)
        at java.nio.file.Files.readAllLines(Unknown Source)
        at SentenceRecorder.fileInArray(SentenceRecorder.java:153)
        at SentenceRecorder.<init>(SentenceRecorder.java:71)
        at SentenceRecorderTest.main(SentenceRecorderTest.java:5)

If I put back the scannerOutput line with the try and catch block I only get a "can't open the file" error instead.
I presume that one way or another we have to open the file before copying the content over to a List?
Here is the …

Violet_82 89 Posting Whiz in Training

OK cool, thanks.
Talking about return types, in here the compiler complained of a uncaught exception - I'm afraid I'm not terribly good with the exception, meaning that I'm never sure when to use them but in any case, I added one as requested:

try{
            return Files.readAllLines(path, ENCODING);
        }
        catch(IOException ioexception){
            System.err.println("General Error with IO");
            ioexception.printStackTrace();
            System.exit(1);
        }

but it's now saying

G:\JAVA\GUI\2015\createFrames\files\withSearch>javac *.java
SentenceRecorder.java:160: error: missing return statement
        }
        ^
1 error

Now, readAllLines() returns a List<String> so both the signature and the returned data are compatible, that leaves me with only one explanation: is it wrong to include a return statement inside a try block?
Sorry, that's how the whole method looks like now:

public List<String> fileInArray(){//save file text into array
        try{
            scannerOutput = new Scanner(new File(workingDir, fileName));
        }
        catch(FileNotFoundException fileNotFoundException){
            System.err.println("Error opening the file");
            System.exit(1);
        }
        Path path = Paths.get(fileName);
        try{
            return Files.readAllLines(path, ENCODING);
        }
        catch(IOException ioexception){
            System.err.println("General Error with IO");
            ioexception.printStackTrace();
            System.exit(1);
        }
    }
Violet_82 89 Posting Whiz in Training

Yes, it is. importing Paths does not import Path. Why would it?

Right, I don't know why I thought that. Is there a general rule then that we should follow when using import statements, like when is it better to import only one or more than one classes as opposed to import them all with xxx.*?

Like in the case discussed above, I amended it to be import java.nio.file.*;, but how about this instead:

import java.nio.file.Files;//for readAllLines()
import java.nio.file.Paths;
import java.nio.file.Path;

Also, slightly different thing:

readAllLines returns a List<String> to that's how you should declare your return type and your receiving variable.

I think I need to change a few more things as well then, like, I declared allSentences as
private ArrayList< String > allSentences = new ArrayList< String >();
but that is wrong then, it should be private List< String > allSentences = new ArrayList< String >();
I've always thought, quite clearly erroneously, that ArrayList and List were effectively, if not the same thing, at least compatible types, meaing I could use them interchangeably.
Same with the method signature, it needs to be
public List<String> fileInArray(){...}
as opposed to
public ArrayList<String> fileInArray(){...}
Let me try and see if it works

Violet_82 89 Posting Whiz in Training

Ah...mmm that was a silly mistake...sorry about that.
The other error though seems a bit more...er, how to put it, difficult.
I'm importing the nio class import java.nio.file.Paths; and that seems to be enough to cover both Path and Paths, although Paths appears to be an interface, is that a problem?
From memory a "cannot find symbol" error occurs because an identifies is used without declaring, but here I'm declaring a variable of type Path when I use it, inside the - now amended - fileInArray() method:

public ArrayList<String> fileInArray(){//save file text into array
        try{
            scannerOutput = new Scanner(new File(workingDir, fileName));
        }
        catch(FileNotFoundException fileNotFoundException){
            System.err.println("Error opening the file");
            System.exit(1);
        }
        Path path = Paths.get(fileName);
        return Files.readAllLines(path, ENCODING);
        ...

So, could it be that path beeds to be declared as a private variable inside the constructor?

Violet_82 89 Posting Whiz in Training

To be honest I gave up, but I can give it a try again

Violet_82 89 Posting Whiz in Training

Sorry, didn't have much time to look at this. OK, I made some small changes, the idea was that before looping through all the sentences in the file, I'd copy them over onto an arraylist, but I'm getting some errors. I used the readAllLines method and , since I haven't modified the GUI as yet I wanted to print the array's elements in the console.
I've added the various import statements (full code available here http://pastebin.com/w86c2ZVi ):

import java.nio.file.Files;//for readAllLines()
import java.nio.file.Paths;//used to get the path of the file
import java.util.ArrayList;//to work with the array list to save the sentences in an ArrayList 
import java.util.List;
import java.util.Collection;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
...
private ArrayList< String > allSentences = new ArrayList< String >();//stores all the sentences in the file
private final static Charset ENCODING = StandardCharsets.UTF_8;
...
public SentenceRecorder(){
    allSentences = fileInArray();//copying content of file in arrayList
    printSentenceArray();
   }
public ArrayList<Object> fileInArray(){//save file text into array
        try{
            scannerOutput = new Scanner(new File(workingDir, fileName));
        }
        catch(FileNotFoundException fileNotFoundException){
            System.err.println("Error opening the file");
            System.exit(1);
        }
        Path path = Paths.get(fileName);
        return Files.readAllLines(path, ENCODING);

    }
    public void printSentenceArray(){
        System.out.println("Array contains: ");
        for(int count = 0; count < allSentences.size(); count++){
            System.out.printf("%s", allSentences.get(count));
        }

    }

but the compiler is complaining:

G:\JAVA\GUI\2015\createFrames\files\withSearch>javac *.java
SentenceRecorder.java:71: error: incompatible types
                allSentences = fileInArray();//copying content of file in arrayList
                                          ^
  required: ArrayList<String>
  found:    ArrayList<Object>
SentenceRecorder.java:151: error: cannot find symbol
                Path path = Paths.get(fileName);
                ^
  symbol:   class Path
  location: class SentenceRecorder
2 errors

G:\JAVA\GUI\2015\createFrames\files\withSearch>

I'm trying to copy the …

Violet_82 89 Posting Whiz in Training

Great! One thing though: at the moment I'm directing the emails to a hotmail email address, but that will change as soon as I get a new email address with the domain of the website - which will chage as well by the way. Everytime I get an email, it goes into the spam folder, even if I mark it to be "no spam": has this got something to do with this:
$mail->setFrom("test@gmail.com", "No reply");
thanks

Violet_82 89 Posting Whiz in Training

Right, I think I might have found the problem. Reading through the php manual, it appears that when I use the filter_input method I shouldn't put the first parameter (type) in quotes like this
$website = filter_input('POST', 'website', FILTER_SANITIZE_URL); but it should instead be $website = filter_input(INPUT_POST, 'website', FILTER_SANITIZE_URL);.
I changed all of them to be

if($_SERVER['REQUEST_METHOD'] == 'POST'){
        $firstName = filter_input(INPUT_POST, 'firstName', FILTER_SANITIZE_STRING);
        $lastName = filter_input(INPUT_POST, 'lastName', FILTER_SANITIZE_STRING);
        $emailAddress = filter_input(INPUT_POST, 'emailAddress', FILTER_SANITIZE_EMAIL);
        $message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING);
        $website = filter_input(INPUT_POST, 'website', FILTER_SANITIZE_URL);
        ...

And now the data in the email comes through OK, but please let me know if you think this amendment is right :-)
thanks

cereal commented: it's ok! +14
Violet_82 89 Posting Whiz in Training

Thanks for that. So I've added what you've suggested, but I run into a problem, I'm sure it's something I've done :-): Now, when I receive the email, the fields are empty, so the values I input in the form are not coming through, this is what I get in the email (it ws definitely working before, I checked that):

First Name: 
Last Name: 
Email address: 
Message: 
Website: 

I'm thinking perhaps I haven't implemented your code correctly, here's how my script looks now - I've basically wrapped almost everyting inside if($_SERVER['REQUEST_METHOD'] == 'POST'){:

<?php
    require 'PHPMailer-master/PHPMailerAutoload.php';
    //header('Content-Type: application/json');    
    //SMTP needs accurate times, and the PHP time zone MUST be set
    //This should be done in your php.ini, but this is how to do it if you don't have access to that
    date_default_timezone_set('Etc/UTC');    
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        $firstName = filter_input('POST', 'firstName', FILTER_SANITIZE_STRING);
        $lastName = filter_input('POST', 'lastName', FILTER_SANITIZE_STRING);
        $emailAddress = filter_input('POST', 'emailAddress', FILTER_SANITIZE_EMAIL);
        $message = filter_input('POST', 'message', FILTER_SANITIZE_STRING);
        $website = filter_input('POST', 'website', FILTER_SANITIZE_URL);            
        $mail = new PHPMailer(true);
        $mail->Timeout       =   30; // set the timeout (seconds)
        //$mail->isSMTP();
        $mail->SMTPAuth   = true;                   // enable SMTP authentication
        $mail->SMTPSecure = "tls";                  // sets the prefix to the servier
        $mail->Host       = "smtp.live.com";        // sets hotmail as the SMTP server
        $mail->Port       = 587;                    // set the SMTP port for the hotmail server
        $mail->Username   = "jasonattin@hotmail.co.uk";      // hotmail username
        $mail->Password   = "xxxxx";           // hotmail password
        //$mail->setFrom($emailAddress, $firstName . ' ' . $lastName);  
        $mail->setFrom("test@gmail.com", "No reply");       
        $mail->addAddress('jasonattin@hotmail.co.uk', 'Giasone Attinio');
        $mail->Subject = 'New request';
        //$mail->Body = $message . "\r\n\r\nWebsite: " . $website; …
Violet_82 89 Posting Whiz in Training

Well, the site was google.co.uk, as per screenshot, which is why I found it rather odd

Violet_82 89 Posting Whiz in Training

Hi guys, something a little strange has happened. While I browsed to google.co.uk home page I've seen a message flashing on the top left of the screen, it flashed literally for about half a second and after ctrl+f5 numerous times I managed to get a screenshot and it says "Online Security this site has no rating".
I saw that message in windows chrome, I'm logged in, I haven't checked in Ubuntu, but it is definitely the first time I saw it. I'm running a scan with malaware byte just in case, and a google search for that hasn't really revealed much.
Any idea what it is, and why it is showing on the google home page? Here is a screenshot by the way:
googleMSG.jpg

Violet_82 89 Posting Whiz in Training

Thanks for looking at that cereal. Needless to say, I'm more than happy to fix the problems if you tell me how :-).
I'm currently integrating the various scripts onto the main website, just to make sure it works, and then I'll integrate your amendments.

an attacker could send a request directly to the formhandler.php script and this will execute without control.

Fair enough, how do I fix that?

You should check each index key of the $_POST array that you want to use. So, you should do something like this:

No problem at all, will get that done.

you will probably received a mail with some PHP warnings

Nope, I didn't get anything.

Violet_82 89 Posting Whiz in Training

Right, I reconsidered the whole thing, as I'm clearly not really good with php and I didn't get any solution from anywhere.
I've refactored the code, and, for simplicity, mocked up a simpler form here http://antonioborrillo.co.uk/formTest/test.php (no styles or fancy animations, just a crude form). And here is what I've decided to do.
As I needed only some basic validation, I've done it clientside, and I've validated only the mandatory fields. If there is an error, meaning merely that the input field is empty as I'm not validating the email address, an error message appears at the top, the same general error message for all the fields. I used to have a customized error address for each field, but to be honest, there is probably no need for that. When the form gets submitted you get a submission message at the top of the form that disappears after 2 seconds.
Let's quickly look at the code.
HTML Form (test.php):

<!DOCTYPE html>
<html>
    <head>
        <script src="jquery-1.11.3.min.js"></script>
        <script src="form_en.js"></script>
        <link rel="stylesheet" type="text/css" href="style.css">
        <title></title>
    </head>
    <body>
        <form id="contactForm" target="_blank" method="POST" action="formhandler.php">    
            <!-- <div class="control-group">
                <label class="control-label" for="title">Title*</label>
                <div class="controls">
                    <select id="title" name="title">
                        <option value="0">Please select</option>
                        <option value="1">Mr </option>
                        <option value="2">Mrs</option>
                        <option value="3">Ms</option>
                        <option value="4">Sir</option>
                    </select>
                    <span class="error"></span>
                </div>
            </div> -->
            <div class="control-group">
                <label class="control-label" for="firstName">First name*</label>
                <div class="controls">
                    <input id="firstName" type="text" name="firstName" value="" class="mandatory">
                    <!-- <span class="error"></span>-->
                </div>
            </div>
            <div class="control-group">
                <label class="control-label" for="lastName">Last name*</label>
                <div class="controls">
                    <input id="lastName" type="text" name="lastName" value="" class="mandatory">
                    <!-- <span class="error"></span>--> …
Violet_82 89 Posting Whiz in Training

Cool thanks.

In particular the Files class (That's Files not File) has a readAllLines method that reads all the lines in a text file ito a List<String> - just what you need!

Yes thanks, readAllLines is the one I was looking at myself after I've done a bit of googling as it seems the quickest and easiest way to copy everything from a file. And yes, the NIO classes are a very new thing for me, somewhat confusing at the same time because there are io classes and then nio classes which look in fact the same, but I'm sure they do different things (the NIO call just static members or something like that?)
I'm just going to code the

Violet_82 89 Posting Whiz in Training

AH OK, I think this is even better, so I don't need to implement a button as it is real time (the results textArea could have an event handler so every type I type something the results are shown, even if this might be a bit more complicated to implement, but I can try).
WIth reading and writing on a file though, I think there could be a problem. In my current application I write to a file using a Scanner scannerInput, so I suppose now I need another variable of type Scanner, one that allows me to read from file, but I don't suppose I can do something like this:

private Scanner scannerOutput;//to output data from the file
...
public void fileInArray(){
        scannerOutput = new Scanner(new File(workingDir, fileName));        
    }

considering that there I've already created a file is already a file

fileName = "sample.txt";
file = new File(workingDir, fileName); 

in the constructor to deal with writing data to the file?
What I'm trying to say is, since a file sample.txt already exists I can't risk creating another one as it will overwrite the current one, presumably. So, when I read from file rather than creating a new one with scannerOutput = new Scanner(new File(workingDir, fileName));, how do I make sure that I open and use the old one?
I had a look on the net for "reading an existing java file" but they all insist on the above approach, so maybe by using that …

Violet_82 89 Posting Whiz in Training

A quick one sorry, what is the best way to add that functionality discussed without relying on the event generated by the button (so that I test it before adding the GUI part)?

read the whole file into an array or List, one sentence per entry - Then loop thru it

Without a button that calls the function, when would it be a good time to create this array and loop through it? I'm thinking to put the functionality in a function anyway, so that I can call it when I add the button

EDIT: Ah also one more thing. What if a keyword I use to search is in more than one sentence? I need to be able to return all the sentences that contain that keyword. I say that because I was thinking to have a function that saves the sentence in the array, search for the keyword and return the relevant sentence/s, so the function will return a string:
public String searchWord(){}

Violet_82 89 Posting Whiz in Training

thanks

But in this case I think your existing code writes 1 word per line, whereas to find sentences you can simplify that to write one sentence per line.

It writes one sentence per line, or rather, whatever the input in one line, so it should be fine:

private class ProcessButtonHandling implements ActionListener{
        public void actionPerformed(ActionEvent event){
            stringInput = input.getText();//copy text from textArea to string
            scannerInput = new Scanner(stringInput);            
            try{    
                fileWriter = new BufferedWriter( new FileWriter(file,true));
            }           
            catch(SecurityException securityException){//if you don't have write access
                System.err.println("You don't have write access to this file");
                System.exit(1);
            }
            catch(FileNotFoundException fileNotFoundException){
                System.err.println("Error opening or creating the file");
                System.exit(1);
            }
            catch(IOException ioexception){
                System.err.println("General Error with IO");
                System.exit(1);
            }
            while(scannerInput.hasNext()){
                stringInput = scannerInput.nextLine();
                try{
                    fileWriter.append(stringInput + separator);
                }
                catch(IOException ioexception){
                    System.err.println("General Error with IO");
                    ioexception.printStackTrace();
                    System.exit(1);
                }
                //System.out.printf("Enter your sentence or end of file - ctrl+z or Enter+ctrl+d\n");
            }
            CloseFile();
            Clear();
        }//end of actionPerformed

    }//end of inner class
Violet_82 89 Posting Whiz in Training

OK I understand, thanks.
That's OK I can implement that, is that I was thinking to do another application, and this might be a bit more than a few lines because if I implement the functionality I need to inplement the GUI as well. That's fine, will do it, you're right in the end, it's a good exercise :-)!
OK, so a few questions:
-can I use the already developed application to save to file rather than redoing it https://www.daniweb.com/programming/software-development/threads/501460/application-to-save-wordsentences-to-file
-the way I envisage this to work is this: the GUI (I know I have to do the functionality first and then the GUI but I might as well clarify a few things) will have, at the bottom of the window after the current buttons, a label explaining what to do, an extra input field for the keyword to be typed in, a search button to search for the keyword and a new textArea which I can use to display the returned strings.
About the functionality now.

loop through all the entries using something like contains(String searchString)to check each entry

When you say entries, you mean the entries stored in the file presumably?
The thing is though, shouldn't I first somehow save all the entries in the file in some kind of array and then loop through it, or that's not necessary and I can loop throught as it is?
When I loop through them, whichever way we do …

Violet_82 89 Posting Whiz in Training

Cool thanks, I don't think I'll implement the search, I was more curious than anything.
So the binary search can also be implemented with strings not only with ints
Cheers

Violet_82 89 Posting Whiz in Training

HI guys, a while ago I built an application to save strings to file https://www.daniweb.com/programming/software-development/threads/501460/application-to-save-wordsentences-to-file and I was wondering, what if I wanted to have the ability to search those strings, say I can choose a search key, like "bring" and search all the strings (and when I say strings I really mean sentences) for that key and when there is a match I display the whole sentence containing that key.
I'm looking into sorting and searching algorithms now, but they all seems to be working with ints, like, the binary search, (the binary search could be a good aid in this project). The thing is though, if I have multiple sentences, how would I sort them first?
Say I have "Sentence number 3", "Sentence number 1", "Sentence number 2", etc

Violet_82 89 Posting Whiz in Training

Hobbist for now, but yes I'd like to get to a point where I could get a programming job, or if not that, at least a job with some programming as part of it. SO where should I start do you reckon, any particular order?

Violet_82 89 Posting Whiz in Training

oh OK, I see thanks. Unfortunately I'm not familiar with any of the above (Maven + Eclipse/IntelliJ + Git, VCS). I develop Java applications, well, simple applications, just with notepad ++.

Violet_82 89 Posting Whiz in Training

@ddanbe, that's what I've been doing so far and I'm thinking that perhaps if I manage to "join" a project group I might take my java learning at another level. I mean I've been doing exercises for quite a while now, and I've learned quite a lot on this forum, mainly thanks to @JamesCherrill, but if I can participate to the development of a big application, together with other developers, I think I might get more inside knowledge of the industry etc.
@~s.o.s~: I've never used github before: how does it work with the code, do I develop a component of something, compile the code and then upload it onto github or whatever is involved is something that I will learn with practice?