0

I want when I choose a radio button and click the execute button, I want my search result to return the result for author title and year. For example if I click on author and entered an author's name stored in the database, I want to get author, title and year. The problem lies with wiring the radio button to the execute box. Thanks in advance.

   package data


         import java.awt.*;
         import java.awt.event.*;
         import javax.swing.*;
         import java.sql.*;
         import java.util.ArrayList;
         public class data extends JFrame implements ActionListener{

/**
 * @param args the command line arguments
 */
//Database Globals
Connection conn;
Statement stmt;
ResultSet result;

//Instance Variables
private Container contentPane;
private JLabel labelSearch;
private JTextField  tfSearch;
private JButton execButton;
private JRadioButton rbAuthorName, rbTitle, rbYear;  
private ButtonGroup searchChoices;
ArrayList<JRadioButton> radioButtonList = new ArrayList<JRadioButton>();

//Constructor
public data(){
    super("Database Search");
    connect();        
}    
//Creating the GUI 
public void buildGui(){

contentPane= getContentPane();
contentPane.setLayout(new FlowLayout());

    //set pane size
    setVisible(true);
    setSize(200,150);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Initializing objects
    labelSearch = new JLabel("Look Up");
    tfSearch = new JTextField(30);
    rbAuthorName = new JRadioButton("Author");
    rbTitle = new JRadioButton("Title");
    rbYear = new JRadioButton("Year");
    searchChoices = new ButtonGroup();
    execButton = new JButton("Execute");

    //Adding objects to the component pane
    contentPane.add(rbAuthorName);
    contentPane.add(rbTitle);
    contentPane.add(rbYear);
    contentPane.add(execButton);
    contentPane.add(labelSearch);
    contentPane.add(tfSearch);              
    radioButtonList.add(rbAuthorName);
    radioButtonList.add(rbTitle);
    radioButtonList.add(rbYear);
    execButton.addActionListener(this);
}

public void connect(){
     try
    {
       System.out.println("Connection to Driver..."); 
       Class.forName("com.mysql.jdbc.Driver");
       System.out.println("Connection successful");
       System.out.println("Connection to Database...");
       conn = DriverManager.getConnection("jdbc:mysql://localhost/tbl_books","root","");
       System.out.println("Connection successful");   

    }catch(ClassNotFoundException cfe)
    {
        System.out.println ("Connection error: "+cfe.getMessage());                    
    }        
    catch(SQLException sqle)
    {
        System.out.println ("Connection error: "+sqle.getMessage());                    
    }           
}

@Override public void actionPerformed(ActionEvent e){

        //Object src = e.getSource();
        if(e.getSource()==execButton){
            String buttonName ="";

        for(JRadioButton button: radioButtonList){
         if(button.isSelected()){
           buttonName = button.getName();
        }
            searchData(buttonName);

        }   

    }
}
public void searchData(String strData){
     strData= tfSearch.getText();   

    try
    {

        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
        String sqlString = "SELECT tbl_authors.author, tbl_books.title, tbl_books.year " + "from tbl_authors, tbl_books " + "where tbl_authors.isbn = tbl_books.isbn";

        if(rbAuthorName.isSelected()){
            sqlString = sqlString + "author LIKE '%" + strData + "%'";
        }

        else if(rbTitle.isSelected()){
            sqlString = sqlString + "title LIKE '%" + strData + "%'";
        }

        else if(rbYear.isSelected()){
            sqlString = sqlString + "date LIKE '%" + strData + "%'";
        }

        result =stmt.executeQuery(sqlString);

        int test = 0;
        String store = "";
        String response = "";

        while(result.next()){
            test ++;
            store = store + "\n"+ test + "." +
            result.getString(1)+ "" +
            result.getString(2)+ "" +
            result.getString(3);
        }
        if(test !=0){
            result.absolute(test);
            //displayData();
            response = "Number of Records" + test + store;
            JOptionPane.showMessageDialog(null, response);
        }
        else{
            JOptionPane.showMessageDialog(null,"Could not find data");
        }

    }catch(Exception e){
        e.getMessage();           
       }
}
//public void displayData(){

//}

public static void main(String[] args) {
    // TODO code application logic here
     CS6153Assignment2 data1 = new CS6153Assignment2();
     data1.connect();
     data1.buildGui();


}

}

