Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 391
  • Last Modified:

Java JCheckBox Event Handeling

Ive been looking around for the best solution for this, ive noticed there is loads of different ways to handle what i want to do, but I would like some advise.

You can use ItemListener , ChangeState ActionListener etc.

From what I have seen I think the best practice code would be ActionListener and getState check. Can anyone confirm?

As you can see my current code handling the check box is somewhat shocking (im learning lol ) Im looking to add a few more checkboxes (once I can get one working)so either of combination of each box can be selected. It would then add the relevant string to the searchParam ie "FileType:pdf" , (multiple boxes selected) "FileType:doc,pdf,txt" etc.

I really would be greatful if someone could give me an example with my code. Im not sure if or even how to use any of the ItemListener etc as ive got an extends Actionlistener on the JFrame. Does this effect it at all?

Thanks in advance for any help.




import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;


class Main extends JFrame implements ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public String[] FileType ={"Pdf" , "Doc" , "txt" , "xls"};
	
	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	JCheckBox chkpdf = new JCheckBox(FileType[0],true);
	JCheckBox chkdoc = new JCheckBox(FileType[1]);
	JCheckBox chktxt = new JCheckBox(FileType[2]);
	JCheckBox chkxls = new JCheckBox(FileType[3]);
	public Search SearchObject = new Search();
	public String pdf = "FileType:pdf";
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
        pnl2.add(chkpdf);
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
		chkpdf.addActionListener(this);
		
        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}
	
	
	
	public void actionPerformed(ActionEvent event) {
		
		if (event.getSource().equals(btn1)){
			String searchParam = txt1.getText().trim();
		    
		if (searchParam.length() < 1) {
		    String txtCheck = "Enter Query String";
			txtArea.setText(txtCheck);
			return;
		    }
		if (event.getSource().equals(btn1));
				try {
					SearchObject.searchGoog(searchParam);
					txtArea.setText(SearchObject.getLine());
					
					} 
				catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					}	
		if (event.getSource().equals(btn1) && (chkpdf.isSelected()));{
		 			
		 		try {
		 			SearchObject.searchGoog(searchParam + pdf);
		 			txtArea.setText(SearchObject.getLine());
		 			return;
		 			} 
		    	catch (Exception ex) {
		    			ex.printStackTrace();}}
		    			 
			    }
	}
	

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

Open in new window

import java.io.*;
import java.net.*;


public class Search {
public String line;
    
    public void searchGoog(String searchString) throws IOException {
        
	URL url = new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + searchString);
	URLConnection connection = url.openConnection();
        
	StringBuilder builder = new StringBuilder();
	BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String buff = null;
	while((buff = reader.readLine()) != null) {
	builder.append(buff);
        
	}
	
System.out.println(builder.toString());
        line = builder.toString();

    }
 public String getLine() {
        return line;
    
    }

    public void setLine(String line) {
        this.line = line; 
    }    
}

Open in new window

0
k3eper
Asked:
k3eper
  • 28
  • 20
1 Solution
 
for_yanCommented:

Though it is probably not much difference but with JChcekBox
I'd use ItemListener, like in this example:
http://www.java2s.com/Code/JavaAPI/javax.swing/JCheckBoxaddItemListenerItemListenerlis.htm
0
 
k3eperAuthor Commented:
See im not sure how to use that as its got this line

