KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sample > google > search > GUIHandler


1 /*
2 * Copyright 2001-2004 The Apache Software Foundation.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */

16
17 package sample.google.search;
18
19 import org.apache.axis2.engine.AxisFault;
20 import sample.google.common.util.PropertyLoader;
21
22 import javax.swing.*;
23 import java.awt.*;
24 import java.awt.event.ActionEvent JavaDoc;
25 import java.awt.event.ActionListener JavaDoc;
26 import java.awt.event.KeyEvent JavaDoc;
27 import java.awt.event.KeyListener JavaDoc;
28 import java.io.File JavaDoc;
29 import java.io.IOException JavaDoc;
30
31 /**
32  * Build and desplay the GUI
33  * implements both KeyListner and ActionListner
34  * KeyListner is used to detect space or Enter key at textField
35  * ActionListner is used for menu cammands
36  * Thread is run to isolate the GUI from internal actions
37  *
38  * @author Gayan Asanka (gayan@opensource.lk)
39  */

40 public class GUIHandler {
41     private static final String JavaDoc HELP_FILE_NAME = "/docs/GoogleSearchHelp.html";
42     /**
43      * Results are desplayed here
44      */

45     private JEditorPane textEditorPane;
46
47     /**
48      * Query parameters typed here
49      * */

50     private JTextField textBox;
51
52     /**
53      * Buttons clicked to view more results and backButton
54      */

55     private JButton nextButton, backButton;
56
57     /**
58      * Menu commands to set the key and maximum no of results per page
59      */

60     private JMenuItem keyMenuItem, maxResultsMenuItem;
61     private AsynchronousClient asyncClient ;
62
63     public GUIHandler(AsynchronousClient asyncClient) {
64         this.asyncClient = asyncClient;
65     }
66
67     /**
68      * Build the GUI using awt and swing components
69      */

70
71
72     public void buildFrame() {
73         JFrame frame;
74         SpringLayout layout;
75         JMenuBar menuBar;
76         JMenu settingsMenu;
77         Spring xSpring, ySpring, hSpring, wSpring;
78
79         frame = new JFrame("Google Search");
80         frame.setResizable(false);
81         layout = new SpringLayout();
82         Container pane = frame.getContentPane();
83         pane.setLayout(layout);
84
85         menuBar = new JMenuBar();
86         frame.setJMenuBar(menuBar);
87         settingsMenu = new JMenu("Settings"); // Create Set menu
88
menuBar.add(settingsMenu);
89
90         keyMenuItem = new JMenuItem("Key");
91         keyMenuItem.addActionListener(new ActionListener JavaDoc(){
92             public void actionPerformed(ActionEvent JavaDoc e) {
93                 setKey();
94             }
95         });
96         settingsMenu.add(keyMenuItem);
97
98         maxResultsMenuItem = new JMenuItem("Result per page");
99         maxResultsMenuItem.addActionListener(new ActionListener JavaDoc(){
100             public void actionPerformed(ActionEvent JavaDoc e) {
101                 setMaxResults();
102             }
103         });
104         settingsMenu.add(maxResultsMenuItem);
105         maxResultsMenuItem.setEnabled(true);
106         maxResultsMenuItem.setToolTipText("This feature is currently disabled!");
107
108         JMenu helpMenu = new JMenu("Help");
109         JMenuItem mnuItemHelp = new JMenuItem("Show Help");
110         helpMenu.add(mnuItemHelp);
111         mnuItemHelp.addActionListener(new ActionListener JavaDoc() {
112             public void actionPerformed(ActionEvent JavaDoc e) {
113                 showHelp();
114             }
115         });
116         menuBar.add(helpMenu);
117
118         Toolkit theKit = frame.getToolkit(); // Get the window toolkit
119
Dimension wndSize = theKit.getScreenSize(); // Get screen size
120
// Set the position to screen center & size to half screen size
121
frame.setBounds(wndSize.width / 6, wndSize.height / 10, // Position
122
wndSize.width * 3 / 5, wndSize.height * 3 / 4); // Size
123
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
124
125         nextButton = new JButton("More Results");
126         pane.add(nextButton);
127         nextButton.addActionListener(new ActionListener JavaDoc(){
128             public void actionPerformed(ActionEvent JavaDoc e) {
129                 processNextButton();
130             }
131         });
132
133         backButton = new JButton("Previous Page");
134         backButton.setVisible(false);
135         pane.add(backButton);
136         backButton.addActionListener(new ActionListener JavaDoc(){
137             public void actionPerformed(ActionEvent JavaDoc e) {
138                 processBackButton();
139             }
140         });
141
142         textEditorPane = new JEditorPane();
143         textEditorPane.setEditable(false);
144         textEditorPane.setContentType("text/html");
145         textEditorPane.addHyperlinkListener(new LinkFollower());
146         JScrollPane scroll = new JScrollPane(textEditorPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
147                 JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
148         pane.add(scroll);
149
150
151
152
153         textBox = new JTextField();
154         textBox.addKeyListener(new KeyListener JavaDoc(){
155             public void keyPressed(KeyEvent JavaDoc e) {}
156             public void keyReleased(KeyEvent JavaDoc e) {}
157             public void keyTyped(KeyEvent JavaDoc e) {
158                 processKeyEvent(e.getKeyChar());
159             }
160         });
161
162         pane.add(textBox);
163
164         SpringLayout.Constraints textBoxConstraints = layout.getConstraints(textBox);
165         xSpring = Spring.constant(0); // Spring we値l use for X
166
ySpring = Spring.constant(0); // Spring we値l use for Y
167
wSpring = Spring.constant(frame.getBounds().width-8); // Spring we値l use for width
168
hSpring = Spring.constant(30); // Strut we値l use for height
169
textBoxConstraints.setWidth(wSpring); // Set component width constraint
170
textBoxConstraints.setHeight(hSpring);
171         textBoxConstraints.setX(xSpring); // Set the WEST edge constraint
172
textBoxConstraints.setY(ySpring);
173
174         SpringLayout.Constraints scrollConstraints = layout.getConstraints(scroll);
175 // SpringLayout.Constraints scrollConstraints = layout.getConstraints(textEditorPane);
176
xSpring = Spring.constant(0); // Spring we値l use for X
177
ySpring = Spring.constant(30); // Spring we値l use for Y
178
wSpring = Spring.constant(frame.getBounds().width-8); // Spring we値l use for width
179
hSpring = Spring.constant(450); // Strut we値l use for height
180
scrollConstraints.setWidth(wSpring); // Set component width constraint
181
scrollConstraints.setHeight(hSpring);
182         scrollConstraints.setX(xSpring); // Set the WEST edge constraint
183
scrollConstraints.setY(ySpring); // Set the NORTH edge constraint
184

185         SpringLayout.Constraints backBtnConstraints = layout.getConstraints(backButton);
186         xSpring = Spring.constant(50); // Spring we値l use for X
187
ySpring = Spring.constant(480); // Spring we値l use for Y
188
wSpring = Spring.constant(200); // Spring we値l use for width
189
hSpring = Spring.constant(30); // Strut we値l use for height
190
backBtnConstraints.setWidth(wSpring); // Set component width constraint
191
backBtnConstraints.setHeight(hSpring);
192         backBtnConstraints.setX(xSpring); // Set the WEST edge constraint
193
backBtnConstraints.setY(ySpring);
194
195         SpringLayout.Constraints nextBtnConstraints = layout.getConstraints(nextButton);
196         xSpring = Spring.constant(250); // Spring we値l use for X
197
ySpring = Spring.constant(480); // Spring we値l use for Y
198
wSpring = Spring.constant(200); // Spring we値l use for width
199
hSpring = Spring.constant(30); // Strut we値l use for height
200
nextBtnConstraints.setWidth(wSpring); // Set component width constraint
201
nextBtnConstraints.setHeight(hSpring);
202         nextBtnConstraints.setX(xSpring); // Set the WEST edge constraint
203
nextBtnConstraints.setY(ySpring);
204         frame.setVisible(true);
205     }
206
207     /**
208      * method showResults
209      * desplay results by ClientCallbackHandler
210      *
211      * @param results
212      */

213     protected void showResults(String JavaDoc results) {
214         textEditorPane.setText(results);
215     }
216
217     /**
218      * method setKey
219      * Get the key from user via an inputDialog and
220      * store it in the properties file
221      */

222     protected void setKey() {
223         String JavaDoc key = JOptionPane.showInputDialog(null,"Set the Google Key",PropertyLoader.getGoogleKey());
224         if (key!=null && !key.trim().equals("")){
225             PropertyLoader.setGoogleKey(key);
226         }
227     }
228
229     private void processBackButton(){
230         if (asyncClient.getStartIndex() != 0) {
231             int i = Integer.parseInt(asyncClient.getMaxResults());
232             asyncClient.setStartIndex(asyncClient.getStartIndex() - i);
233             if (asyncClient.getStartIndex() == 0) {
234                 backButton.setVisible(false);
235             }
236             doSearch();
237         }
238     }
239     /**
240      * method keyTyped
241      * fires when user typing in TextField textBox
242      * act when detects space and Enter key only
243      *
244      * @param event
245      */

246     private void processKeyEvent(int event) {
247         if (event == KeyEvent.VK_SPACE || event == KeyEvent.VK_ENTER) {
248             asyncClient.setSearch(textBox.getText().trim());
249             if (!asyncClient.getPrevSearch().equals(asyncClient.getSearch())) {
250                 doSearch();
251             }
252         }
253     }
254
255     /**
256      * method showHelp
257      */

258     private void showHelp() {
259
260         JFrame frame= new JFrame();
261         Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
262         frame.setLocation(screenSize.width/5,
263                 screenSize.height/5);
264         frame.setSize(screenSize.width/2,screenSize.height/2);
265
266         BorderLayout layout = new BorderLayout();
267
268         JScrollPane jsp ;
269         JEditorPane jep;
270
271         jep = new JEditorPane();
272         jep.addHyperlinkListener(new LinkFollower());
273         jep.setEditable(false);
274         jep.setContentType("text/html");
275
276         jsp = new JScrollPane(jep);
277
278         Container contentPane = frame.getContentPane();
279         contentPane.setLayout(layout);
280         contentPane.add(jsp, BorderLayout.CENTER);
281         String JavaDoc helpDoc = System.getProperty("user.dir")+HELP_FILE_NAME;
282
283         try {
284             jep.setPage(new File JavaDoc(helpDoc).toURL());
285         } catch (IOException JavaDoc e) {
286             JOptionPane.showMessageDialog(null,"Help file not detected","Help file error",JOptionPane.ERROR_MESSAGE);
287             return;
288         }
289         frame.setVisible(true);
290     }
291
292
293     private void processNextButton() {
294         int i = Integer.parseInt(asyncClient.getMaxResults());
295         asyncClient.setStartIndex(asyncClient.getStartIndex() + i);
296         backButton.setVisible(true);
297         doSearch();
298     }
299
300     private void setMaxResults() {
301         String JavaDoc maxResults =
302                 JOptionPane.showInputDialog(null,
303                         "Enter the number of maximum results per page (Maximum allowed is 10)",asyncClient.getMaxResults());
304         if (maxResults==null){
305             return;
306         }else{
307             try {
308                 asyncClient.setMaxResults(Integer.parseInt(maxResults) +"");
309                 asyncClient.setPrevSearch("");
310             } catch (NumberFormatException JavaDoc e) {
311                 return;
312             }
313
314         }
315
316     }
317
318
319     private void doSearch(){
320         new ClientThread().run();
321
322     }
323
324     private class ClientThread implements Runnable JavaDoc{
325         /**
326          * method run
327          * check the flag doSearch
328          * if it's set, call sendMsg method
329          */

330         public void run() {
331             if (!asyncClient.getSearch().equals(asyncClient.getPrevSearch())) {
332                 asyncClient.setStartIndex(0);
333                // return;
334
}
335             try {
336                 asyncClient.sendMsg();
337             } catch (AxisFault axisFault) {
338                 axisFault.printStackTrace();
339             }
340         }
341     }
342 }
Popular Tags