k3eper
asked on
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)
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)
See http://stackoverflow.com/questions/3727662/how-can-you-search-google-programmatically-java-api
ASKER
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.
Add an actionListener to the button, or, preferably, create it with an Action:
http://www.exampledepot.com/egs/javax.swing/button_Button.html
http://www.exampledepot.com/egs/javax.swing/button_Button.html
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.
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.
ASKER
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)
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());
}
}
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);
To read JSON is quite another question.
You can download a class librarys that will do it.
Let me find a link for you.
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
You can slo check this one about parsing and writing JSON and
where to get library:
https://www.experts-exchange.com/questions/27068225/Java-JSON-and-complex-class-w-arraylist-of-hashmap.html
ASKER
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;
}
}
ASKER
Trying to get that data from line into a JTextArea called txtArea.
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;
}
}
correction of the moisprints in the line 22 above:
System.out.println(builder .toString( ));
System.out.println(builder
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.
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.
ASKER
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();
}
}
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;
}
}
ASKER
I just tried something which came back with an odd result I thought.
Line 34 i added txtArea.setText(event.getA ctionComma nd() + "\n" + (SearchObject.line));
I would expect it show the actioncommand of course and the line string data.
but the results are
Searchnull
Line 34 i added txtArea.setText(event.getA
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();
}
}
OK, this works
There is still some issue with layouts - but you can click and see how it populates the text box.
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();
}
}
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;
}
}
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();
}
}
ASKER
Thank you,
so what did i do wrong?
so what did i do wrong?
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
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
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 )
(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());
}
}
But... you probably want to pass the search parameter to the Search class
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();
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You definitely don't want to carry with you third party libraries if there is no great need for them
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
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.
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.
ASKER
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
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
ASKER
O forgot to add, i didnt work on any of the layout yet as i wanted to get the search results to screen first ;)
>>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.
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.
ASKER
Very helpful and descriptive
You are always welcome.