public class MainClass extends JPanel implements ItemListener {
  public MainClass() {

and im using implements ActionListener in my current code how would i use both?
0
 
for_yanCommented:
One thing is you can implement any num ber of interfaces:

public class MainClass extends JPanel implements ItemListener, ActionListenere {

The only think that you need to implement all methods of both interfacse if you declare this way

ItemListener has only one method and ActionListnere also

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
for_yanCommented:
But I think in you case - do you really need to have any even associated with the checkbox?
You reaklly need to start any activity when user clicks the button
The checkbox just modifies the poroperty of how you are going to search
0
 
for_yanCommented:
So if I undedertsatnd it correctly the right thing would be tio do more or less what you do -
you don't need to have a special listener for the checkbox - it is just when you start your actgfivitiy based on the clck of the button you need to check the sate of your checkbox
So in this case you don't need to implement ItemListener
0
 
k3eperAuthor Commented:
ok so I would use

class Main extends JFrame implements ActionListener, ItemListener

and a ChageState listener?
0
 
for_yanCommented:
To catch the eventyt when someone clicks your chckbox you need to implement ItemListener

which means you need to define method
public void itemStateChanged(ItemEvent ie){

}
0
 
for_yanCommented:
But read my posts above and thiink if in your situation you really need to catch the actual moment
when the sate is changed
In order to check the satus of the box - checked or unchecked - you really do not need to have any listener - you can check it at any momemnt in your code
It is only if yiou need to initiate any action when yuser clicks the checkbox - that;s when you would need to listene to event generated by this cklick

0
 
for_yanCommented:
In your case the click on the checkbox should not initiate the search - it only modifies the way you are doing the serach when user clicks the button - correct?
In such case you really do not need to listen to checkbox state change - you just need to check the status of the checkbox at the moment when user clickeed the button
So you need only to listen to the button click and just check tghe status of the checkbox when you initatite the serach
0
 
for_yanCommented:
Below is the gernarl scheme how you would work with the class which implements both listeners in general,
but still read ny posts above - in your case perhaps you don't need to listen to events generated by clcicking
on the checkbox

class Main extends JFrame implements ActionListener, ItemListener {

...


button.addActionListener(this);


checkbox.addItemListener(this);


....




public void actionPerformed(ActionEvent ae) {

//do something when they click the bitton

}


public void itemStateChanged(ItemEvent ie){

//do something whewn the click the checkbox

}


}

Open in new window

0
 
k3eperAuthor Commented:
Ok Ive got the code attached but it fails

"Exception in thread "main" java.lan.NullPointerException
at main.<init>(Main.java:55)
at main.main(Main.java:91)


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener, ItemListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	String[] FileType ={"Pdf" , "Doc" , "txt" , "xls"};
	
	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	JCheckBox chkpdf = new JCheckBox(FileType[0]);
	JCheckBox chkdoc = new JCheckBox(FileType[1]);
	JCheckBox chktxt = new JCheckBox(FileType[2]);
	JCheckBox chkxls = new JCheckBox(FileType[3]);
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
        pnl2.add(chkpdf);
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
		chkpdf.addItemListener(this);
        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}
	public String searchString = txt1.getText();
	public void actionPerformed(ActionEvent event) {
		if (event.getSource().equals(btn1)) {
		    String searchParam = txt1.getText().trim();
		    if (searchParam.length() < 1) {
			String txtCheck = "Enter Query String";
			txtArea.setText(txtCheck);
		    }
		   
		    else {
			Search SearchObject = new Search();

			try {
			    SearchObject.searchGoog(searchString);
			    txtArea.setText(SearchObject.getLine());
			} catch (Exception ex) {
			    ex.printStackTrace();
			}
		    }
		}
	    }
	public void itemStateChanged(ItemEvent ie){
	if 	(ie.getStateChange()==ItemEvent.SELECTED){
	 try {
		 String searchString = txt1.getText() + "%20FileType:pdf" ;
		 System.out.println(searchString);//check output is correct
		
	 }catch(Exception ex){
         ex.printStackTrace();
     }
	}
		
	}
	public static void main (String[] args)
	{
	new Main();
	}

	
}

Open in new window

0
 
k3eperAuthor Commented:
Sorry line 90 not 91
0
 
k3eperAuthor Commented:
I think it must be to do with the String searchString

but im not sure how I can call the searchString from each ActionEvent and ItemStateChange event unless i make it public?
0
 
for_yanCommented:
public has nothing to do with it - it allows to accsee this string form other classes.
Let me try tyour code - II moved to another place I need to craete your nd paste your cass again
0
 
for_yanCommented:
Can you repsond in the mantime to my suggestions above - od you really need to trackl events form the checkbox?
0
 
for_yanCommented:

This line

public String searchString = txt1.getText();

 lliveas between any methods - so it tries to execute it before it executes your contsructor - at that monent
yout textfield txt1 is not yet created so txt1 points to null
and therefore txt1.getText() throws NullPointerexception
0
 
k3eperAuthor Commented:
No i only need to check the state

then if selected

add whatever the type of file (pdf for instance) to the search term

Example of google search

inurl:Thisbookname Filetype:pdf
0
 
for_yanCommented:
This would work - you declare serachString in the beginning but then
assign

searchString =txt1.getText()
aalready in the event hanlder method
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener, ItemListener
{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	String[] FileType ={"Pdf" , "Doc" , "txt" , "xls"};

	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	JCheckBox chkpdf = new JCheckBox(FileType[0]);
	JCheckBox chkdoc = new JCheckBox(FileType[1]);
	JCheckBox chktxt = new JCheckBox(FileType[2]);
	JCheckBox chkxls = new JCheckBox(FileType[3]);

    	public String searchString;
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
        pnl2.add(chkpdf);
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
		chkpdf.addItemListener(this);
        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}