Programmer254
  • 41
  • 2
  • 5
  • 10
  • 2
    I'm having difficulty understanding exactly what your problem is. Could you give us more details about your problem please? – Hovercraft Full Of Eels Oct 30 '12 at 19:03
  • 1
    I've seen your question's edit, thanks, but still can you tell us how your current code not working? What problems are you having with it? Errors? Bad behaviors? On review of your code, I don't see you using the text held in the JTextFields anywhere. I'm not sure that I see where you've even added the JTextFields to the GUI. Perhaps that's your problem. – Hovercraft Full Of Eels Oct 30 '12 at 20:20
  • Besides the fact that you don't seem to use some of your textfields and that I don't see the point of some labels, I don't see any serious problems. Describe what you would expect to see and what you are actually observing. – Guillaume Polet Oct 30 '12 at 21:12
  • I see, you're using the tfSearch JTextField only, which is fine. Again, you need to tell us more about what is wrong with your program's behavior. You're making us guess and we're usually quite bad at doing that. – Hovercraft Full Of Eels Oct 30 '12 at 21:22
  • @Guillaume Polet Sorry for delayed response. I actually was not in a position to early. I did edit the code and removed the labels and text fields that don't need to be there. I should have removed them earlier when I was still writing the code. Sorry for the confusion. – Programmer254 Oct 31 '12 at 01:49
  • @user1655056 The question is not clear. What is the problem with the code you show? What do you mean by *"wiring the radio button to the execute box"* ? – tenorsax Oct 31 '12 at 02:06
  • @HovercraftFullOfEels Sorry for delayed response. I actually was not in a position to early. I did edit the code and removed the labels and text fields that don't need to be there. I should have removed them earlier when I was still writing the code. Sorry for the confusion.I did change the description of the code. The problem is when I click the "execute" button my whole table is displayed before entering any values and before even choosing any radio button. I need it to display only the search query. – Programmer254 Oct 31 '12 at 02:21
  • @Max The problem is when I click the "execute" button my whole table is displayed before entering any values and before even choosing any radio button.I need it to display only the search query. Thanks. – Programmer254 Oct 31 '12 at 02:22
  • @user1655056 you can have one radio button selected by default. Also, don't execute `searchData()` if `tfSearch.getText()` is null or empty. – tenorsax Oct 31 '12 at 02:28
  • @Max. Thanks for that. Just edited my main and did set tfAuthorName to true. However my radio buttons dont seem to be wired together with the "execute" button since the search query does not return any values when I input any value. – Programmer254 Oct 31 '12 at 02:42
  • @user1655056 not sure what is `tfAuthorName` as it is not in the source code you provided. Again, what does *"wired together"* mean? You can add action listeners to radio buttons the same way you did to the `execute` button. – tenorsax Oct 31 '12 at 02:49

1 Answers1

0

I think what you want to do is when you click on the execute Button it looks for the currently selected RadioButton. The easiest way to do that would be saving all your Buttons into a Collection (ArrayList for instance):

ArrayList<JRadioButton> radioButtonList = new ArrayList<JRadioButton>();
radioButtonList.add(rbAuthorName);
radioButtonList.add(rbTitle);
radioButtonList.add(rbtYear);

And than in the ActionListener of the execute Button iterating over that list and looking for the selected one:

@Override
public void actionPerformed(ActionEvent e){
        if(e.getSource()==execButton){

          String buttonName="";

          for(JRadioButton button: radioButtonList){
             if(button.isSelected()){
               buttonName = button.getName;
          }

          searchData(buttonName);
        }
    }

After that you only have to modifiy the searchData method a little bit so that strData gets the value of the parameter.

1r0n1k
  • 405
  • 1
  • 4
  • 14
  • Thank you for understanding my question. That's exactly what I'm trying to do ie the execute button to look for the currently clicked radio button. I changed the code around as you suggested. Unfortunately I am still get the same problem. I'm actually using netbeans where the actionPerformed method is being highlighted by the yellow line meaning that it is not being implemented. I think the problem has to do with the implementation of the actionPerformed method. Thanks – Programmer254 Nov 01 '12 at 17:55
  • Could you update the code in your question? That would make it easier for me to search for the error. What you can try to do is adding the `@Override` annotation infront of the `actionPerformed` method (look at my updated answer), indicating that you implement a method from a parent class. Furthermore there is a compiler error on line 18 (`private JTextField , tfSearch;`), it's probably a typo and shouldn't be the cause of your problem. Just get rid of the comma. – 1r0n1k Nov 02 '12 at 07:26
  • Sorry for the delayed response. I have made the changes but still have the same problem. I have updated the code above. Thanks. – Programmer254 Nov 05 '12 at 22:52