3

I have a program that has three functions; to read a file, write to a file and search for specific text within a file. I'm currently working on creating a GUI to use with it so that I will no-longer rely on the console. I've already created a fully functional "main window" and functional buttons with respect to the three aforementioned functions, as well as an exit button. Now I'm working on the GUI window for my Search function - the window is created as the response to the Search button being clicked. I have the window and components layed out the way I want but I'm having trouble setting up the action listener for when the user presses Enter after inputting the string they wish to search for. I've looked at a number of different sources including SOverflow, the javadoc and actionlistener tutorials; but I'm getting nowhere fast.

Here is the base code to draw the Search button in the main window and link to the Search GUI (I linked to this through main):

public class SimpleDBGUI{
    static File targetFile;                                                                                         //Declare File var to be used in methods below for holding user's desired file
    static JTextField sdbTarget;
    static JTextField searchTerm;


    public void mainWindow(){

        //Create main window for Program
        JFrame mainWindow = new JFrame("Simple Data Base");                                                         //Init frame
        mainWindow.setSize(500, 180);                                                                               //Set frame size
        mainWindow.setVisible(true);                                                                                //Make frame visible

        //Create panel for the main window of the GUI
        JPanel simpleGUI = new JPanel( new GridBagLayout());
        GridBagConstraints gbCons = new GridBagConstraints();
        mainWindow.getContentPane().add(simpleGUI);                                                                 //Adds JPanel container to the ContentPane of the JFrame

        //Create button linking to the search function
        JButton searchButton = new JButton("Search");                                                               //Init button with text
        gbCons.fill = GridBagConstraints.BOTH;
        gbCons.gridx = 1;
        gbCons.gridy = 2;
        gbCons.weightx = .1;
        searchButton.setActionCommand("Search");
        searchButton.addActionListener( new ButtonClickListener());
        simpleGUI.add(searchButton, gbCons);                                                                        //Adds the "Search" button to the JPanel

        //Create TextField for user to input a desired file
        sdbTarget = new JTextField();
        gbCons.fill = GridBagConstraints.BOTH;
        gbCons.gridx = 0;
        gbCons.gridy = 1;
        gbCons.gridwidth = 3;
        simpleGUI.add(sdbTarget, gbCons);                                                                           //Adds TextField to GUI
    }

    public class ButtonClickListener implements ActionListener{                                                     //Sets the EventListener for every function

        public void actionPerformed(ActionEvent event){

            targetFile = new File(sdbTarget.getText());
            String function = event.getActionCommand();                                                             //Reads the ActionCommand into a string for use in performing desired function

            if( function.equals("Search")){                                                                         //Search Function, draws search window and components
                JFrame searchWindow = new JFrame("SimpleDB Search");                                                //Draw window
                searchWindow.setSize(500, 200);
                searchWindow.setVisible(true);

                JPanel searchGUI = new JPanel( new GridBagLayout());                                                //Create container and add to window 
                GridBagConstraints gb1Cons = new GridBagConstraints();
                searchWindow.getContentPane().add(searchGUI);

                JLabel searchPrompt = new JLabel("Please input the word/phrase you wish to find:");                 //Prompt user to specify string to search for
                gb1Cons.fill = GridBagConstraints.BOTH;
                gb1Cons.gridy = 0;
                gb1Cons.gridx = 0;
                //gb1Cons.weighty = .1;
                searchGUI.add(searchPrompt, gb1Cons);                                                               //Add prompt to container

                JTextField searchTerm = new JTextField();                                                           //Create JTextField for user input and add to container
                gb1Cons.fill = GridBagConstraints.BOTH;
                gb1Cons.gridy = 1;
                gb1Cons.gridx = 0;
                //gb1Cons.weighty = .1;
                searchGUI.add(searchTerm, gb1Cons); 
                searchTerm.addActionListener(this);                                                                 //Assign ActionListener to JTextField

                JTextArea searchResult = new JTextArea();                                                           //Create search output box and add to container
                gb1Cons.fill = GridBagConstraints.BOTH;
                gb1Cons.gridy = 2;
                gb1Cons.gridx = 0;
                //gb1Cons.weighty = .1;
                searchGUI.add(searchResult, gb1Cons);

                public void actionPerformed( ActionEvent event){        //Tried this as one event handler, supposed to execute the following upon the user pressing Enter, failed of course

                    boolean stringFound = false;                                                                    //Set flag false
                    try{
                        Scanner searchFile = new Scanner(targetFile);                                               //Read file to be searched into a scanner
                        String searchInput = searchTerm.getText();                                                  //Read term to search for into a string

                        while( searchFile.hasNextLine()){                                                           //Check that specified file has a next line and:
                            String searchLine = searchFile.nextLine();                                                  //Read line into string
                            if( searchLine.contains(searchInput)){                                                      //Check that Line contains searched term and:
                                stringFound = true;                                                                         //If line contains term, set flag to true
                                searchResult.append("**" + searchLine + "**");                                              //Append line with term to output box
                            }
                        }searchFile.close();                                                                        //Close scanner

                        if(!stringFound){
                            searchResult.append("The term(s) you searched for does not exist in this file");        //Output if line does not contain term
                        }
                    }catch(IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

2 Answers2

3

You should try to re-structure your code some

I would not create the GUI within an actionPerformed, create it outside (or make a class for it extend JFrame), and in actionPerformed, just display it setVisible(true).

Even if this suggestion is not your problem, it would probably solve it.

Your current situation is:

Your are adding the actionListener to JTextField searchTerm, the actionListener that your are adding is actually the ButtonClickListener so you already have an actionPerformed method,hence same method!!!

So outcome is:

when you press enter in your searchTerm the ButtonClickListener.actionPerformed will be called and if you try to write "Search" in the textfield you will see something interesting!!

A short code for adding a new actionListener would be

searchTerm.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    //DO YOUR STUFF
  }
});
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
  • From what I've seen, the JTextField component is supposed to have some sort of listener for when `Enter` is pressed, but I've not been able to figure it out. I've tried putting my code that is supposed to execute as a result of searchTerm specification within the parenthesis (argument?) of the listener, but continually end up failing out. – Joshua Napier Nov 24 '15 at 16:02
  • I've never used the `@Override` line before, is it necessary? – Joshua Napier Nov 24 '15 at 16:06
  • The actionPerformed is fired when enter is pressed, to figure out that its the JTextField check the source on the event, in actionCommand you will have the text – Petter Friberg Nov 24 '15 at 16:06
  • @Override is not necessary – Petter Friberg Nov 24 '15 at 16:07
  • This worked, thanks! Does the `@Override` line actually do anything, or does it just point out that the user is about to override something? – Joshua Napier Nov 24 '15 at 16:13
  • It does not do anything else then telling that it was defining a method of the implementation.. – Petter Friberg Nov 24 '15 at 16:16
1

Just paste this code in your constructor.

Hope it'll help. Remember your searchTerm should be of jtextfield as the code for jtextxarea is bit different.

searchTerm.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {             
        actionPerformed(e);
    }
});
Maaz
  • 65
  • 1
  • 11