	public void actionPerformed(ActionEvent event) {
		if (event.getSource().equals(btn1)) {
		    String searchParam = txt1.getText().trim();
		    if (searchParam.length() < 1) {
			String txtCheck = "Enter Query String";
			txtArea.setText(txtCheck);
		    }

		    else {
			Search SearchObject = new Search();

			try {
                searchString = txt1.getText();
			    SearchObject.searchGoog(searchString);
			    txtArea.setText(SearchObject.getLine());
			} catch (Exception ex) {
			    ex.printStackTrace();
			}
		    }
		}
	    }
	public void itemStateChanged(ItemEvent ie){
	if 	(ie.getStateChange()==ItemEvent.SELECTED){
	 try {
		 String searchString = txt1.getText() + "%20FileType:pdf" ;
		 System.out.println(searchString);//check output is correct

	 }catch(Exception ex){
         ex.printStackTrace();
     }
	}

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


}

Open in new window

0
 
for_yanCommented:
Taht's why you don't need any events associated with the checkbox

At the moement when user checks the checknbox - your program does not need to do anything
It is onluy at the moment when user click the button, that your program need to check the stet of the checkbox
So you don't need to track any events associated with the checkbox
0
 
for_yanCommented:
That is the only thisng you need to do insaide the actionPerformed() method:

	try {
                searchString = txt1.getText();
                if(chkpdf.isSelected()){ //ccheck the sate of the checkBox
                    //modify searh string in such a way as to serach for PDFs 
                    
                }
			    SearchObject.searchGoog(searchString);

Open in new window


you don't need to listen for the event when someone checks the box
0
 
for_yanCommented:
Please, respond to my posting - do you understand waht I'm talking about ?- that you do not need to catch the actual event when user
checks the box, just the checked box will modify your actions when you process the click of the button.

If I'm wrong and your operations are different - then please explain it to me,
otherwise tell me if you understand what I'm taliking about.

If not, explain to me what it is that you do not understand
and I'll try to explain again.


0
 
for_yanCommented:
One thing to realise is that checking the state of the checkbox - this is one thing
and adding listener and waiting for the events from the checkbox - this is quite different thing.

If you would need to initiate the search at the moemnet when user
selects/deselects the checkbox- then you would have needed to add listener to the checkbox.
Howvere, as far as I undersatnd your program operation - your program does not need to react at the very moment
the user click the checkbox. The Swing will change the state of the checkbox upon clicking on it by the user
without participation of your program - this is the service which Swing provides to you automatically..
The user can click or unclick it several times - your program does not need to react
It only needs to read the state of the checkbox before it goes to search.
If that is the case - you don't need any listenere to be associated with the checkbox.
You jsust have listener assosciated with the button, and then before
starting the serach - you read the sate of the checkbox
and adjust your search command accordingly.

Please, write if there is something you do not understand about this process.


0
 
k3eperAuthor Commented:
like this?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener, ItemListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	String[] FileType ={"Pdf" , "Doc" , "txt" , "xls"};
	
	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	JCheckBox chkpdf = new JCheckBox(FileType[0]);
	JCheckBox chkdoc = new JCheckBox(FileType[1]);
	JCheckBox chktxt = new JCheckBox(FileType[2]);
	JCheckBox chkxls = new JCheckBox(FileType[3]);
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
        pnl2.add(chkpdf);
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
		chkpdf.addItemListener(this);
        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}
	public String searchString;
	public void actionPerformed(ActionEvent event) {
		if (event.getSource().equals(btn1)) {
		    String searchParam = txt1.getText().trim();
		    if (searchParam.length() < 1) {
			String txtCheck = "Enter Query String";
			txtArea.setText(txtCheck);
		    }
		    if (chkpdf.isSelected()){
		    	String searchString = txt1.getText() + "%20FileType:pdf" ;
				 System.out.println(searchString);//check output is correct
				
		    }
		    else {
			Search SearchObject = new Search();

			try {
			    SearchObject.searchGoog(searchString);
			    txtArea.setText(SearchObject.getLine());
			} catch (Exception ex) {
			    ex.printStackTrace();
			}
		    }
		}
	    }
	public static void main (String[] args)
	{
	new Main();
	}

	
}

