• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 284
  • Last Modified:

EventAction Java

I have been trying to teach myself Java, have completed various tuts and the "Java In easy steps 4th Edition". I have a basic understanding but Im finding it difficult to find advanced tuts on things like advanced actions that can be perfromed by clicking a JButton for instance.

Particularly Im trying to understand how to perform URL actions for instance click a button and a search runs off on google (using its ajax API).

Can anyone point me in the direction of some tutorials or some ideas on how that could be achieved (just the action interaction with URL)
0
k3eper
Asked:
k3eper
  • 16
  • 10
  • 7
1 Solution
 
k3eperAuthor Commented:
Thank you for the reponse, ive come across this already but the understanding im after is how to Action something like a search using a JButton. I can create a non gui script that does what i want i just dont know how to action the JButton :( hope that makes sense.
0
 
CEHJCommented:
Add an actionListener to the button, or, preferably, create it with an Action:

http://www.exampledepot.com/egs/javax.swing/button_Button.html
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:
I think there is a bit of confusion in what you are asking.

There are two distinct things there - they may happen to be related in the flow of your application, but they have not much in common in the sense
of mastering and learning.
You either want to understand how events are working in Java, or how to go to URL, search google from Java  code, etc.

As I'm guessing from this reamark

>but the understanding im after is how to Action something like a search using a JButton

  you are probably interested in the events. If so, please understand  from the beginning that event handling is general
and after you know how to handle events you can then respond to the event either by going to some URL or
by filling in the textbox in your java application window - the general pattern of your actions will still stay the same.

So if you want to read about event handling in Java GUI, you can read here:
http://download.oracle.com/javase/tutorial/uiswing/events/intro.html
or here
http://my.execpc.com/~gopalan/java/dragger.html
(this is rather old reference, but the ideas stay the same)
or other links you can get by googling Java Event Model


So read some of this and ask questions if something is not clear.




 
0
 
k3eperAuthor Commented:
Thanks for the responses, I think I am on the right track now.

Ive created a seporate class for the search function. and am trying to call it from the main class.

Now i have another issue, how do i capture the output from the search and place it in the (txtArea) in the main class?

Im not sure how to use the JSONObject (its part of the code supplied by Google http://code.google.com/apis/websearch/docs/#The_Hello_World_of_Google_Search)


import java.awt.event.*;
import java.io.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

class Goog extends JFrame implements ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -9121626341050251232L;
	
	JPanel pnl = new JPanel();
	JTextField txt1 = new JTextField(20);
	JButton btn1 = new JButton("Search");
	JTextArea txtArea = new JTextArea(30,30);
	
	public Goog()
	{
		super("Swing Window");
		setSize(500, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		add(pnl);
		setVisible(true);
		pnl.add(btn1);
		pnl.add(txt1);
		pnl.add(txtArea);
	}
	
	public void actionPerformed(ActionEvent event) {
		if (event.getSource()==btn1)
		{	Search SearchObject = new Search();
			try {
				SearchObject.searchGoog();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	public static void main (String[] args) throws IOException{
		
		new Goog();
	}
	
}



CLASS CALLED


import java.io.*;
import java.net.*;
import net.sf.json.JSONObject;

public class Search {
	public void searchGoog() throws IOException {
	URL url = new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=TEST");
	URLConnection connection = url.openConnection();

	String line;
	StringBuilder builder = new StringBuilder();
	BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	while((line = reader.readLine()) != null) {
	builder.append(line);
	}
	JSONObject json = new JSONObject(builder.toString());
	
}
	
}

Open in new window

0
 
for_yanCommented:

You can add  to your search class method which will return to you the required piece of data , sya , public String getText() { return ...;} and you'll then sertText on your txtbox, sometyhing like

Search SearchObject = new Search();
			try {
				SearchObject.searchGoog();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
   }
String text = searchObject.getText();

txtArea.setText(text);

Open in new window

0
 
for_yanCommented:

To read JSON is quite another question.
You can download a class librarys that will do it.
Let me find a link for you.
0
 
for_yanCommented:
0
 
for_yanCommented:

try to download class library ofr dealing with JSON here:

http://findjar.com/jar/net/sf/json-lib/json-lib/2.3/json-lib-2.3-jdk15.jar.html
0
 
for_yanCommented:

You can slo check this one about parsing and writing JSON and
where to get library:
http://www.experts-exchange.com/Programming/Languages/Java/Q_27068225.html
0
 
k3eperAuthor Commented:
Im not able to getText from the line variable any ideas?
import java.io.*;
import java.net.*;


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

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

Open in new window

0
 
k3eperAuthor Commented:
Trying to get that data from line into a JTextArea called txtArea.
0
 
for_yanCommented:

why is that on line 18:
builder.append(getLine());

You need first to read text from connection.

Try to exeute first this metod
and let us know if you can print the output to System.out for the beginning:

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


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

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

Open in new window

0
 
for_yanCommented:
correction of the moisprints in the line 22 above:

System.out.println(builder.toString());
0
 
for_yanCommented:
After you see that you can read and print the text,
then show your code which creates the GUI.
Once you have the text and have properly
created GUI you just say txtArea.setText(line);
and textArea should be populated with text.
0
 
k3eperAuthor Commented:
thanks for the responses, ive tried that and im still not getting anthing in the textArea field. Code is attached.


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


class Main extends JFrame implements ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	JPanel pnl = new JPanel();
	JTextField txt1 = new JTextField(20);
	JButton btn1 = new JButton("Search");
	JTextArea txtArea = new JTextArea(30,30);
	
	public Main()
		{
		super("Swing Window");
		setSize(500, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		add(pnl);
		setVisible(true);
		pnl.add(btn1);
		pnl.add(txt1);
		pnl.add(txtArea);
		btn1.addActionListener(this);
		}
	
	public void actionPerformed(ActionEvent event)
	{
		if (event.getSource()==btn1)
		{ Search SearchObject = new Search();
		txtArea.setText(SearchObject.line);
		}
	}
	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() throws IOException {
        
	URL url = new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=test");
	URLConnection connection = url.openConnection();
        
        
        
	StringBuilder builder = new StringBuilder();
	BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	while((line = reader.readLine()) != null) {
	builder.append(line);
        
	}
	
System.out.println(builder.toString());
    }
 public String getLine() {
        return line;
    
    }

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

Open in new window

0
 
k3eperAuthor Commented:
I just tried something which came back with an odd result I thought.

Line 34 i added txtArea.setText(event.getActionCommand() + "\n" + (SearchObject.line));

I would expect it show the actioncommand of course and the line string data.

but the results are

Searchnull


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


class Main extends JFrame implements ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	JPanel pnl = new JPanel();
	JTextField txt1 = new JTextField(20);
	JButton btn1 = new JButton("Search");
	JTextArea txtArea = new JTextArea(30,30);
	
	public Main()
		{
		super("Swing Window");
		setSize(500, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		add(pnl);
		setVisible(true);
		pnl.add(btn1);
		pnl.add(txt1);
		pnl.add(txtArea);
		btn1.addActionListener(this);
		}
	
	public void actionPerformed(ActionEvent event)
	{
		if (event.getSource()==btn1)
		{ Search SearchObject = new Search();
		txtArea.setText(event.getActionCommand() + "\n" + (SearchObject.line));
		}
	}
	public static void main (String[] args)
	{
	new Main();
	}
}

Open in new window

0
 
for_yanCommented:
OK, this works

There is still some issue with  layouts - but you can click and see how it populates the text box.

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


class Main extends JFrame implements ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	
	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(30,30);
            txtArea.setLineWrap(true);

           Container c = this.getContentPane();



           pnl.setLayout(new BorderLayout());
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(txtArea);
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
            c.add(pnl);
            setSize(500, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
            	setVisible(true);
		}
	
	public void actionPerformed(ActionEvent event)
	{
		if (event.getSource().equals(btn1))
		{
            System.out.println("ttt");
            Search SearchObject = new Search();
            try{
            SearchObject.searchGoog();
            }catch(Exception ex){
                ex.printStackTrace();
            }
		txtArea.setText(SearchObject.getLine());
		}
	}
	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() throws IOException {
        
	URL url = new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=test");
	URLConnection connection = url.openConnection();
        
                   System.out.println("Im here");
        
	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
 
for_yanCommented:

OK, replace the first class - thiis one has normal layout:

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


class Main extends JFrame implements ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	
	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 c = this.getContentPane();
            c.setLayout(new BorderLayout());



           pnl.setLayout(new BorderLayout());
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
            c.add(pnl);
            setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
            	setVisible(true);
		}
	
	public void actionPerformed(ActionEvent event)
	{
		if (event.getSource().equals(btn1))
		{
            System.out.println("ttt");
            Search SearchObject = new Search();
            try{
            SearchObject.searchGoog();
            }catch(Exception ex){
                ex.printStackTrace();
            }
		txtArea.setText(SearchObject.getLine());
		}
	}
	public static void main (String[] args)
	{
	new Main();
	}
}

Open in new window

0
 
k3eperAuthor Commented:
Thank you,

so what did i do wrong?
0
 
for_yanCommented:
You did many things in rather strange way, in particular
these windows layouts, etc.
But the main thing why it was not working, I think was that - you created an instance variable line,
which should have been populated with the resulting string in Search and then you should have grabbed it froim Main and
setText of the textArea to that line.
In fact, you were usiong this variable line for some temporary needs - when
doing that:

while((line = reader.readLine()) != null) {
      builder.append(line);
       
      }
so in the end of this operation value of line was becoming null (end of file)
and yes, you pouplated with contents StringBuilder builder,
but you never assigned contents of the stringbuilder to line.

So in fact you should not have been using instance variable
line for temporary purposes, and after
population of string builder you should have assigned
its contents to line so that when you grab this line using getLine() method of Search from Main
you should be getting line populated woth data.
So, I changed:


String buff = null;  <---- local variable for temp purposes
while((buff = reader.readLine()) != null) {
      builder.append(buff);
       
      }

line = builder.toString();  <--- assigning what we accumulated in builder to line




0
 
CEHJCommented:
You can simplify your code greatly. The Search class doesn't need to maintain state - it's a utility class effectively so can be as follows. Also reading line-wise is an unnecessary inefficiency

(See http://technojeeves.com/joomla/index.php/free/51-copying-streams )
import java.io.*;
import net.proteanit.io.IOUtils;
import java.net.*;


public class Search {
    public String line;

    public static String searchGoog() throws IOException {
        return IOUtils.inputStreamToString(new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=test").openStream());
    }

}

Open in new window

0
 
CEHJCommented:
But... you probably want to pass the search parameter to the Search class
0
 
CEHJCommented:
That would make your two methods look like this (and this works fine for me)
public static String searchGoog(String params) throws IOException {
        return IOUtils.inputStreamToString(new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + params).openStream());
    }
...................


    public void actionPerformed(ActionEvent event) {
        if (event.getSource().equals(btn1)) {

            try {
		txtArea.setText(Search.searchGoog(txt1.getText()));
	    } catch (Exception ex) {
		ex.printStackTrace();
	    }

	}
    }

Open in new window

0
 
for_yanCommented:

These are your classes with serach parameter passed
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class Main extends JFrame implements ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	JPanel pnl ;
	JTextField txt1 ;
	JButton btn1 ;
	JTextArea txtArea ;
	
	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 c = this.getContentPane();
            c.setLayout(new BorderLayout());



           pnl.setLayout(new BorderLayout());
		pnl1.add(btn1);
		pnl1.add(txt1);
        pnl.add(pnl1,BorderLayout.NORTH);
		pnl2.add(new JScrollPane(txtArea));
        pnl.add(pnl2, BorderLayout.CENTER);
		btn1.addActionListener(this);
            c.add(pnl);
            setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
            	setVisible(true);
		}
	
	public void actionPerformed(ActionEvent event)
	{
		if (event.getSource().equals(btn1))
		{
            System.out.println("ttt");
            String searchString = txt1.getText();
            Search SearchObject = new Search();
            try{
            SearchObject.searchGoog(searchString);
            }catch(Exception ex){
                ex.printStackTrace();
            }
		txtArea.setText(SearchObject.getLine());
		}
	}
	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();
        
                   System.out.println("Im here");
        
	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
 
for_yanCommented:
You definitely don't want to carry with you third party libraries if there is no great need for them
0
 
CEHJCommented:
It's not a 'third party library'. Just an extra class. It doesn't matter whose extra class it is. What *does* matter is that you should try to leverage tested, reusable code in your programming. This is simply good and professional practice
0
 
for_yanCommented:
You sure could have put all  functionality into one class in this case, but if you chose to
have two classes for that that is not a bad thing, especially for the learning purposes.

But you certainly  don't want to add even more classes for doing standard things, especially
written by someone else - suppose there is some problem - it is pain to debug
such things. The simpler is your program - the better.

0
 
k3eperAuthor Commented:
thank you very much for your responses, I do plan on add quite a bit more to the funcitonality. The Base code of the search is given by Google and they used JSON originally.

My next step was to search using the imput field (youve added it already tho thanks again) Now i want to add a few more things, if I get stuck and cant work it out myself using google etc I will ask on here again. Thank you

0
 
k3eperAuthor Commented:
O forgot to add, i didnt work on any of the layout yet as i wanted to get the search results to screen first ;)
0
 
CEHJCommented:
>>But you certainly  don't want to add even more classes for doing standard things

That's exactly why you DO add classes - because standard things are reusable. Rewriting the same code over and over again to do that is not only a waste of time, it's an error-prone waste of time.

I wrote that class either before i knew of the existence of http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html or before it existed. I suggest you use these routines. They will save you a lot of time.
0
 
k3eperAuthor Commented:
Very helpful and descriptive
0
 
for_yanCommented:
You are always welcome.
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 16
  • 10
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now