Open in new window

0
 
for_yanCommented:
Yes, like this but you should also
remove ItemListnere form the first line, ther wise it would require that you implement the
itemStateChanged method

class Main extends JFrame implements ActionListener {
...

0
 
for_yanCommented:
Your checkbox in this case plays similar role as your JTextField.
You are not listemning to any events associated with the textfiled - because
you don't care when user is typing - you only care when user preses the button - then you read
what user typed. The saem is in your case true for the checkbox -
you only care what is the staus of your check box when user clicks the botton
you don't need to react when the user checkjs/unchecks the checkbox.

So your last wvarian was fine - you remove the itemStateChanged method;
just remove ItemListener form class declaration othereise compuiler woul require to have the
method implemented
 
0
 
k3eperAuthor Commented:
Ok this seems to work

but i think its going to getting very messy with all the IF else if and try catch for every else if

i will need to make else if try catch for each possible combonation of boxes that are selected.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	String[] FileType ={"Pdf" , "Doc" , "txt" , "xls"};
	
	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	JCheckBox chkpdf = new JCheckBox(FileType[0]);
	JCheckBox chkdoc = new JCheckBox(FileType[1]);
	JCheckBox chktxt = new JCheckBox(FileType[2]);
	JCheckBox chkxls = new JCheckBox(FileType[3]);
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
        pnl2.add(chkpdf);
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
		
        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}
	public String searchString;
	public void actionPerformed(ActionEvent event) {
		if (event.getSource().equals(btn1)) {
		    String searchParam = txt1.getText().trim();
		    if (searchParam.length() < 1) {
			String txtCheck = "Enter Query String";
			txtArea.setText(txtCheck);
		    }
		    else if (chkpdf.isSelected()){
		    	String searchString = txt1.getText() + "%20FileType:pdf" ;
				 System.out.println(searchString);//check output is correct
				 try {
					 Search SearchObject = new Search();   
					 SearchObject.searchGoog(searchString);
					    txtArea.setText(SearchObject.getLine());
					} catch (Exception ex) {
					    ex.printStackTrace();
				
					}
		    }
		    else {
			Search SearchObject = new Search();

			try {
			    SearchObject.searchGoog(searchString);
			    txtArea.setText(SearchObject.getLine());
			} catch (Exception ex) {
			    ex.printStackTrace();
			}
		    }
		}
	    }
	public static void main (String[] args)
	{
	new Main();
	}

	
}

Open in new window

0
 
k3eperAuthor Commented:
arr I think if i pass the same string just + the Filetype each time it should work dont you think?
0
 
for_yanCommented:
Yes, from the point of view of Java code you jsut modify the filetype leaving the string itself - its seesm fine

From the point of view of search command - and this service you are using - that I don't know - so you want to limit search only to PDF files?
does this service which you use:
https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + searchString);

allow it?
 it all depends on this service - do you know  its description or something?

This already epends on the requireent of the service - you need to
have it in the required format, and that's what your program can do
once you know the format.
0
 
for_yanCommented:
When you have many boxes - if you want to have them exclusive - so taht search each time can go
only through one type of files - then you may want to llok atch CheckBoxGroup  - that class would ensure
that wne one chcekbox is clicked then none ofther of this group is clicked;
If you can aloow serach acroos any combinations - say pdfs and xls's both are allowed - then you rather
keep indepndednt checkboxes
0
 
k3eperAuthor Commented:
yes its just using google to search and google uses "Filetype:"

Type this into google

inurl:SQL Best Practice Filetype:pdf

youll see what i mean
0
 
for_yanCommented:

Sure, then just concatennate your string in such way:
q=inurl%3ASQL Best Practice Filetype%3Apdf

Open in new window


"inurl%3A" + searchString + " Filetype%3Apdf"  and ffed this into your method

if they checked xls box

then make string this way I guess:

"inurl%3A" + searchString + " Filetype%3Axls"

jsut with if-else you can
create exactly the line you want



0
 
k3eperAuthor Commented:
Ok getting closer I think

It doesnt seem to place the results into the txtarea now thom but i think i only need the try catch at the end ?


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	String[] FileType ={"Pdf" , "Doc" , "txt" , "xls"};
	
	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	JCheckBox chkpdf = new JCheckBox(FileType[0]);
	JCheckBox chkdoc = new JCheckBox(FileType[1]);
	JCheckBox chktxt = new JCheckBox(FileType[2]);
	JCheckBox chkxls = new JCheckBox(FileType[3]);
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
        pnl2.add(chkpdf);
        pnl2.add(chkdoc);
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
		
        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}
	public String searchString = "FileType:";
	public void actionPerformed(ActionEvent event) {
		System.out.println(searchString);
		if (event.getSource().equals(btn1)) {
		    String searchParam = txt1.getText().trim();
		    if (searchParam.length() < 1) {
			String txtCheck = "Enter Query String";
			txtArea.setText(txtCheck);
		    }
		    else if (chkpdf.isSelected()){
		    
		    	String searchString = "pdf%20" + txt1.getText();
				 System.out.println(searchString);//check output is correct
		    }	 
		    else if (chkdoc.isSelected()){
		    String searchString = "doc" + txt1.getText();	
		    System.out.println(searchString);//check output is correct
			 
		    }
		    
		    else {
			Search SearchObject = new Search();

			try {
				 SearchObject.searchGoog(searchString);
				    txtArea.setText(SearchObject.getLine());
				} catch (Exception ex) {
				    ex.printStackTrace();
			
				}
	    }
			}
		    }
		
	    
	public static void main (String[] args)
	{
	new Main();
	}

	
}

Open in new window

0
 
k3eperAuthor Commented:
Hmmm

the syntax for searching with Filetype if it has multi types is

Filetype:pdf,doc,txt

etc.

At the moment when the app has both boxes selected it produced

this output

FileType:
pdf%20SQL
doc%20SQL

i need to get it to be

Filetype:pdf,doc + txt1.getText

0
 
k3eperAuthor Commented:
I dont think this nested IFs are going to work there must be another better way. I cant see how this will work.

Can you show me how it would work with multiple boxes? please
0
 
for_yanCommented:
This will do it:

(you made it incorrect with else - you wawere reading serchString in one branche of if
and searching in another bracnch of after else )

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener
{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	String[] FileType ={"Pdf" , "Doc" , "txt" , "xls"};

	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	JCheckBox chkpdf = new JCheckBox(FileType[0]);
	JCheckBox chkdoc = new JCheckBox(FileType[1]);
	JCheckBox chktxt = new JCheckBox(FileType[2]);
	JCheckBox chkxls = new JCheckBox(FileType[3]);
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
        pnl2.add(chkpdf);
        pnl2.add(chkdoc);
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);

        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}
	public String searchString = "FileType:";
	public void actionPerformed(ActionEvent event) {
		System.out.println(searchString);
		if (event.getSource().equals(btn1)) {
		    String searchParam = txt1.getText().trim();
		    if (searchParam.length() < 1) {
			String txtCheck = "Enter Query String";
			txtArea.setText(txtCheck);
		    }
		    else if (chkpdf.isSelected()){

		    	searchString = "pdf%20" + txt1.getText();
				 System.out.println(searchString);//check output is correct
		    }
		    else if (chkdoc.isSelected()){
		    searchString = "doc" + txt1.getText();
		    System.out.println(searchString);//check output is correct

		    }

		    
			Search SearchObject = new Search();

			try {
				 SearchObject.searchGoog(searchString);
				    txtArea.setText(SearchObject.getLine());
				} catch (Exception ex) {
				    ex.printStackTrace();

				}

			}
		    }


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


}

Open in new window

0
 
k3eperAuthor Commented:
what if both are selected?
0
 
for_yanCommented:
Before it was syaing

if(chckpdf.isSelected()){

saerchString = ... //read fro textbox
}
else {
//createv Search objecte and feed serachString and start search

}


as a resulty of this logic - if the check box was cheked it did assign seacchString
bjut didnot go to acrtual search

you need to remove esle here:

if(chckpdf.isSelected()){

saerchString = ... //read fro textbox
}
// no else neede here

//createv Search objecte and feed serachString and start search






0
 
for_yanCommented:
if both are selected you can perhpahs concatentate - in the foirst loop you add the part for pdf - in the next
loop you add the part ofr xls  - but taht woud probably mean that they need to be both there -
all that is about google seraching indfex; at least in Java you can do wahtever you want with strings,
but how googlewill interpret it  that is a nother stoiry
0
 
k3eperAuthor Commented:
maybe i should create a combobox allowing only 1 to be selected

then anothe search to allow all to be selected. that would be simpler but still give the possible selections.
0
 
for_yanCommented:
yes, combobox will make sense if you want to allow to select only one file type
0
 
k3eperAuthor Commented:
Ok this seems to work better but when I println it doesnt show txt1.getText() only selected index string?


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener,ItemListener
{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	String[] FileType ={"Pdf" , "Doc" , "txt" , "xls"};

	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	JCheckBox chkpdf = new JCheckBox(FileType[0]);
	JCheckBox chkdoc = new JCheckBox(FileType[1]);
	JCheckBox chktxt = new JCheckBox(FileType[2]);
	JCheckBox chkxls = new JCheckBox(FileType[3]);
	JComboBox box = new JComboBox(FileType);
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
        //pnl2.add(chkpdf);
        pnl2.add(box);
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
		//box.addItemListener(this)

        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}
	public String searchString = "";
	public void actionPerformed(ActionEvent event) {
		System.out.println(searchString);
		if (event.getSource().equals(btn1)) {
		    String searchParam = txt1.getText().trim();
		    if (searchParam.length() < 1) {
			String txtCheck = "Enter Query String";
			txtArea.setText(txtCheck);
		    if (box.getSelectedIndex()==0);{
		    	searchString = txt1.getText()+ "FileType:pdf" ;
				 System.out.println(searchString);//check output is correct	
		    }
		    }
			}
		    }


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


	@Override
	public void itemStateChanged(ItemEvent arg0) {
		// TODO Auto-generated method stub
		
	}


}

Open in new window

0
 
for_yanCommented:

It didn't print because you messed up many things
but mostly with the if's
printing only in case your input line was less than one symbol length

also you were printing only if the selected index was zero - that would not print if you select, say,
 doc - not pdf

I correscted all of it - it now prints

package checkbox;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener,ItemListener
{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	String[] FileType ={"Pdf" , "Doc" , "txt" , "xls"};

	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	JCheckBox chkpdf = new JCheckBox(FileType[0]);
	JCheckBox chkdoc = new JCheckBox(FileType[1]);
	JCheckBox chktxt = new JCheckBox(FileType[2]);
	JCheckBox chkxls = new JCheckBox(FileType[3]);
	JComboBox box;
    public String searchString;
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);
        box    = new JComboBox(FileType);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
        //pnl2.add(chkpdf);
        pnl2.add(box);
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
		//box.addItemListener(this)

        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}

	public void actionPerformed(ActionEvent event) {
	//	System.out.println(searchString);
		if (event.getSource().equals(btn1)) {
		    String searchParam = txt1.getText().trim();
		    if (searchParam.trim().length() == 0) {
			String txtCheck = "Enter Query String";


			txtArea.setText(txtCheck);
             return;
            }

		    	searchString = txt1.getText()+ "FileType:" + box.getSelectedItem() ;
				 System.out.println(searchString);//check output is correct	

		    }
			}



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



	public void itemStateChanged(ItemEvent arg0) {
		// TODO Auto-generated method stub
		
	}


}

Open in new window

0
 
for_yanCommented:
remove first line "package checkbox;"
from the above posted code
0
 
k3eperAuthor Commented:
Arr see that looks much better and works in principle but if i need to use searchString to search

Search SearchObject = new Search();
                               SearchObject.searchGoog(searchString);
                                  txtArea.setText(SearchObject.getLine());

I would need to add a Try and Catch (as attached) but then it wouldnt work properly because if i changed the selection to say a doc instead of pdf it would only return pdf

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener,ItemListener
{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	String[] FileType ={"Pdf" , "Doc" , "txt" , "xls"};

	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	JCheckBox chkpdf = new JCheckBox(FileType[0]);
	JCheckBox chkdoc = new JCheckBox(FileType[1]);
	JCheckBox chktxt = new JCheckBox(FileType[2]);
	JCheckBox chkxls = new JCheckBox(FileType[3]);
	JComboBox box;
    public String searchString;
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);
        box    = new JComboBox(FileType);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
        pnl2.add(box);
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
	

        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}

	public void actionPerformed(ActionEvent event) {
		if (event.getSource().equals(btn1)) {
		    String searchParam = txt1.getText().trim();
		    if (searchParam.trim().length() == 0) {
			String txtCheck = "Enter Query String";


			txtArea.setText(txtCheck);
             return;
            }

		    	searchString = txt1.getText()+ "%20FileType:" + box.getSelectedItem() ;
				 System.out.println(searchString);//check output is correct	
				 try {
					 Search SearchObject = new Search();
					 SearchObject.searchGoog(searchString);
					    txtArea.setText(SearchObject.getLine());
					} catch (Exception ex) {
					    ex.printStackTrace();

					}

		    }
			}



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



	public void itemStateChanged(ItemEvent arg0) {
		// TODO Auto-generated method stub
		
	}


}

Open in new window

0
 
k3eperAuthor Commented:
this look correct?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener,ItemListener
{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	String[] FileType ={"Pdf" , "Doc" , "txt" , "xls"};

	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	JCheckBox chkpdf = new JCheckBox(FileType[0]);
	JCheckBox chkdoc = new JCheckBox(FileType[1]);
	JCheckBox chktxt = new JCheckBox(FileType[2]);
	JCheckBox chkxls = new JCheckBox(FileType[3]);
	JComboBox box;
    public String searchString;
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);
        box    = new JComboBox(FileType);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
        pnl2.add(box);
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
	

        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}

	public void actionPerformed(ActionEvent event) {
		if (event.getSource().equals(btn1)) {
		    String searchParam = txt1.getText().trim();
		    if (searchParam.trim().length() == 0) {
			String txtCheck = "Enter Query String";


			txtArea.setText(txtCheck);
             return;
		    }
			else

		    	searchString = txt1.getText()+ "%20FileType:" + box.getSelectedItem() ;
				 System.out.println(searchString);//check output is correct	
				 try {
					 Search SearchObject = new Search();
					 SearchObject.searchGoog(searchString);
					    txtArea.setText(SearchObject.getLine());
					} catch (Exception ex) {
					    ex.printStackTrace();

					}

		    }
			}



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



	public void itemStateChanged(ItemEvent arg0) {
		// TODO Auto-generated method stub
		
	}


}

Open in new window

0
 
k3eperAuthor Commented:
YAY! i think ive got it

what do you think?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener,ItemListener
{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	String[] FileType ={"Pdf" , "Doc" , "txt" , "xls"};

	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	JCheckBox chkpdf = new JCheckBox(FileType[0]);
	JCheckBox chkdoc = new JCheckBox(FileType[1]);
	JCheckBox chktxt = new JCheckBox(FileType[2]);
	JCheckBox chkxls = new JCheckBox(FileType[3]);
	JComboBox box;
    public String searchString;
	public Main()
		{
		super("Swing Window");
		pnl = new JPanel();
        JPanel pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        JPanel pnl2 = new JPanel();
        txt1 = new JTextField(20);
        box    = new JComboBox(FileType);

        btn1 = new JButton("Search");
        txtArea = new JTextArea(20,30);
        txtArea.setLineWrap(true);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());



        pnl.setLayout(new BorderLayout());
        pnl2.add(box);
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
	

        container.add(pnl);
        setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
		}

	public void actionPerformed(ActionEvent event) {
		if (event.getSource().equals(btn1)) {
		    String searchParam = txt1.getText().trim();
		    if (searchParam.trim().length() == 0) {
			String txtCheck = "Enter Query String";


			txtArea.setText(txtCheck);
             return;
		    }
			else

		    	searchString = "inurl:" + txt1.getText()+ "%20FileType:" + box.getSelectedItem() ;
				 System.out.println(searchString);//check output is correct	
				 try {
					 Search SearchObject = new Search();
					 SearchObject.searchGoog(searchString);
					    txtArea.setText(SearchObject.getLine());
					    return;
					} catch (Exception ex) {
					    ex.printStackTrace();

					}

		    }
			}



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



	public void itemStateChanged(ItemEvent arg0) {
		// TODO Auto-generated method stub
		
	}


}

Open in new window

0
 
for_yanCommented:
Seems fine to me.
You probably do not need "else" after the "if" with
return; inside, but this does not hurt and should work with else or without else in this case.
0
 
k3eperAuthor Commented:
Very helpful as always
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 28
  • 20
Tackle projects and never again get stuck behind a technical roadblock.
Join Now