Searching Vectors

If I add several of these objects:
     //A customer
     public PGVideoCust(String first, String last, String address, String address2, String phone, String custID)
          firstName = first;
          lastName = last;
          streetAddress = address;
          cityStateZip = address2;
          phoneNumber = phone;
          ID = custID;
          videosOut.addElement("None");
     } //end customer
to a vector.. How can i go about searching the vector for ID not just searching for an object in the vector. I tried (vector is customers) customers.indexOf(12432) where 12432 is a valid ID of one of the objects in the vector but it returns -1 everytime.. Understand what I'm trying to do?

I understand. You need to look at each entry, cast as the object you expect it to be, then test the ID...
Vector stuff = new Vector(0);
for(int a = 0; a < stuff.size(); a++){
  // Will throw classCastException if not the right type.
  myObject X = (myObject)stuff.get(a);
  if(X.ID == mySearch){
    // You found it.
}In similar cases where I know that I'll be storing things based on some known criteria, like an ID, I prefer to use a Hashtable instead. The hashtable stores the goods and all you have to do is ask for the ID like this....
Hashtable HT = new Hashtable();
// Store your goodies...
HT.put(
  myCustomer.ID, // must be an Object so Integer not int
  myCustomer);
// get the goodies...
myCustomer = HT.get(theID // Again.  Integer);

Similar Messages

  • Searching a vector

    Ok, second post. I gave up on the whole array idea and moved to vectors. I got it reading the text file and adding to the vector succesfully. Now I need to search that vector. The text file looks like this:
    9876543 9876543 Y
    0612207 0612207 N
    0123456 0123456 N
    1234567 1234567 Y
    Here's my code so far:
    import java.*;
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class EmailForms extends JFrame implements ActionListener {
         private JTextField jtfUserName;
         private JPasswordField jpfPassword;
         private JButton jbtLogin;
         private JButton jbtCancel;
         Vector LoginData = new Vector();
         public static void main (String[] args) {     
              EmailForms LoginFrame = new EmailForms();
              LoginFrame.setSize(200, 100);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              int screenWidth = screenSize.width;
              int screenHeight = screenSize.height;
              Dimension frameSize = LoginFrame.getSize();
              int x = (screenWidth - frameSize.width)/2;
              int y = (screenHeight - frameSize.height)/2;
              LoginFrame.setLocation(x, y);
              LoginFrame.pack();
              LoginFrame.setVisible(true);     
         public EmailForms () {     
              try {     
                   String UP1Line;
                   FileInputStream fis = new FileInputStream("UP1.txt");
                  BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                  while ((UP1Line = br.readLine()) != null) {
                        StringTokenizer st = new StringTokenizer(UP1Line, " ");
                        while (st.hasMoreTokens()) {
                          LoginData.addElement(st.nextToken());
                    br.close();
                    fis.close();
              catch (IOException ex){
                   JOptionPane.showMessageDialog(this, "Fatal Systems Error", "Email Forms: File Error 1",
                   JOptionPane.INFORMATION_MESSAGE);
                   System.exit(0);     
              catch (NullPointerException ex){
                   JOptionPane.showMessageDialog(this, "Fatal Systems Error", "Email Forms: File Error 2",
                   JOptionPane.INFORMATION_MESSAGE);
                   System.exit(0);     
              setTitle("E-Forms: Login");
              JPanel jpLoginLabels = new JPanel();
              jpLoginLabels.setLayout(new GridLayout(2, 1));
              jpLoginLabels.add(new JLabel("Username:"));
              jpLoginLabels.add(new JLabel("Password:"));
              JPanel jpLoginText = new JPanel();
              jpLoginText.setLayout(new GridLayout(2, 1));
              jpLoginText.add(jtfUserName = new JTextField(10));
              jpLoginText.add(jpfPassword = new JPasswordField(10));
              JPanel p1 = new JPanel();
              p1.setLayout(new BorderLayout());     
              p1.add(jpLoginLabels, BorderLayout.WEST);
              p1.add(jpLoginText, BorderLayout.CENTER);
              JPanel p2 = new JPanel();
              p2.setLayout(new FlowLayout(FlowLayout.CENTER));     
              p2.add(jbtLogin = new JButton("Login"));
              p2.add(jbtCancel = new JButton("Cancel"));     
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(p1, BorderLayout.CENTER);
              getContentPane().add(p2, BorderLayout.SOUTH);
              jbtLogin.addActionListener(this);
              jbtCancel.addActionListener(this);
         public void actionPerformed(ActionEvent e) {
              String arg = e.getActionCommand();
              int index = find(jtfUserName.getText().trim(), new String(jpfPassword.getPassword()));
              if (arg == "Cancel") {
                   System.exit(0);
                   arg = "";
              if (arg == "Login") {
                   if (index == -1) {
                        JOptionPane.showMessageDialog(this, "Username/Password Not Found", "Email Forms: Login Error",
                        JOptionPane.INFORMATION_MESSAGE);
                   else {
                        if (index == 1 ){
                             JOptionPane.showMessageDialog(this, "Username and Password Found: Admin", "Email Forms: Good",
                             JOptionPane.INFORMATION_MESSAGE);
                        else {
                             JOptionPane.showMessageDialog(this, "Username and Password Found: User", "Email Forms: Good",
                             JOptionPane.INFORMATION_MESSAGE);          
              arg = "";
         public int find(String UName, String PWord) {
              for (int i = 0; i < LoginData.size(); i++) {                                        
                   // if ((first.element.of.first.line.UName  == LoginData.elementAt(i)) && (second.element.of.first.line.PWord == LoginData(i))) {
                   //          if (third.element.of.first.line.yes or no admin == "Y") {
                   //               goto adminside;
                   //               return 1; }
                   //          else {
                   //               goto userside;
                   //               return 2;
              return -1;
    }Essentially this is a login method. The standard username and password. The kicker is the third entry in each line of the vector "Y" or "No". This entry denotes whether or not the user is an admin. If he/she is an admin, they go to an admin program else he/she is a regular user and goes to the user program. I've done some reading on searching vectors in this forum as well as others, but none have I have read have tackled this third entry. Can someone have a look and give me their opinion.
    Thanks in advance,
    Colin

    Here you go:
    1. Use a HashMap to look up credentials.
    2. Use regular expressions to check for certain values
    The code does what you need (just checked it), but you probably wouldn't save the credentials as a "String[]" array. So there's room for improvement ;)
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class EmailForms extends JFrame implements ActionListener {
         private static final long serialVersionUID = -6409081110711705001L;
         private JTextField jtfUserName;
         private JPasswordField jpfPassword;
         private JButton jbtLogin;
         private JButton jbtCancel;
         private HashMap<String, String[]> users;
         public static void main (String[] args) {     
              EmailForms LoginFrame = new EmailForms();
              LoginFrame.setSize(200, 100);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              int screenWidth = screenSize.width;
              int screenHeight = screenSize.height;
              Dimension frameSize = LoginFrame.getSize();
              int x = (screenWidth - frameSize.width)/2;
              int y = (screenHeight - frameSize.height)/2;
              LoginFrame.setLocation(x, y);
              LoginFrame.pack();
              LoginFrame.setVisible(true);     
         public EmailForms () {     
              users = new HashMap<String, String[]>();
              try {     
                   String UP1Line;
                   FileInputStream fis = new FileInputStream("UP1.txt");
                  BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                  while ((UP1Line = br.readLine()) != null) {
                       String [] items = UP1Line.split(" ", 4);     //max. 6 tokens, separated by semicolon
                       users.put(items[0], new String[] { items[1], items[2] });
                       if (items[2].matches("[Yy]"))
                            System.err.println("y");
                       else
                            System.err.println("n");
                    br.close();
                    fis.close();
              catch (IOException ex){
                   JOptionPane.showMessageDialog(this, "Fatal Systems Error", "Email Forms: File Error 1",
                   JOptionPane.INFORMATION_MESSAGE);
                   System.exit(0);     
              catch (NullPointerException ex){
                   JOptionPane.showMessageDialog(this, "Fatal Systems Error", "Email Forms: File Error 2",
                   JOptionPane.INFORMATION_MESSAGE);
                   System.exit(0);     
              setTitle("E-Forms: Login");
              JPanel jpLoginLabels = new JPanel();
              jpLoginLabels.setLayout(new GridLayout(2, 1));
              jpLoginLabels.add(new JLabel("Username:"));
              jpLoginLabels.add(new JLabel("Password:"));
              JPanel jpLoginText = new JPanel();
              jpLoginText.setLayout(new GridLayout(2, 1));
              jpLoginText.add(jtfUserName = new JTextField(10));
              jpLoginText.add(jpfPassword = new JPasswordField(10));
              JPanel p1 = new JPanel();
              p1.setLayout(new BorderLayout());     
              p1.add(jpLoginLabels, BorderLayout.WEST);
              p1.add(jpLoginText, BorderLayout.CENTER);
              JPanel p2 = new JPanel();
              p2.setLayout(new FlowLayout(FlowLayout.CENTER));     
              p2.add(jbtLogin = new JButton("Login"));
              p2.add(jbtCancel = new JButton("Cancel"));     
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(p1, BorderLayout.CENTER);
              getContentPane().add(p2, BorderLayout.SOUTH);
              jbtLogin.addActionListener(this);
              jbtCancel.addActionListener(this);
         public void actionPerformed(ActionEvent e) {
              String arg = e.getActionCommand();
              int index = find(jtfUserName.getText().trim(), new String(jpfPassword.getPassword()));
              if (arg == "Cancel") {
                   System.exit(0);
                   arg = "";
              if (arg == "Login") {
                   if (index == -1) {
                        JOptionPane.showMessageDialog(this, "Username/Password Not Found", "Email Forms: Login Error",
                        JOptionPane.INFORMATION_MESSAGE);
                   else {
                        if (index == 1 ){
                             JOptionPane.showMessageDialog(this, "Username and Password Found: Admin", "Email Forms: Good",
                             JOptionPane.INFORMATION_MESSAGE);
                        else {
                             JOptionPane.showMessageDialog(this, "Username and Password Found: User", "Email Forms: Good",
                             JOptionPane.INFORMATION_MESSAGE);          
              arg = "";
         public int find(String UName, String PWord) {
              String [] creds = users.get(UName);
              if (creds!=null && creds[0].matches(PWord)) {
                   System.out.println("ok");
                   if (creds[1].matches("[Yy]"))
                        return 1;
                   else
                        return 0;
              System.err.println("not ok");
              return -1;
    }

  • Internet search engine

    hello iam trying to get the simple Java applet that searches multiple Internet search engines. can any one help me
    how to do in simple way....

    Hi,
    Please go through the above site you will find excellent codes.
    Anyhow here is the sample Applet Search engine code.
    import java.awt.*;
    import java.applet.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    // v1.5 Home Page Search applet
    // 15th February 1998
    * This applet provides search facilities for Web sites with no CGI access
    * Copyright (c) 1997 Richard Everitt G4ZFE
    * [email protected]
    * This program is free software; you can redistribute it and/or modify it
    * under the terms of the GNU General Public License as published by the
    * Free Software Foundation; either version 2 of the License, or (at your
    * option) any later version.
    * This program is distributed in the hope that it will be useful, but
    * WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    * General Public License for more details.
    * You should have received a copy of the GNU General Public License along
    * with this program; if not, write to the Free Software Foundation, Inc.,
    * 675 Mass Ave, Cambridge, MA 02139, USA.
    /* Applet parameters:
    * This applet takes two parameters
    * a. hostname, the name of the Demon Home Page (e.g babbage). The name is
    * converted to lower case and used to create the URL of the
    * pages to search i.e. http://www.<hostname>.demon.co.uk.
    * (this parameter is required for Demon Internet users
    * only)
    * b. IPaddress, the corresponding IP address for the Home Page. I plan to
    * use it as it will allow the search applet to run from
    * behind a firewall. Demon have stated in the HomePage AUP
    * that the IP address should not be directly used. I do not
    * recommend its use (the www.babbage.demon.co.uk IP address
    * has already changed once)
    * (this parameter is optional)
    * c. maxSearch, the maximum number of pages to search. If your site is vast
    * then the search will take a long time so people will give
    * up. This parameter limits the number of pages to be searched
    * to a sensible value reducing the search time (but also
    * reducing its usefullness)
    * (this parameter is optional. Defaults to 100)
    * d. debug, this parameter is for my use. Set to true to display
    * parameter and debug information.
    * (this parameter is optional)
    * e. server, this parameter allows the search applet to be used on non-
    * Demon home pages. This parameter should point to the name
    * of the site, e.g "http://www.myisp.com/me/" (note use of
    * trailing "/" character.
    * (this parameter is required for Non-Demon Internet users)
    * f. indexName, this parameter allows the search applet to be used on non-
    * Demon home pages. This parameter should point to the name
    * of the index page (e.g home.htm). If not set then
    * "index.htm" ot "index.html" is asummed.
    * (this parameter is optional)
    * g. bgColour, The background colour for the applet in RGB hex format
    * (rrggbb). The default is light grey.
    * h. fgColour, The foreground colour for the applet in RGB hex format
    * (rrggbb). The default is black.
    * Example of applet use on a Demon Home Page - www.babbage.demon.co.uk
    * <APPLET CODE="HomePageSearch.class" WIDTH=650 HEIGHT=400>
    * <PARAM NAME="hostname" VALUE="babbage">
    * <EM>Sorry but the Search applet requires a Java aware
    * Web browser </EM>
    * </APPLET>
    * Example of applet use on a non-Demon Home Page - www.myisp.co.uk/fred/
    * and the "index" page is called home.htm
    * <APPLET CODE="HomePageSearch.class" WIDTH=650 HEIGHT=400>
    * <PARAM NAME="server" VALUE="http://www.myisp.co.uk/fred/">
    * <PARAM NAME="indexName" VALUE="home.htm">
    * <EM>Sorry but the Search applet requires a Java aware
    * Web browser </EM>
    * </APPLET>
    /* Modification history
    * xxxx 12th February - alpha version
    * v0.9 19th February - first beta version
    * v0.91 26th February - tidy up
    * - added maxSearch functionality
    * - added debugMode parameter
    * v0.92 03rd March - added server and indexname parameters to
    * allow use on non-Demon home pages
    * v0.93 09th March - fixed bug with lowercase filenames
    * added case insensitive/sensitive/match whole
    * word functionality
    * v0.94 12th March - fixed bug which resulted in "cannot connect"
    * error on non-demon sites.
    * v0.95 15th March - Removed some uses of debugMode. Server parameter
    * can be set to http://localhost/ to simulate this.
    * - Added support for working behind proxy servers/
    * firewalls. This uses the IP Address rather than
    * the hostname of the server for connections.
    * v0.96 17th March - Corrected code to parse HREFs. It was not
    * understanding framed format or spaces.
    * - Match whole word not working properly
    * - HREF="http://server/" was not being followed
    * correctly
    * v0.97 20th March - fixed bug where incorrect page name was being
    * displayed for a match. This was due to the use
    * of a global variable for the page name. As the
    * stack unwound then this variable was lost. Stack
    * used to stored page name instead.
    * v0.98 23rd March - if match found on index page (using HTTP) then URL to
    * jump to was created incorrectly.
    * v0.99 25th March - allow to be resized < 600 pixels
    * allow handling of links such as
    * "/www/page.html"
    * v1.0 8th April - Added bgColour, fgColour applet parameters
    * Set default of 100 for maximum number pages to search
    * Added option menu for number of pages to search
    * Allow handling of framed links such as
    * <FRAME SRC="framepage.html">
    * v1.1 18th April - Display Page title rather than page name in list of
    * matches.
    * If match found on index page (using FILE://) then
    * URL to jump to was created incorrectly.
    * Broke the <= 600 pixels code by adding the "Max
    * Pages" option menu. Size of buttons adjusted to
    * allow all widgets to be display in < 600 pixles
    * v1.2 9th May - Removed hard limits by using vectors rather than
    * arrays.
    * Search the index page and index page links first.
    * Added internalisation support for titles. A subset
    * of the special character entity names (e.g &egrave;)
    * are converted into Unicode characters so that they
    * are displayed correctly.
    * Fixed bug - "match word" did not match the last word
    * on a line.
    * v1.3 8th July - Bug fix release
    * Links with single quotes e.g
    * Test Page
    * were not being searched
    * fgColour and bgColour only worked with UNIX browsers!
    * Fixed to allow useage with MS Windows browsers,
    * although due to limitations in Win32 AWT the colour
    * of buttons and their text cannot be changed.
    * v1.4 4th August - Bug fix release
    * Single quote HREF fix in v1.3 broke some normal
    * HREF link code (no </A> on same line as HREF).
    * v1.5 15th February - Applet now searches .txt files
    * Fixed bug for demon internet users who use index
    * pages other than index.htm and index.html
    * Added further lower case localisation support
    public class HomePageSearch extends Applet
    final int MAX_NUMBER_PAGES = 100; // default limit of number
    // pages to read
    final int BACKSPACE_CHARACTER = 8; // ASCII backspace
    final int NUMBER_SPECIAL_CHARS = 45; // Number of special character
    // entity names supported
    Button search, clear, abort; // GUI buttons
    TextField inputArea; // TextField used to enter
    // search text in
    TextField statusArea; // TextField used to display
    // search status
    List resultsArea; // List to display matches in
    public String hostName; // Host name paramter read by
    // applet (required)
    public String IPAddress; // IP address parameter read by
    // applet (optional)
    public int maxSearch = MAX_NUMBER_PAGES;
    // Maximum number of pages to
    // search (optional)
    public boolean debugMode; // TRUE = localhost
    // FALSE = on-line
    Vector pageNames; // Pages that have been visited
    public String server; // Non-Demon home page starting point
    public String indexName; // Name of index page (defaults to
    // index.html or index.htm)
    SearchPages cp = null; // Search thread
    Checkbox caseSensitive;
    Checkbox caseInsensitive;
    Checkbox matchWholeWord;
    public boolean matchCase = false; // Flag to indicate if we
    // need to match case.
    public boolean matchWord = false; // Flag to indicate if we need
    // to match the whole word
    String versionNumber = "v1.5";
    boolean packComponents; // Set to true if size < 600
    Color bgColour; // Background colour of applet
    Color fgColour; // Foreground colour of applet
    Choice numPagesChoice; // Option menu to select max
    // number of pages to search
    Vector pageMatch; // Pages that contain the
    // search word
    public void init ()
    Panel p;
    getParameters (); // Read the applet parameters
    setLayout (new BorderLayout ());
    // If applet size is <= 600 pixels then reduce the length
    // of text fields, labels etc so that the applet will
    // display OK
    if (size().width <= 600)
    packComponents = true;
    else
    packComponents = false;
    // This panel consists of a input text field where the
    // user enters the text to search for. The buttons allow
    // the search to be started, aborted and clear the applet's
    // output fields.
    p = new Panel();
    p.setLayout (new FlowLayout());
    Label lab = new Label ("Search for: ");
    lab.setFont (new Font ("Helvetica", Font.PLAIN, 12));
    p.add (lab);
    if (packComponents)
    inputArea = new TextField ("",15);
    else
    inputArea = new TextField ("",20);
    p.add (inputArea);
    if (packComponents)
    search = new Button ("search");
    search.setFont (new Font ("Helvetica", Font.BOLD, 12));
    else
    search = new Button (" search ");
    search.setFont (new Font ("Helvetica", Font.BOLD, 14));
    p.add (search);
    if (packComponents)
    clear = new Button ("clear");
    clear.setFont (new Font ("Helvetica", Font.BOLD, 12));
    else
    clear = new Button (" clear ");
    clear.setFont (new Font ("Helvetica", Font.BOLD, 14));
    p.add (clear);
    if (packComponents)
    abort = new Button ("stop");
    abort.setFont (new Font ("Helvetica", Font.BOLD, 12));
    else
    abort = new Button (" stop ");
    abort.setFont (new Font ("Helvetica", Font.BOLD, 14));
    abort.disable();
    p.add (abort);
    if (packComponents)
    lab = new Label ("Pages");
    else
    lab = new Label (" Max. Pages:");
    lab.setFont (new Font ("Helvetica", Font.PLAIN, 12));
    p.add (lab);
    numPagesChoice = new Choice();
    p.add (numPagesChoice);
    p.setForeground (fgColour);
    p.setBackground (bgColour);
    add ("North",p);
    // This panel lists the results. When an item from the list
    // box is double clicked the URL is opened up.
    p = new Panel();
    p.setLayout (new GridLayout(0,1));
    resultsArea = new List (10,false);
    p.add (resultsArea);
    p.setForeground (fgColour);
    p.setBackground (bgColour);
    add ("Center",p);
    p = new Panel();
    Label labVersion = new Label (versionNumber);
    labVersion.setFont (new Font ("Helvetica", Font.PLAIN, 12));
    p.add (labVersion);
    CheckboxGroup caseSense = new CheckboxGroup();
    // This textfield shows the status of the search to provide
    // some feedback to the user. The page count is displayed.
    if (packComponents)
    statusArea = new TextField ("",14);
    else
    statusArea = new TextField ("",20);
    statusArea.setEditable (false);
    p.add (statusArea);
    if (packComponents)
    caseInsensitive = new Checkbox ("in-sensitive");
    else
    caseInsensitive = new Checkbox ("case in-sensitive");
    p.add (caseInsensitive);
    caseInsensitive.setCheckboxGroup (caseSense);
    if (packComponents)
    caseSensitive = new Checkbox ("sensitive" );
    else
    caseSensitive = new Checkbox ("case sensitive" );
    p.add (caseSensitive);
    caseSensitive.setCheckboxGroup (caseSense);
    caseSense.setCurrent (caseInsensitive);
    if (packComponents)
    matchWholeWord = new Checkbox ("whole word");
    else
    matchWholeWord = new Checkbox ("match whole word");
    p.add (matchWholeWord);
    p.setForeground (fgColour);
    p.setBackground (bgColour);
    add ("South",p);
    disableButtons (); // Disable buttons until text entered
    // Create vector to hold pages that have been found
    // and pages that contain the search text
    pageNames = new Vector();
    pageMatch = new Vector();
    // Now that we know what the maxSearch parameter is fill
    // in sensible page numbers
    for (int i=maxSearch / 5; i<= maxSearch; i += maxSearch / 5)
    numPagesChoice.addItem (Integer.toString(i));
    numPagesChoice.setFont (new Font ("Helvetica", Font.PLAIN, 12));
    // Set the default number of pages to be searched
    numPagesChoice.select (0);
    maxSearch = maxSearch / 5;
    // Set the background + foreground applet colours
    // setBackground(bgColour);
    // setForeground(fgColour);
    // Always set text input field to white for readability
    inputArea.setBackground (Color.white);
    // Function enableButtons
    // Purpose - enable use of buttons in GUI
    public void enableButtons ()
    search.enable();
    clear.enable();
    // Function disableButtons
    // Purpose - disable use of buttons in GUI
    final void disableButtons ()
    search.disable();
    clear.disable();
    // Function getParameters
    // Purpose - read applet parameters
    final void getParameters ()
    hostName = getParameter ("hostname");
    IPAddress = getParameter ("IPAddress");
    String num = getParameter ("maxSearch");
    String arg = getParameter ("debug");
    server = getParameter ("server");
    indexName = getParameter ("indexName");
    String colour = getParameter("bgColour");
    if (colour == null)
    // I wish this could be locali[sz]ed so that I could
    // write lightGrey !!
    bgColour = Color.lightGray;
    else
    try
    bgColour = new Color(Integer.parseInt(colour, 16));
    catch (NumberFormatException e)
    bgColour=Color.lightGray;
    colour = getParameter("fgColour");
    if (colour == null)
    fgColour = Color.black;
    else
    try
    fgColour = new Color(Integer.parseInt(colour, 16));
    catch (NumberFormatException e)
    bgColour=Color.black;
    // Check for missing parameters
    if (hostName == null && server == null)
    statusArea.setText ("Error - no host/server");
    System.out.println (" Error: No hostname specified");
    hostName = "none";
    maxSearch = (num == null) ? MAX_NUMBER_PAGES : Integer.parseInt(num);
    debugMode = (arg == null) ? false : true;
    if (debugMode)
    System.out.println ("hostname is " + hostName);
    System.out.println ("IPAddress is " + IPAddress);
    System.out.println ("maxSearch is " + maxSearch);
    System.out.println ("debugMode is " + debugMode);
    System.out.println ("server is " + server);
    System.out.println ("indexName is " + indexName);
    System.out.println ("bgColour is " + bgColour);
    System.out.println ("fgColour is " + fgColour);
    // Display parameter information
    public String[][] getParameterInfo()
    String[][] info =
    {"hostname","String","hostname of site"},
    {"IPAddress","String","IP address of site"},
    {"maxSearch","String","maximum number of pages to search"},
    {"debug","String","debug mode"},
    {"server","String","Home Page URL"},
    {"indexName","String","Name of index page"},
    {"bgColour","Color","Background colour of applet"},
    {"fgColour","Color","Foreground colour of applet"}
    return info;
    // Display applet information
    public String getAppletInfo()
    return "Home Page Search Applet v1.5";
    // Function keyDown
    // Purpose - enable or disable buttons. When search text is entered
    // the search and clear buttons are enabled. When no search text has
    // been entered the buttons are disabled.
    public boolean keyDown (Event e, int nKey)
    boolean boolDone = true;
    String text;
    text = inputArea.getText(); // Read the search text
    int n = text.length(); // Count number of chars
    if (nKey == BACKSPACE_CHARACTER)// catch backspace character
    boolDone = false;
    n--;
    else
    boolDone = false;
    n++;
    if (n > 0)
    enableButtons ();
    else
    disableButtons ();
    return (boolDone);
    // Purpose - this function handles all the GUI events
    public boolean action (Event e, Object o)
    String text; // Search text entered by user
    String searchText; // Lower case version of above
    URL newURL = null;
    // Check to see if the option menu has been selected
    if (e.target instanceof Choice)
    Choice c = (Choice) e.target;
    try
    maxSearch = Integer.parseInt(c.getSelectedItem(), 10);
    catch (NumberFormatException ex)
    maxSearch = MAX_NUMBER_PAGES;
    if (debugMode)
    System.out.println ("maxSearch is now " + maxSearch);
    // Check to see if a checkbox has been pressed
    if (e.target instanceof Checkbox)
    if (caseSensitive.getState() == true)
    matchCase = true;
    else
    matchCase = false;
    if (matchWholeWord.getState() == true)
    matchWord = true;
    else
    matchWord = false;
    // A button has been pressed - determine which
    if (e.target instanceof Button)
    if (e.target == search)
    // Search button pressed - read in
    // search text entered
    text = inputArea.getText();
    // Make sure ther's somthing to search for
    if (text.length() == 0)
    return (false);
    // New search so clear the GUI out
    if (resultsArea.countItems() > 0)
    resultsArea.clear();
    disableButtons ();
    abort.enable();
    statusArea.setText("");
    // Clear out previous search data
    pageNames.removeAllElements();
    pageMatch.removeAllElements();
    // We're off - start the search thread
    cp = new SearchPages (this, hostName, text, maxSearch);
    cp.start();
    else if (e.target == abort)
    // Abort button pressed - stop the thread
    if (cp != null)
    cp.stop();
    cp = null;
    // Enable buttons for another search
    enableButtons();
    abort.disable();
    else
    // Clear button pressed - clear all the fields
    // and return
    inputArea.setText("");
    statusArea.setText("");
    // Clear radio buttons
    caseSensitive.setState(false);
    caseInsensitive.setState(true);
    matchWholeWord.setState(false);
    // Clear option menu
    numPagesChoice.select (0);
    try
    maxSearch = Integer.parseInt(numPagesChoice.getSelectedItem(), 10);
    catch (NumberFormatException ex)
    maxSearch = MAX_NUMBER_PAGES;
    if (debugMode)
    System.out.println ("maxSearch is now " + maxSearch);
    if (resultsArea.countItems() > 0)
    resultsArea.clear();
    cp = null;
    // Selection made from the list of matches
    if (e.target instanceof List)
    List list = (List) e.target;
    int index = list.getSelectedIndex();
    // Extract the page name from the list
    if (index < pageMatch.size())
    String URLSelected = (String)pageMatch.elementAt(index);
    try
    // If URL stored then use it
    if (URLSelected.startsWith ("http:") ||
    URLSelected.startsWith ("file:"))
    newURL = new URL(URLSelected);
    else if (server == null)
    newURL = new URL("http://www." + hostName + ".demon.co.uk/" + URLSelected);
    else
    newURL = new URL (server + URLSelected);
    catch(MalformedURLException excep)
    System.out.println("action(): Bad URL: " + newURL);
    if (debugMode)
    System.out.println (" Jumping to ... " + newURL.toString());
    // Display the document
    getAppletContext().showDocument(newURL,"_self");
    return true; // We're done
    // Purpose - checks to see if a page has already been
    // visited by the search thread
    boolean checkAlreadyFound (String page)
    if (pageNames.size() == 0)
    return (false);
    // Check this is a new one
    for (int i=1; i < pageNames.size() ;i++)
    String pageName = (String) pageNames.elementAt(i);
    if (pageName.equalsIgnoreCase (page))

  • Help, experiencing minor bugs in program

    this is supposed to use rectangles and you should be able to load and save and they have colors and do a few more things with them, the loading is where it doesn't work.
    *-------------------------------------------------------------- 80 columns ---|
    * This is the main class for the application. It is built along the same
    * lines as the Editor class of project 1. It has a constructor, two instance
    * methods, and a static main()  that kicks the whole thing off.
    * The two instance methods are a menu creation method, and a menuItems
    * initialisation method.  The constructor instantiates the window
    * and sets up its internals by creating and installing the drawing canvas,
    * toolbar, and menus. All of the code works correctly as is and should
    * require no changes.
    * @version      1.1 15/04/01
    * @author       Julie Zelenski
    * @author       Restructured by Ian A. Mason
    * @see       javax.swing.JFrame
    * @see       javax.swing.JMenuBar
    * @see       javax.swing.JMenuItem
    * @see       javax.swing.JMenu
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class JavaDraw extends JFrame {
        final Toolbar toolbar = new Toolbar();
        final DrawingCanvas canvas = new DrawingCanvas(toolbar, 350, 350);
        final int menuMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
        final JMenuBar mb = new JMenuBar();
        final String[]
             fileMenuItems = {"Clear all", "Load file", "Save to file", "Quit"};
        final int[] fileKeyCodes = {KeyEvent.VK_N, KeyEvent.VK_O, KeyEvent.VK_S, KeyEvent.VK_Q};
        final ActionListener[] fileActionListeners = {
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.clearAll();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.loadFile();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.saveToFile();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  System.exit(0);}}
        final String[] editMenuItems = {"Cut", "Copy", "Paste", "Delete"};
        final int[] editKeyCodes = {KeyEvent.VK_X, KeyEvent.VK_C, KeyEvent.VK_V, KeyEvent.VK_BACK_SPACE};
        final int[] editMenuMasks = {menuMask, menuMask, menuMask, 0};
        final ActionListener[] editActionListeners = {
         new ActionListener() {
              public void actionPerformed(ActionEvent e) { canvas.cut();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) { canvas.copy();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) { canvas.paste();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) { canvas.delete();}}
        final String[] layeringMenuItems = {"Bring to front", "Send to back"};
        final int[]    layeringKeyCodes = {KeyEvent.VK_F, KeyEvent.VK_B};
        final ActionListener[] layeringActionListeners = {
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.bringToFront();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.sendToBack();}}
        private JavaDraw(){
         super("JavaDraw!");
         toolbar.setCanvas(canvas);
         getContentPane().add(toolbar, BorderLayout.SOUTH);
         getContentPane().add(canvas, BorderLayout.CENTER);
         createMenus();
         setJMenuBar(mb);
         setLocation(100, 20);
         pack();
         setVisible(true);
        static public void main(String[] args){
         JavaDraw javaDraw = new JavaDraw();
        private void initMenus(JMenu m,
                      String  miLabel,
                      int keyCode,
                      int menuMask,
                      ActionListener al){
         JMenuItem mi = new JMenuItem(miLabel);
         m.add(mi);
         mi.addActionListener(al);
         mi.setAccelerator(KeyStroke.getKeyStroke(keyCode, menuMask));
        private void createMenus(){
         JMenu m;
         m = new JMenu("File");
         for(int i = 0; i < fileMenuItems.length; i++)
             initMenus(m,
                    fileMenuItems,
              fileKeyCodes[i],
              menuMask,
              fileActionListeners[i]);
         mb.add(m);
         m = new JMenu("Edit");
         for(int i = 0; i < editMenuItems.length; i++)
         initMenus(m,
              editMenuItems[i],
              editKeyCodes[i],
              editMenuMasks[i],
              editActionListeners[i]);
         mb.add(m);
         m = new JMenu("Layering");
         for(int i = 0; i < layeringMenuItems.length; i++)
         initMenus(m,
              layeringMenuItems[i],
              layeringKeyCodes[i],
              menuMask,
              layeringActionListeners[i]);
         mb.add(m);
    *-------------------------------------------------------------- 80 columns ---|
    * The DrawingCanvas class a small extension of JComponent
    * @version 1.1 15/04/01
    * @author Julie Zelenski
    * @author (touched up by Ian A. Mason)
    * @see javax.swing.JComponent
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    public class DrawingCanvas extends JComponent{
    static final int DRAG_NONE = 0;
    static final int DRAG_CREATE = 1;
    static final int DRAG_RESIZE = 2;
    static final int DRAG_MOVE = 3;
    // list of all shapes on canvas
    protected Vector allShapes;          
    // currently selected shape (can be null at times)
    protected Rect selectedShape;
    // reference to toolbar to message for tool&color settings
    protected Toolbar toolbar;
    protected Rect clipboard=null;          
    /* These are the unimplemented menu commands. The menus are already
    * set up to send the correct messages to the canvas, but the
    * method bodies themselves are currently completely empty. It will
    * be your job to fill them in!
    public void cut() {
         copy();
         delete();
    public void copy() {
         int x=(int)selectedShape.getBounds().getX();
         int y=(int)selectedShape.getBounds().getY();
         Point p=new Point(x,y);
         clipboard=new Rect(p,this);
         clipboard.setBounds(selectedShape.getBounds());
    public void paste() {
         if(clipboard==null)
              return;
         allShapes.add(clipboard);
         setSelectedShape(clipboard);
         copy();
         this.repaint();
    public void delete() {
         if(selectedShape==null)
              return;
         else{
         int num=allShapes.indexOf(selectedShape);
         allShapes.remove(num);
         selectedShape=null;
         this.repaint();
    public void clearAll() {
         allShapes.removeAllElements();
         this.repaint();
    public void loadFile() {
         Load load=new Load(this);
         load.setSize(250,200);
         load.validate();
         load.setVisible(true);
    public void done(Vector vect){
         allShapes.removeAllElements();
         for(int i=0;i<vect.size();i++){
              allShapes.add(vect.elementAt(i));
         this.repaint();
    public void saveToFile() {
         Save save=new Save(allShapes);
         save.setSize(250,200);
         save.validate();
         save.setVisible(true);
    public void bringToFront() {
         if(selectedShape==null)
              return;
         int size=allShapes.size();
         int index=allShapes.indexOf(selectedShape);
         for(int i=index+1;i<=size-1;i++){
              allShapes.set(i-1,allShapes.elementAt(i));
         allShapes.set(size-1,selectedShape);
         this.repaint();
    public void sendToBack() {
         if(selectedShape==null)
              return;
         int index=allShapes.indexOf(selectedShape);
         for(int i=index-1;i>=0;i--){
              allShapes.remove(allShapes.elementAt(i+1));
              allShapes.add(i+1,allShapes.elementAt(i));
         allShapes.remove(allShapes.elementAt(0));
         allShapes.add(0,selectedShape);
         this.repaint();
    * Constructor for creating a new empty DrawingCanvas. We set up
    * our size and background colors, instantiate an empty vector of shapes,
    * and install a listener for mouse events using our inner class
    * CanvasMouseHandler
    public DrawingCanvas(Toolbar tb, int width, int height){
         setPreferredSize(new Dimension(width, height));
         setBackground(Color.white);
         toolbar = tb;
         allShapes = new Vector();
         selectedShape = null;
         CanvasMouseHandler handler = new CanvasMouseHandler();
         addMouseListener(handler);
         addMouseMotionListener(handler);
    * All components are responsible for drawing themselves in
    * response to repaint() requests. The standard method a component
    * overrides is paint(Graphics g), but for Swing components, the default
    * paint() handler calls paintBorder(), paintComponent() and paintChildren()
    * For a Swing component, you override paintComponent and do your
    * drawing in that method. For the drawing canvas, we want to
    * clear the background, then iterate through our shapes asking each
    * to draw. The Graphics object is clipped to the region to update
    * and we use to that avoid needlessly redrawing shapes outside the
    * update region.
    public void paintComponent(Graphics g){
         Rectangle regionToRedraw = g.getClipBounds();
         g.setColor(getBackground());
         g.fillRect(regionToRedraw.x, regionToRedraw.y,
              regionToRedraw.width, regionToRedraw.height);
         Iterator iter = allShapes.iterator();
         while (iter.hasNext())
         ((Rect)iter.next()).draw(g, regionToRedraw);
    * Changes the currently selected shape. There is at most
    * one shape selected at a time on the canvas. It is possible
    * for the selected shape to be null. Messages the shape to
    * change its selected state which will in turn refresh the
    * shape with the knobs active.
    protected void setSelectedShape(Rect shapeToSelect) {
         // if change in selection
         if (selectedShape != shapeToSelect) {
         // deselect previous selection
         if (selectedShape != null)
              selectedShape.setSelected(false);
         // set selection to new shape
         selectedShape = shapeToSelect;
         if (selectedShape != null) {
              shapeToSelect.setSelected(true);
    * A hit-test routine which finds the topmost shape underneath a
    * given point.We search Vector of shapes in back-to-front order
    * since shapes created later are added to end and drawn last, thus
    * appearing to be "on top" of the earlier ones. When a click comes
    * in, we want to select the top-most shape.
    protected Rect shapeContainingPoint(Point pt){
         for (int i = allShapes.size()-1; i >= 0; i--) {
         Rect r = (Rect)allShapes.elementAt(i);
         if (r.inside(pt)) return r;
         return null;
    * The inner class CanvasMouseHandler is the object that handles the
    * mouse actions (press, drag, release) over the canvas. Since there is
    * a bit of state to drag during the various operations (which shape,
    * where we started from, etc.) it is convenient to encapsulate all that
    * state with this little convenience object and register it as the
    * handler for mouse events on the canvas.
    protected class CanvasMouseHandler
         extends MouseAdapter implements MouseMotionListener {
         Point dragAnchor;          
         // variables using to track state during drag operations
         int dragStatus;
         /** When the mouse is pressed we need to figure out what
         * action to take. If the tool mode is arrow, the click might
         * be a select, move or reisze. If the tool mode is one of the
         * shapes, the click initiates creation of a new shape.
         public void mousePressed(MouseEvent event){
         Rect clicked = null;
         Point curPt = event.getPoint();
         // first, determine if click was on resize knob of selected shape
         if (toolbar.getCurrentTool() == Toolbar.SELECT) {
              if (selectedShape != null &&
              (dragAnchor = selectedShape.getAnchorForResize(curPt))
              != null) {
              // drag will resize this shape
              dragStatus = DRAG_RESIZE;     
              } else if ((clicked = shapeContainingPoint(curPt)) != null) {
              // if not, check if any shape was clicked
              setSelectedShape(clicked);
              // drag will move this shape      
              dragStatus = DRAG_MOVE;
              dragAnchor = curPt;
              } else {     
              // else this was a click in empty area,
              // deselect selected shape,
              setSelectedShape(null);
              // drag does nothing in this case
              dragStatus = DRAG_NONE;
         } else {
              Rect newShape = new Rect(curPt, DrawingCanvas.this);
              // create rect here
              allShapes.add(newShape);
              setSelectedShape(newShape);
              dragStatus = DRAG_CREATE;          
              // drag will create (resize) this shape
              dragAnchor = curPt;
         /** As the mouse is dragged, our listener will receive periodic
         * updates as mouseDragged events. When we get an update position,
         * we update the move/resize event that is in progress.
         public void mouseDragged(MouseEvent event){
         Point curPt = event.getPoint();
         switch (dragStatus) {
         case DRAG_MOVE:
              selectedShape.translate(curPt.x - dragAnchor.x,
                             curPt.y - dragAnchor.y);
              // update for next dragged event
              dragAnchor = curPt;
              break;
         case DRAG_CREATE: case DRAG_RESIZE:
              selectedShape.resize(dragAnchor, curPt);
              break;
         public void mouseMoved(MouseEvent e) {}
    /** A little helper routine that will be useful for the load & save
    * operations. It brings up the standard JFileChooser dialog and
    * allows the user to specify a file to open or save. The return
    * value is the full path to the chosen file or null if no file was
    * selected.
    protected String filenameChosenByUser(boolean forOpen){
         JFileChooser fc = new JFileChooser(System.getProperty("user.dir") +
                             java.io.File.separator + "Documents");
         int result = (forOpen? (fc.showOpenDialog(this)) :
              fc.showSaveDialog(this));
         java.io.File chosenFile = fc.getSelectedFile();
         if (result == JFileChooser.APPROVE_OPTION && chosenFile != null)
         return chosenFile.getPath();
         return null;
         // return null if no file chosen or dialog cancelled
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import java.io.*;
    class Load extends JFrame implements ActionListener, Serializable{
         Container contentPane;
         JTextField jtf;
         JButton jb;
         Object obj=null;
         Load load;
         Thread thread;
         DrawingCanvas draw;
         public Load(DrawingCanvas dc){
              draw=dc;
              contentPane=getContentPane();
              contentPane.setLayout(new FlowLayout());
              jtf=new JTextField(20);
              jb=new JButton("Load");
              jb.addActionListener(this);
              contentPane.add(jtf);
              contentPane.add(jb);
         public void actionPerformed(ActionEvent e){
              String text=jtf.getText();
              SimpleObjectReader reader=SimpleObjectReader.openFileForReading(text+".shp");
              if(reader==null){
                   System.out.println("Couldn't open file!");
                   return;
              obj=reader.readObject();
              reader.close();
              draw.done((Vector)obj);
              this.setVisible(false);
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.Vector;
    import java.io.*;
    class Save extends JFrame implements ActionListener, Serializable{
         Container contentPane;
         JTextField jtf;
         Vector shapes;
         JButton jb;
         public Save(Vector shapeVector){
              shapes=shapeVector;
              contentPane=getContentPane();
              contentPane.setLayout(new FlowLayout());
              jtf=new JTextField(20);
              jb=new JButton("Save");
              jb.addActionListener(this);
              contentPane.add(jtf);
              contentPane.add(jb);
         public void actionPerformed(ActionEvent e){
              String text=jtf.getText();
              SimpleObjectWriter writer=SimpleObjectWriter.openFileForWriting(text+".shp");
              if(writer==null){
                   System.out.println("Couldn't open file!");
                   return;
              writer.writeObject(shapes);
              writer.close();
              this.setVisible(false);
    *-------------------------------------------------------------- 80 columns ---|
    * The RectShape class defines a simple rectangular shape object.
    * It tracks its bounding box, selected state, and the canvas it is being
    * drawn in. It has some basic methods to select, move, and resize the
    * rectangle. It has methods that draw the shape in the selected or unselected
    * states and updates the canvas whenever the state or bounds of the rectangle
    * change. The code that is there works properly, but you will need to extend
    * and change the code to support additional features.
    * @version 1.1 15/04/01
    * @author Julie Zelenski
    * @author (touched up by Ian A. Mason)
    import java.awt.*;
    import java.io.*;
    public class Rect implements Serializable{     
    protected Rectangle bounds;
    protected boolean isSelected;
    public Color color;
    public DrawingCanvas canvas;
    protected static final int KNOB_SIZE = 6;
    protected static final int NONE = -1;
    protected static final int NW = 0;
    protected static final int SW = 1;
    protected static final int SE = 2;
    protected static final int NE = 3;
    /** The constructor that creates a new zero width and height rectangle
    * at the given position in the canvas.
    public Rect(Point start, DrawingCanvas dcanvas){
         canvas = dcanvas;
         bounds = new Rectangle(start);
         color=canvas.toolbar.getCurrentColor();
    /** The "primitive" for all resizing/moving/creating operations that
    * affect the rect bounding box. The current implementation just resets
    * the bounds variable and triggers a re-draw of the union of the old &
    * new rectangles. This will redraw the shape in new size and place and
    * also "erase" if bounds are now smaller than before. It is a good
    * design to have all changes to a critical variable bottleneck through
    * one method so that you can be sure that all the updating that goes
    * with it only needs to be implemented in this one place. If any of your
    * subclasses have additional work to do when the bounds change, this is
    * the method to override. Make sure that any methods that change the
    * bounds call this method instead of directly manipulating the variable.
    protected void setBounds(Rectangle newBounds){
         Rectangle oldBounds = bounds;
         bounds = newBounds;
         updateCanvas(oldBounds.union(bounds));
    /** The resize operation is called when first creating a rect, as well as
    * when later resizing by dragging one of its knobs. The two parameters
    * are the points that define the new bounding box. The anchor point
    * is the location of the mouse-down event during a creation operation
    * or the opposite corner of the knob being dragged during a resize
    * operation. The end is the current location of the mouse. If you
    * create the smallest rectangle which encloses these two points, you
    * will have the new bounding box. Use the setBounds() primitive which
    * is the bottleneck we are using for all geometry changes, it handles
    * updating and redrawing.
    public void resize(Point anchor, Point end){
         Rectangle newRect = new Rectangle(anchor);
         // creates smallest rectange which
         // includes both anchor & end
         newRect.add(end);
         // reset bounds & redraw affected areas
         setBounds(newRect);      
    public Rectangle getBounds(){
         return bounds;
    /** The translate operation is called when moving a shape by dragging in
    * the canvas. The two parameters are the delta-x and delta-y to move
    * by. Note that either or both can be negative. Create a new rectangle
    * from our bounds and translate and then go through the setBounds()
    * primitive to change it.
    public void translate(int dx, int dy){
         Rectangle newRect = new Rectangle(bounds);
         newRect.translate(dx, dy);
         setBounds(newRect);
    /** Used to change the selected state of the shape which will require
    * updating the affected area of the canvas to add/remove knobs.
    public void setSelected(boolean newState){
         isSelected = newState;
         // need to erase/add knobs
         // including extent of extended bounds
         updateCanvas(bounds, true);
    /** The updateCanvas() methods are used when the state has changed
    * in such a way that it needs to be refreshed in the canvas to properly
    * reflect the new settings. The shape should take responsibility for
    * messaging the canvas to properly update itself. The appropriate AWT/JFC
    * way to re-draw a component is to send it the repaint() method with the
    * rectangle that needs refreshing. This will cause an update() event to
    * be sent to the component which in turn will call paint(), where the
    * real drawing implementation goes. See the paint() method in
    * DrawingCanvas to see how it is implemented.
    protected void updateCanvas(Rectangle areaOfChange, boolean enlargeForKnobs){
         Rectangle toRedraw = new Rectangle(areaOfChange);
         if (enlargeForKnobs)
         toRedraw.grow(KNOB_SIZE/2, KNOB_SIZE/2);
         canvas.repaint(toRedraw);
    protected void updateCanvas(Rectangle areaOfChange){
         updateCanvas(areaOfChange, isSelected);
    /** When the DrawingCanvas needs a shape to draw itself, it sends a draw
    * message, passing the graphics context and the current region being
    * redrawn. If the shape intersects with that region, it must draw itself
    * doing whatever it takes to properly represent itself in the canvas
    * (colors, location, size, knobs, etc.) by messaging the Graphics object.
    public void draw(Graphics g, Rectangle regionToDraw){
         if (!bounds.intersects(regionToDraw))
         return;
         g.setColor(color);
         g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
         if (isSelected) { // if selected, draw the resizing knobs
         // along the 4 corners
         Rectangle[] knobs = getKnobRects();
         for (int i = 0; i < knobs.length; i++)
              g.fillRect(knobs[i].x, knobs[i].y,
                   knobs[i].width, knobs[i].height);
    /** When the DrawingCanvas needs to determine which shape is under
    * the mouse, it asks the shape to determine if a point is "inside".
    * This method should returns true if the given point is inside the
    * region for this shape. For a rectangle, any point within the
    * bounding box is inside the shape.
    public boolean inside(Point pt){
         return bounds.contains(pt);
    /** When needed, we create the array of knob rectangles on demand. This
    * does mean we create and discard the array and rectangles repeatedly.
    * These are small objects, so perhaps it is not a big deal, but
    * a valid alternative would be to store the array of knobs as an
    * instance variable of the Shape and and update the knobs as the bounds
    * change. This means a little more memory overhead for each Shape
    * (since it is always storing the knobs, even when not being used) and
    * having that redundant data opens up the possibility of bugs from
    * getting out of synch (bounds move but knobs didn't, etc.) but you may
    * find that a more appealing way to go. Either way is fine with us.
    * Note this method provides a nice unified place for one override from
    * a shape subclass to substitute fewer or different knobs.
    protected Rectangle[] getKnobRects(){
         Rectangle[] knobs = new Rectangle[4];
         knobs[NW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                        bounds.y - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         knobs[SW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                        bounds.y + bounds.height - KNOB_SIZE/2,
                        KNOB_SIZE, KNOB_SIZE);
         knobs[SE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                        bounds.y + bounds.height - KNOB_SIZE/2,
                        KNOB_SIZE, KNOB_SIZE);
         knobs[NE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                        bounds.y - KNOB_SIZE/2,
                        KNOB_SIZE, KNOB_SIZE);
         return knobs;
    /** Helper method to determine if a point is within one of the resize
    * corner knobs. If not selected, we have no resize knobs, so it can't
    * have been a click on one. Otherwise, we calculate the knob rects and
    * then check whether the point falls in one of them. The return value
    * is one of NW, NE, SW, SE constants depending on which knob is found,
    * or NONE if the click doesn't fall within any knob.
    protected int getKnobContainingPoint(Point pt){
         // if we aren't selected, the knobs
         // aren't showing and thus there are no knobs to check
         if (!isSelected) return NONE;
         Rectangle[] knobs = getKnobRects();
         for (int i = 0; i < knobs.length; i++)
         if (knobs[i].contains(pt))
              return i;
         return NONE;
    /** Method used by DrawingCanvas to determine if a mouse click is starting
    * a resize event. In order for it to be a resize, the click must have
    * been within one of the knob rects (checked by the helper method
    * getKnobContainingPoint) and if so, we return the "anchor" ie the knob
    * opposite this corner that will remain fixed as the user drags the
    * resizing knob of the other corner around. During the drag actions of a
    * resize, that fixed anchor point and the current mouse point will be
    * passed to the resize method, which will reset the bounds in response
    * to the movement. If the mouseLocation wasn't a click in a knob and
    * thus not the beginning of a resize event, null is returned.
    public Point getAnchorForResize(Point mouseLocation){
         int whichKnob = getKnobContainingPoint(mouseLocation);
         // no resize knob is at this location
         if (whichKnob == NONE)
         return null;
         switch (whichKnob) {
         case NW: return new Point(bounds.x + bounds.width,
                        bounds.y + bounds.height);
         case NE: return new Point(bounds.x, bounds.y + bounds.height);
         case SW: return new Point(bounds.x + bounds.width, bounds.y);
         case SE: return new Point(bounds.x, bounds.y);
         return null;
    import java.io.*;
    * SimpleObjectReader is a small class to wrap around the usual ObjectStream
    * to shield you from the exception handling which we haven't yet gotten
    * to in class.
    * <P>It has just three methods of note: one to open a new file for reading,
    * one to read an object from an open file, and one to close the file when done.
    * <P>Any object that you attempt to read must properly implement the Serializable
    * interface. Here is a simple example that shows using the SimpleFileReader to
    * to rehydrate objects from a file and print them:
    * <PRE>
    * SimpleObjectReader reader = SimpleObjectReader.openFileForReading("shapes");
    * if (reader == null) {
    * System.out.println("Couldn't open file!");
    * return;
    * Object obj;
    * while ((obj = reader.readObject()) != null)
    * System.out.println(obj);
    * reader.close();
    * </PRE>
    * <P>You are free to edit or extend this class, but we don't expect that
    * you should need to make any changes.
    * @version 1.1 15/04/01
    * @author Julie Zelenski
    * @author (touched up by Ian A. Mason)
    public class SimpleObjectReader {
    private ObjectInputStream ois;
    * Opens a new file for reading. The filename can either be a relative
    * path, which will be relative to the working directory of the program
    * when started, or an absolute path. If the file exists and can be
    * opened, a new SimpleObjectReader is returned. If the file cannot be
    * opened (for any reason: wrong name, wrong path, lack of permissions, etc.)
    * null is returned.
    public static SimpleObjectReader openFileForReading(String filename){
         try {
         return new SimpleObjectReader(new ObjectInputStream(new FileInputStream(filename)));
         } catch(IOException e) {     
         return null;
    * Reads a single object from the file and returns it. If there are
    * no more objects in the file (i.e, we have reached the end of file),
    * null is returned null is returned. null is also
    * returned on any I/O error.
    public Object readObject (){
         try {
         return ois.readObject();
         } catch (IOException e) {
         e.printStackTrace();
         return null;
         } catch (ClassNotFoundException e) {
         e.printStackTrace();
         return null;
    * Closes the file when done reading. You should close a reader when
    * you are finished to release the OS resources for use by others.
    public void close (){
         try {
         ois.close();
         catch (IOException e) {}
    * Constructor is private so that only means to create a new reader
    * is through the static method which does error checking.
    private SimpleObjectReader(ObjectInputStream ois){
         this.ois = ois;
    import java.io.*;
    * SimpleObjectWriter is a small class to wrap around the usual
    * ObjectOutputStream to shield you from the exception handling
    * which we haven't yet gotten to in class.
    * <P>It has just three methods of note: one to open a new file for writing,
    * one to write an object to the file, and one to close the
    * the file when done.
    * <P>Here is a simple example that shows using the SimpleObjectWriter
    * to create a new file and write some objects into it:
    * <PRE>
    * SimpleObjectWriter writer =
    * SimpleObjectWriter.openFileForWriting("objects");
    * if (writer == null) {
    * System.out.println("Couldn't open file!");
    * return;
    * writer.writeObject("Here is a string");
    * writer.writeObject("And another one.");
    * writer.writeObject(new Date());
    * writer.close();
    * </PRE>
    * <P>You are free to edit or extend this class, but we don't expect that
    * you should need to make any changes.
    * @version 1.1 15/04/01
    * @author Julie Zelenski
    * @author (touched up by Ian A. Mason)
    public class SimpleObjectWriter {
    private ObjectOutputStream oos;
    * Opens a new file for writing. The filename can either be a relative
    * path, which will be relative to the working directory of the program
    * when started, or an absolute path. If the file can be created, a
    * new SimpleObjectWriter is returned. If the file already exists, this
    * will overwrite its content

    I'm not reading that either, but to help you for next time:
    - use more than 1 sentence to describe your problem
    - only post the RELEVANT code, or a small test program with the same problem if possible.
    At least you formatted it, I'll give you that.
    Cheers,
    Radish21
    PS. I think in this case, posting another (better worded) thread might be a good idea, because no one is going to read this one. In general though, don't :)

  • How to change color of selected label from list of labels?

    My Problem is that I have a list of labels. RowHeaderRenderer is a row header renderer for Jtable which is rendering list items and (labels).getListTableHeader() is a method to get the list. When we click on the label this code is executed:
    getListTableHeader().addMouseListener(new MouseAdapter()
    public void mouseReleased(MouseEvent e)
    if (e.getClickCount() >= 1)
    int index = getListTableHeader().locationToIndex(e.getPoint());
    try
    if (((ae_AlertEventInfo)theAlerts.values().toArray()[index]).ackRequiredFlag)
    AcknowledgeEvent ackEvent = new AcknowledgeEvent(
    this, (ae_AlertEventInfo)theAlerts.values().toArray()[index]);
    fireAcknowledgeEvent(ackEvent);
    ((HeaderListModel)listModel).setElementAt(ACK, index);
    catch(Exception ex) {;}
    Upon mouse click color of the label should be changed. For some period of time ie. Upto completion of fireAcknowledgeEvent(ackEvent);
    This statement is calling this method:
    public void handleAcknowledgeEvent(final AcknowledgeEvent event)
    boolean ackOk = false;
    int seqId = ((ae_AlertEventInfo)event.getAlertInfo()).sequenceId;
    if (((ae_AlertEventInfo)event.getAlertInfo()).ackRequiredFlag)
    try
    // perform call to inform server about acknowledgement.
    ackOk = serviceAdapter.acknowledge(seqId,
    theLogicalPosition, theUserName);
    catch(AdapterException aex)
    Log.error(getClass(), "handleAcknowledgeEvent()",
    "Error while calling serviceAdapter.acknowledge()", aex);
    ExceptionHandler.handleException(aex);
    else
    // Acknowledge not required...
    ackOk = true;
    //theQueue.buttonAcknowledge.setEnabled(false);
    final AlertEventQueue myQueue = theQueue;
    if (ackOk)
    Object popupObj = null;
    synchronized (mutex)
    if( hasBeenDismissed ) { return; }
    // mark alert event as acknowledged (simply reset ack req flag)
    ae_AlertEventInfo info;
    Iterator i = theAlerts.values().iterator();
    while (i.hasNext())
    info = (ae_AlertEventInfo) i.next();
    if (info.sequenceId == seqId)
    // even if ack wasn't required, doesn't hurt to set it
    // to false again. But it is important to prevent the
    // audible from playing again.
    info.ackRequiredFlag = false;
    info.alreadyPlayed = true;
    // internally uses the vector index so
    // process the queue acknowledge update within
    // the synchronize block.
    final ae_AlertEventInfo myAlertEventInfo = event.getAlertInfo();
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    myQueue.acknowledge(myAlertEventInfo);
    myQueue.updateAcknowledgeButtonState();
    // here we should stop playing sound
    // if it is playing for this alert.
    int seqId1;
    if (theTonePlayer != null)
    seqId1 = theTonePlayer.getSequenceId();
    if (seqId1 == seqId)
    if (! theTonePlayer.isStopped())
    theTonePlayer.stopPlaying();
    theTonePlayer = null;
    // get reference to popup to be dismissed...
    // The dismiss must take place outside of
    // the mutex... otherwise threads potentially
    // hang (user hits "ok" and is waiting for the
    // mutex which is currently held by processing
    // for a "move to summary" transition message.
    // if the "dismiss" call in the transition
    // message were done within the mutex, it might
    // hang on the dispose method because the popup
    // is waiting for the mutex...
    // So call popup.dismiss() outside the mutex
    // in all cases.
    if(event.getSource() instanceof AlertEventPopup)
    popupObj = (AlertEventPopup)event.getSource();
    else
    popupObj = thePopups.get(event.getAlertInfo());
    thePopups.remove(event.getAlertInfo());
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    // search vector elements to determine icon color in main frame
    String color = getColor();
    fireUpdateEvent(new UpdateEvent(this, blinking, color));
    // Call dismiss outside of the mutex.
    if (popupObj !=null)
    if(popupObj instanceof AlertEventPopup)
    ((AlertEventPopup)popupObj).setModal(false);
    ((AlertEventPopup)popupObj).setVisible(false); // xyzzy
    ((AlertEventPopup)popupObj).dismiss();
    else
    // update feedback... ack failed
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    myQueue.setInformationMessage("Acknowledge failed to reach server... try again");
    return;
    Code for RowHeaderRenderer is:
    class RowHeaderRenderer extends JLabel implements ListCellRenderer
    JTable theTable = null;
    ImageIcon image = null;
    RowHeaderRenderer(JTable table)
    image = new ImageIcon(AlertEventQueue.class.getResource("images" + "/" + "alert.gif"));
    theTable = table;
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setHorizontalAlignment(LEFT);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    public Component getListCellRendererComponent( JList list, Object value,
    int index, boolean isSelected, boolean cellHasFocus)
    int level = 0;
    try
    level = Integer.parseInt(value.toString());
    catch(Exception e)
    level = 0;
    if (((ae_AlertEventInfo)theAlerts.values().toArray()[index]).ackRequiredFlag)
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    this.setHorizontalAlignment(JLabel.CENTER);
    this.setVerticalAlignment(JLabel.CENTER);
    setIcon(image);
    else
    setBorder(BorderFactory.createLineBorder(Color.gray));
    setText("");
    setIcon(null);
    return this;
    I tried but when i am clicking a particular label, the color of all labels in the List is being changed. So can you please assist me in changing color of only the label that is selected and the color must disappear after completion of Upto completion of fireAcknowledgeEvent(ackEvent);

    im a bit confused with the post so hopefully this will help you, if not then let me know.
    I think the problem is that in your renderer your saying
    setBackground(header.getBackground());which is setting the backgound of the renderer rather than the selected item, please see an example below, I created a very simple program where it adds JLabels to a list and the renderer changes the colour of the selected item, please note the isSelected boolean.
    Object "value" is the currentObject its rendering, obviously you may need to test if its a JLabel before casting it but for this example I kept it simple.
    populating the list
    public void populateList(){
            DefaultListModel model = new DefaultListModel();
            for (int i=0;i<10;i++){
                JLabel newLabel = new JLabel(String.valueOf(i));
                newLabel.setOpaque(true);
                model.addElement(newLabel);           
            this.jListExample.setModel(model);
            this.jListExample.setCellRenderer(new RowHeaderRenderer());
        }the renderer
    class RowHeaderRenderer extends JLabel implements ListCellRenderer
        JTable theTable = null;
        public Component getListCellRendererComponent(JList list, Object value,
                                                      int index, boolean isSelected, boolean cellHasFocus){
            JLabel aLabel = (JLabel)value;
            if (isSelected){
                aLabel.setBackground(Color.RED);
            }else{
                aLabel.setBackground(Color.GRAY);
            return aLabel;       
    }

  • FAQ: What's new in the Photoshop CS6 beta?

    We are excited to enable all of our customers to explore the application and see some of the new features we have been working on. The application is not yet complete, but some of the features you may want to check out in the beta include: significant performance improvements in key editing tools; new interface color preferences; preset migration and sharing; Background Save and Auto-recovery; an all-new Crop tool; new Content-Aware tools; type styles; layer search; vector strokes; dashed line creation; skin tone-aware selections and masking; improved lens adjustments; new blur tools; new video tools; completely new 3D** workflows; and much more. The Photoshop CS6 beta also includes a pre-release version of Adobe Bridge software.
    **3D features and some GPU-enabled features are not supported on Windows XP.
    Additional Information:
    Photoshop CS6 beta training/learning resources (videos, articles, & tutorials)

    Bug fixes.
    Type "ios 6.0.2" into the search bar at the top of this page by Support and read for yourself.

  • Method invokeMethod(java.lang.String, org.w3c.dom.Element) not found

    I am calling a Web Service that returns an XML-file. The XML-file should be passed to a method that puts the xml into a table in my database.
    I will upload the 3 files that are being used for this.
    When I rebuild my files I get the following error in CustomerCO.java:
    Error(78,38): method invokeMethod(java.lang.String, org.w3c.dom.Element) not found in interface oracle.apps.fnd.framework.OAApplicationModule
    Line 78 reads as follows:
    String Status = (String)am.invokeMethod("initSaveXml", wsXml);
    Any suggestions?
    PS: I am a newbie to java and framework :-(
    Here are my files:
    CustomerCO.java:
    /*===========================================================================+
    | Copyright (c) 2001, 2005 Oracle Corporation, Redwood Shores, CA, USA |
    | All rights reserved. |
    +===========================================================================+
    | HISTORY |
    +===========================================================================*/
    package xxcu.oracle.apps.ar.customer.server.webui;
    import java.io.Serializable;
    import java.lang.Exception;
    import oracle.apps.fnd.common.VersionInfo;
    import oracle.apps.fnd.framework.OAApplicationModule;
    import oracle.apps.fnd.framework.webui.OAControllerImpl;
    import oracle.apps.fnd.framework.webui.OAPageContext;
    import oracle.apps.fnd.framework.webui.beans.OAWebBean;
    import org.w3c.dom.Element;
    import xxcu.oracle.apps.ar.customer.ws.LindorffWS;
    * Controller for ...
    public class CustomerCO extends OAControllerImpl implements Serializable
    public static final String RCS_ID="$Header$";
    public static final boolean RCS_ID_RECORDED =
    VersionInfo.recordClassVersion(RCS_ID, "%packagename%");
    * Layout and page setup logic for a region.
    * @param pageContext the current OA page context
    * @param webBean the web bean corresponding to the region
    public void processRequest(OAPageContext pageContext, OAWebBean webBean)
    super.processRequest(pageContext, webBean);
    * Procedure to handle form submissions for form elements in
    * a region.
    * @param pageContext the current OA page context
    * @param webBean the web bean corresponding to the region
    public void processFormRequest(OAPageContext pageContext, OAWebBean webBean)
    super.processFormRequest(pageContext, webBean);
    * 2009.07.09, Roy Feirud, lagt til for å utføre spørring
    if (pageContext.getParameter("Search") != null)
    OAApplicationModule am = pageContext.getApplicationModule(webBean);
    //Setter søkekriteriene til LindorffWS
    String Name = pageContext.getParameter("SearchName");
    String Address = pageContext.getParameter("SearchAddress");
    String Zip = pageContext.getParameter("SearchZipCode");
    String City = pageContext.getParameter("SearchCity");
    String Born = pageContext.getParameter("SearchBorn");
    String Phone = pageContext.getParameter("SearchPhoneNo");
    Serializable[] param = { Name, Address, Zip, City, Born, Phone };
    //Bygger søkestrengen
    String SearchString = (String)am.invokeMethod("initBuildString", param );
    //Initialiserer LindorffWS
    LindorffWS WsConnection = new LindorffWS();
    try
    //Kaller Web Sevice fra Lindorff
    Element wsXml = (Element)WsConnection.XmlFulltextOperator(SearchString);
    String Status = (String)am.invokeMethod("initSaveXml", wsXml);
    catch(Exception WsExp)
    // WsConnection = new LindorffWS();
    System.out.println("Kall til LindorffWS feilet!");
    am.invokeMethod("initQueryCustomer");
    CustomerAMImpl.java:
    package xxcu.oracle.apps.ar.customer.server;
    import java.io.Serializable;
    import java.sql.CallableStatement;
    import java.sql.SQLException;
    import java.sql.Types;
    import oracle.apps.fnd.common.MessageToken;
    import oracle.apps.fnd.framework.OAException;
    import oracle.apps.fnd.framework.server.OAApplicationModuleImpl;
    import oracle.apps.fnd.framework.server.OADBTransaction;
    import oracle.apps.fnd.framework.server.OAExceptionUtils;
    import org.w3c.dom.Element;
    // --- File generated by Oracle Business Components for Java.
    public class CustomerAMImpl extends OAApplicationModuleImpl implements Serializable
    * This is the default constructor (do not remove)
    public CustomerAMImpl()
    * Sample main for debugging Business Components code using the tester.
    public static void main(String[] args)
    launchTester("xxcu.oracle.apps.ar.customer.server", "CustomerAMLocal");
    * Container's getter for CustomerVO1
    public CustomerVOImpl getCustomerVO1()
    return (CustomerVOImpl)findViewObject("CustomerVO1");
    * 2009.07.09, Roy Feirud, Lagt til for å utføre spørring.
    public void initQueryCustomer()
    CustomerVOImpl vo = getCustomerVO1();
    if (vo!=null)
    vo.initQuery();
    * 2009.08.31, Roy Feirud, Lagt til for å bygge opp input til WebService hos Lindorff.
    public String initBuildString(String Name
    ,String Address
    ,String Zip
    ,String City
    ,String Born
    ,String Phone)
    String ws_string = null;
    CallableStatement cs = null;
    try
    String sql= "BEGIN ISS_WS_LINDORFF_PKG.BUILD_STRING (?,?,?,?,?,?,?); END;";
    OADBTransaction txn = getOADBTransaction();
    cs = txn.createCallableStatement(sql,1);
    cs.setString(1,Name);
    cs.setString(2,Address);
    cs.setString(3,Zip);
    cs.setString(4,City);
    cs.setString(5,Born);
    cs.setString(6,Phone);
    cs.registerOutParameter(7,Types.VARCHAR);
    cs.execute();
    OAExceptionUtils.checkErrors (txn);
    ws_string = cs.getString(7);
    cs.close();
    catch (SQLException sqle)
    String Prosedyre = "ISS_WS_LINDORFF_PKG.BUILD_STRING";
    String Errmsg = sqle.toString();
    MessageToken[] tokens = {new MessageToken("PROSEDYRE", Prosedyre), new MessageToken("ERRMSG", Errmsg)};
    throw new OAException("ISS", "ISS_PLSQL_ERROR",tokens,OAException.ERROR, null);
    return ws_string;
    public String initSaveXml(Element WsXml)
    String Status = "Error";
    CallableStatement cs = null;
    try
    String sql= "BEGIN ISS_XML2TABLE_PKG.ISS_AR_CUSTOMERS_TMP (?,?); END;";
    OADBTransaction txn = getOADBTransaction();
    cs = txn.createCallableStatement(sql,1);
    cs.setObject(1,WsXml);
    cs.registerOutParameter(2,Types.VARCHAR);
    cs.execute();
    OAExceptionUtils.checkErrors (txn);
    Status = cs.getString(2);
    cs.close();
    catch (SQLException sqle)
    String Prosedyre = "ISS_XML2TABLE_PKG.ISS_AR_CUSTOMERS_TMP";
    String Errmsg = sqle.toString();
    MessageToken[] tokens = {new MessageToken("PROSEDYRE", Prosedyre), new MessageToken("ERRMSG", Errmsg)};
    throw new OAException("ISS", "ISS_PLSQL_ERROR",tokens,OAException.ERROR, null);
    return Status;
    LindorffWS.java:
    package xxcu.oracle.apps.ar.customer.ws;
    import oracle.soap.transport.http.OracleSOAPHTTPConnection;
    //import org.apache.soap.encoding.soapenc.BeanSerializer;
    import org.apache.soap.encoding.SOAPMappingRegistry;
    //import org.apache.soap.util.xml.QName;
    import java.util.Vector;
    import org.w3c.dom.Element;
    import java.net.URL;
    import org.apache.soap.Body;
    import org.apache.soap.Envelope;
    import org.apache.soap.messaging.Message;
    import oracle.jdeveloper.webservices.runtime.WrappedDocLiteralStub;
    * Generated by the Oracle9i JDeveloper Web Services Stub/Skeleton Generator.
    * Date Created: Fri Jul 10 10:37:21 CEST 2009
    * WSDL URL: http://services.lindorffmatch.com/Search/Search.asmx?WSDL
    public class LindorffWS extends WrappedDocLiteralStub
    public LindorffWS()
    m_httpConnection = new OracleSOAPHTTPConnection();
    public String endpoint = "http://services.lindorffmatch.com/Search/Search.asmx";
    private OracleSOAPHTTPConnection m_httpConnection = null;
    private SOAPMappingRegistry m_smr = null;
    public Element XmlFulltextOperator(String xmlString) throws Exception
    URL endpointURL = new URL(endpoint);
    Envelope requestEnv = new Envelope();
    Body requestBody = new Body();
    Vector requestBodyEntries = new Vector();
    String wrappingName = "XmlFulltextOperator";
    String targetNamespace = "http://services.lindorffmatch.com/search";
    Vector requestData = new Vector();
    requestData.add(new Object[] {"xmlString", xmlString});
    requestBodyEntries.addElement(toElement(wrappingName, targetNamespace, requestData));
    requestBody.setBodyEntries(requestBodyEntries);
    requestEnv.setBody(requestBody);
    Message msg = new Message();
    msg.setSOAPTransport(m_httpConnection);
    msg.send(endpointURL, "http://services.lindorffmatch.com/search/XmlFulltextOperator", requestEnv);
    Envelope responseEnv = msg.receiveEnvelope();
    Body responseBody = responseEnv.getBody();
    Vector responseData = responseBody.getBodyEntries();
    return (Element)fromElement((Element)responseData.elementAt(0), org.w3c.dom.Element.class);
    _______________________________________________________________________________________________________________________________

    Hi,
    Create an Interface to your application Module then from interface call your method,
    refer http://www.oraclearea51.com/oracle-technical-articles/oa-framework/oa-framework-beginners-guide/213-how-to-call-am-methods-from-controller-without-using-invokemethod.html for creating Interface for AM and calling it in controller.
    Regards,
    Reetesh Sharma

  • Jdev: method invokeMethod(java.lang.String, org.w3c.dom.Element) not found

    I am calling a Web Service that returns an XML-file. The XML-file should be passed to a method that puts the xml into a table in my database.
    I will upload the 3 files that are being used for this.
    When I rebuild my files I get the following error in CustomerCO.java:
    Error(78,38): method invokeMethod(java.lang.String, org.w3c.dom.Element) not found in interface oracle.apps.fnd.framework.OAApplicationModule
    Line 78 reads as follows:
    String Status = (String)am.invokeMethod("initSaveXml", wsXml);
    Any suggestions?
    PS: I am a newbie to java and framework
    Here are my files:
    CustomerCO.java:
    /*===========================================================================+
    Copyright (c) 2001, 2005 Oracle Corporation, Redwood Shores, CA, USA
    All rights reserved.
    ===========================================================================
    HISTORY
    +===========================================================================*/
    package xxcu.oracle.apps.ar.customer.server.webui;
    import java.io.Serializable;
    import java.lang.Exception;
    import oracle.apps.fnd.common.VersionInfo;
    import oracle.apps.fnd.framework.OAApplicationModule;
    import oracle.apps.fnd.framework.webui.OAControllerImpl;
    import oracle.apps.fnd.framework.webui.OAPageContext;
    import oracle.apps.fnd.framework.webui.beans.OAWebBean;
    import org.w3c.dom.Element;
    import xxcu.oracle.apps.ar.customer.ws.LindorffWS;
    * Controller for ...
    public class CustomerCO extends OAControllerImpl implements Serializable
    public static final String RCS_ID="$Header$";
    public static final boolean RCS_ID_RECORDED =
    VersionInfo.recordClassVersion(RCS_ID, "%packagename%");
    * Layout and page setup logic for a region.
    * @param pageContext the current OA page context
    * @param webBean the web bean corresponding to the region
    public void processRequest(OAPageContext pageContext, OAWebBean webBean)
    super.processRequest(pageContext, webBean);
    * Procedure to handle form submissions for form elements in
    * a region.
    * @param pageContext the current OA page context
    * @param webBean the web bean corresponding to the region
    public void processFormRequest(OAPageContext pageContext, OAWebBean webBean)
    super.processFormRequest(pageContext, webBean);
    * 2009.07.09, Roy Feirud, lagt til for å utføre spørring
    if (pageContext.getParameter("Search") != null)
    OAApplicationModule am = pageContext.getApplicationModule(webBean);
    //Setter søkekriteriene til LindorffWS
    String Name = pageContext.getParameter("SearchName");
    String Address = pageContext.getParameter("SearchAddress");
    String Zip = pageContext.getParameter("SearchZipCode");
    String City = pageContext.getParameter("SearchCity");
    String Born = pageContext.getParameter("SearchBorn");
    String Phone = pageContext.getParameter("SearchPhoneNo");
    Serializable[] param = { Name, Address, Zip, City, Born, Phone };
    //Bygger søkestrengen
    String SearchString = (String)am.invokeMethod("initBuildString", param );
    //Initialiserer LindorffWS
    LindorffWS WsConnection = new LindorffWS();
    try
    //Kaller Web Sevice fra Lindorff
    Element wsXml = (Element)WsConnection.XmlFulltextOperator(SearchString);
    String Status = (String)am.invokeMethod("initSaveXml", wsXml);
    catch(Exception WsExp)
    // WsConnection = new LindorffWS();
    System.out.println("Kall til LindorffWS feilet!");
    am.invokeMethod("initQueryCustomer");
    CustomerAMImpl.java:
    package xxcu.oracle.apps.ar.customer.server;
    import java.io.Serializable;
    import java.sql.CallableStatement;
    import java.sql.SQLException;
    import java.sql.Types;
    import oracle.apps.fnd.common.MessageToken;
    import oracle.apps.fnd.framework.OAException;
    import oracle.apps.fnd.framework.server.OAApplicationModuleImpl;
    import oracle.apps.fnd.framework.server.OADBTransaction;
    import oracle.apps.fnd.framework.server.OAExceptionUtils;
    import org.w3c.dom.Element;
    // --- File generated by Oracle Business Components for Java.
    public class CustomerAMImpl extends OAApplicationModuleImpl implements Serializable
    * This is the default constructor (do not remove)
    public CustomerAMImpl()
    * Sample main for debugging Business Components code using the tester.
    public static void main(String[] args)
    launchTester("xxcu.oracle.apps.ar.customer.server", "CustomerAMLocal");
    * Container's getter for CustomerVO1
    public CustomerVOImpl getCustomerVO1()
    return (CustomerVOImpl)findViewObject("CustomerVO1");
    * 2009.07.09, Roy Feirud, Lagt til for å utføre spørring.
    public void initQueryCustomer()
    CustomerVOImpl vo = getCustomerVO1();
    if (vo!=null)
    vo.initQuery();
    * 2009.08.31, Roy Feirud, Lagt til for å bygge opp input til WebService hos Lindorff.
    public String initBuildString(String Name
    ,String Address
    ,String Zip
    ,String City
    ,String Born
    ,String Phone)
    String ws_string = null;
    CallableStatement cs = null;
    try
    String sql= "BEGIN ISS_WS_LINDORFF_PKG.BUILD_STRING (?,?,?,?,?,?,?); END;";
    OADBTransaction txn = getOADBTransaction();
    cs = txn.createCallableStatement(sql,1);
    cs.setString(1,Name);
    cs.setString(2,Address);
    cs.setString(3,Zip);
    cs.setString(4,City);
    cs.setString(5,Born);
    cs.setString(6,Phone);
    cs.registerOutParameter(7,Types.VARCHAR);
    cs.execute();
    OAExceptionUtils.checkErrors (txn);
    ws_string = cs.getString(7);
    cs.close();
    catch (SQLException sqle)
    String Prosedyre = "ISS_WS_LINDORFF_PKG.BUILD_STRING";
    String Errmsg = sqle.toString();
    MessageToken[] tokens = {new MessageToken("PROSEDYRE", Prosedyre), new MessageToken("ERRMSG", Errmsg)};
    throw new OAException("ISS", "ISS_PLSQL_ERROR",tokens,OAException.ERROR, null);
    return ws_string;
    public String initSaveXml(Element WsXml)
    String Status = "Error";
    CallableStatement cs = null;
    try
    String sql= "BEGIN ISS_XML2TABLE_PKG.ISS_AR_CUSTOMERS_TMP (?,?); END;";
    OADBTransaction txn = getOADBTransaction();
    cs = txn.createCallableStatement(sql,1);
    cs.setObject(1,WsXml);
    cs.registerOutParameter(2,Types.VARCHAR);
    cs.execute();
    OAExceptionUtils.checkErrors (txn);
    Status = cs.getString(2);
    cs.close();
    catch (SQLException sqle)
    String Prosedyre = "ISS_XML2TABLE_PKG.ISS_AR_CUSTOMERS_TMP";
    String Errmsg = sqle.toString();
    MessageToken[] tokens = {new MessageToken("PROSEDYRE", Prosedyre), new MessageToken("ERRMSG", Errmsg)};
    throw new OAException("ISS", "ISS_PLSQL_ERROR",tokens,OAException.ERROR, null);
    return Status;
    LindorffWS.java:
    package xxcu.oracle.apps.ar.customer.ws;
    import oracle.soap.transport.http.OracleSOAPHTTPConnection;
    //import org.apache.soap.encoding.soapenc.BeanSerializer;
    import org.apache.soap.encoding.SOAPMappingRegistry;
    //import org.apache.soap.util.xml.QName;
    import java.util.Vector;
    import org.w3c.dom.Element;
    import java.net.URL;
    import org.apache.soap.Body;
    import org.apache.soap.Envelope;
    import org.apache.soap.messaging.Message;
    import oracle.jdeveloper.webservices.runtime.WrappedDocLiteralStub;
    * Generated by the Oracle9i JDeveloper Web Services Stub/Skeleton Generator.
    * Date Created: Fri Jul 10 10:37:21 CEST 2009
    * WSDL URL: http://services.lindorffmatch.com/Search/Search.asmx?WSDL
    public class LindorffWS extends WrappedDocLiteralStub
    public LindorffWS()
    m_httpConnection = new OracleSOAPHTTPConnection();
    public String endpoint = "http://services.lindorffmatch.com/Search/Search.asmx";
    private OracleSOAPHTTPConnection m_httpConnection = null;
    private SOAPMappingRegistry m_smr = null;
    public Element XmlFulltextOperator(String xmlString) throws Exception
    URL endpointURL = new URL(endpoint);
    Envelope requestEnv = new Envelope();
    Body requestBody = new Body();
    Vector requestBodyEntries = new Vector();
    String wrappingName = "XmlFulltextOperator";
    String targetNamespace = "http://services.lindorffmatch.com/search";
    Vector requestData = new Vector();
    requestData.add(new Object[] {"xmlString", xmlString});
    requestBodyEntries.addElement(toElement(wrappingName, targetNamespace, requestData));
    requestBody.setBodyEntries(requestBodyEntries);
    requestEnv.setBody(requestBody);
    Message msg = new Message();
    msg.setSOAPTransport(m_httpConnection);
    msg.send(endpointURL, "http://services.lindorffmatch.com/search/XmlFulltextOperator", requestEnv);
    Envelope responseEnv = msg.receiveEnvelope();
    Body responseBody = responseEnv.getBody();
    Vector responseData = responseBody.getBodyEntries();
    return (Element)fromElement((Element)responseData.elementAt(0), org.w3c.dom.Element.class);
    _______________________________________________________________________________________________________________________________

    Hi,
    wrong forum. If this is a problem related to the use of OA framework, please use the OA framework forum here on OTN
    Frank

  • Simple webcrawler

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Vector;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class WebCrawler implements Runnable{
          // URLs to be searched
        Vector<String> vectorToSearch = new Vector<String>();
        // URLs already searched
        Vector<String> vectorSearched = new Vector<String>();
        // URLs which match
        Vector<String> vectorMatches = new Vector<String>();
        String address = "http://www.bloomberg.com";
         public static void main(String[] args){
              WebCrawler webCrawler = new WebCrawler();
              webCrawler.start();
         public void start() {
              vectorToSearch.add(address);
              run();
         public void run() {
              try{
                   while (vectorToSearch.size() > 0){
                        System.out.println("Searching "+vectorToSearch.get(0));
                        getAndParsePage(vectorToSearch.get(0));
              catch(Exception e){
                   e.printStackTrace();
         private void getAndParsePage(String add) throws IOException{
              try{
                   URL url = new URL(add);
                   BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                   String i;
                   Vector<String> thisUrl = null;
                   thisUrl = new Vector<String>();
                   while (((i=in.readLine()) != null)){thisUrl.add(i);}
                   for (String input : thisUrl){
                        if (input.indexOf("href=\"http://")!=-1){
                             Pattern pattern = Pattern.compile("http://.*\"");
                             Matcher matcher = pattern.matcher(input);
                             if (matcher.find()){
                                  String result = matcher.group();
                                  result = result.substring(0,result.indexOf("\""));
                                  try {
                                       URL urlLink = new URL(result);
                                       result = urlLink.toString();
                                       if (!result.equals(add))
                                            if(!wasSearched(add))
                                                 vectorToSearch.add(0,result);
                                   catch (MalformedURLException e) {
              }catch(Exception e){
              vectorToSearch.remove(add);
              vectorSearched.add(add);
              System.out.println("closing "+add);
         private boolean wasSearched(String add){
              for (String s : vectorSearched) if (s.equals(add))return true;
              return false;
    }the problem is i search some urls more then once
    Message was edited by:
    Kernel_77

    kernel,
    Pattern.compile("http://.*\"");
    the .* is greedy, meaning that it'll keep matching to the end of the line... sugest you try [^\"]*\" in place of .*
    can't see why it would search some URL's twice though... unless they're in the source page twice.
    keith/
    Message was edited by: corlettk

  • How do you search for a partial match in a vector table?

    Hi,
    I have a program that parses some table of mine into a vector table. It has a search function in the program that is intended to search the vector table for a specified keyword that the user enters. If a match is found, it returns true. If no match is found, false is returned.
    That part works great. However, I would like my program to search the vector table to try and find a PARTIAL match of the users entry, instead of looking for a complete match.
    Currently my program uses the Vector method 'contains(Object elem)' to find the complete matches and that part works great. It doesn't seem to work with partial matches. Either the exact syntax of the user's entry is in the table or it isn't.
    Hope I was clear enough. Any thoughts?
    Cheers,
    the sherlock

    You might find this code of interest. It uses the same commands as mentioned previously, but wraps them into a Comparator object. Note that you can't store elements with '*' in the Vector 'v' and that you must sort the elements with Collections.sort() beforehand.
    import java.util.*;
    class WildcardComparator implements Comparator
        public int compare(Object o1, Object o2)
         String string1 = (String)o1;
         String string2 = (String)o2;
         if(string2.indexOf("*") != -1) {
             // take off asterik
             return wildcardCompare(string1,
                           string2.substring(0, string2.length()-1));
         return string1.compareTo(string2);
        public int wildcardCompare(String s1, String key_s) {
         String s1substring = s1.substring(0, key_s.length());
         return s1substring.compareTo(key_s);
    public class wildcard
        public static void main(String[] args)
         Vector v = new Vector();
         v.add("coke");
         v.add("pepsi");
         v.add("7-up");
         v.add("a&w root beer");
         v.add("a&w cream");
         Collections.sort(v, new WildcardComparator());
         String key = "a&w*";
         int index = Collections.binarySearch(v,
                                  key,
                                  new WildcardComparator());
         if(index > 0)
             System.out.println("elem: " + v.get(index));
         else
             System.out.println("item not found");
         key = "c*";
         index = Collections.binarySearch(v,
                                  key,
                                  new WildcardComparator());
         if(index > 0)
             System.out.println("elem: " + v.get(index));
         else
             System.out.println("item not found");
    }

  • Searching for String in Vector

    I know I posted just a few minutes ago about sorting, but I'm making a program (not related to homework at all, this is all for my parents business) and my program needs to store names and fetch them. We have thousands of people in our contacts so it's only logical that I would provide searching so that my mom could easily find a contact she is looking for.
    The contacts are stored in a vector, first name, last name, address, etc. I want to provide a search function that can search the names, or addresss, or both. Then, when a match is found, it returns the results to a JList or something.
    Search Text: "St. Marie"
    Results:
    1. St. Marie, Josh
    2. St. Marie, Someone
    etc etc...

    My program uses files, it uses the files to populate the vector. I'm using a vector, not an array or anything else to access the data in the files. heres a sample of the save method in my program.private void saveContacts ()
          FileOutputStream fos = null;
          try
              fos = new FileOutputStream ("contacts.dat");
              DataOutputStream dos = new DataOutputStream (fos);
              dos.writeInt (contacts.size ());
              for (int i = 0; i < contacts.size (); i++)
                   Contact temp = (Contact) contacts.elementAt (i);
                   dos.writeUTF (temp.fname);
                   dos.writeUTF (temp.lname);
                   dos.writeUTF (temp.phone);
                   dos.writeUTF (temp.fax);
                   dos.writeUTF (temp.email);
          catch (IOException e)
             MsgBox mb = new MsgBox (this, "CM Error",
                                     e.toString ());
             mb.dispose ();
          finally
             if (fos != null)
                 try
                     fos.close ();
                 catch (IOException e) {}
       }The variable "contacts" is my vector.

  • Problem using a vector of strings as patterns to search a text file

    Ideas? Goal is to use several patterns from one file to search for matches in a second file, one pattern at a time. I have added the file of patterns to a vector and created an iterator to grab each pattern successively. I also can effectively search for matches in the second file, but can't seem to find a way to combine them. I've tried nested while(s) in both orders without success.
    Thank you for any suggestions.

    It sounds to me like it should work. What does your search code look like?

  • Searching a Vector of objects

    I'm embarassed to ask this question but I haven't figured out the answer myself yet so I need help.
    I need to be able to search a Vector (it could be an Array just as easily) by only certain parts of the objects in the vector. So for example I have vector v that contains 10 objects o. Objects o are a very small custom class that each have a name and a number. How do I search the vector for the object o that contains name x?
    I tried overriding the equals method of object o and using the IndexOf method of vector v but that did not work.

    I'm embarassed to ask this question but I haven't
    figured out the answer myself yet so I need help.
    I need to be able to search a Vector (it could be an
    Array just as easily) by only certain parts of the
    objects in the vector. So for example I have vector
    v that contains 10 objects o. Objects o are a very
    small custom class that each have a name and a
    number. How do I search the vector for the object o
    that contains name x?Iterate over the Vector and ask each element whether its name is x.
    I tried overriding the equals method of object o and
    using the IndexOf method of vector v but that did not
    work.What does "did not work" mean?

  • Searching through very large vectors

    I am working on a way to process two flat tab delimited files into a tree, assign a x and y coordinate to each node in the tree and output all the nodes (with their coordinates) to a new flat file.
    I currently have a program that works pretty well. It roughly uses the following flow.
    - Read both files into memory (by opening the file reading each line and load the appropriate data from each line into a Vector, making sure no duplicates are entered by comparing the currentline to the last line.
    - Using the first vector (which contains the strating nodes) search through the second vector (which contains parent child relationships between 2 nodes) to construct the tree. For this tree I use a XML DOM Document. In this logic I use a for loop to find all the children for the given node. I store the index of each found reference and when all children are found I loop through all the indexes and delete those records from the parent-child vector.
    - After the tree is created I walk through the tree and assign each node a x and y attribute.
    - When this is done I create a NodeList and use are for-loop to write each node (with x and y) to a StringBuffer which is then written to a file. In this process for each new node that is written I check (in the StringBuffer) if the node (name) is present. If not I write the new Node.
    - For debugging purposes I write all the references from the second Vector to a file and output the XML DOM tree to a XML file.
    This program works wel. It handles files with 10000 start nodes and 20000 parent-child references (30000 nodes in total) in under 2 minutes (using 1:20 for the generation of the output file).
    However when the volume of these file increase it starts to struggle.
    As the ultimate test I ran it with a file that contains 250000 start nodes and 500000 references. For it to run I need to use the -Xmx256m parameter to allocate extra memory. But I ran it for 2 hours and killed it because I didn't want to wait longer.
    What I would like to know is how I can approach this better. Right now I'm loading the data from the files into memory entirely. Maybe this isn't the best approach.
    Also I'm looping through a Vector with 500000 elements, how can this be done more efficiently? However the reference vector isn't sorted in any way.

    Hi,
    That's no problem.. Here's some sample code:
    package tests;
    import java.util.List;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.Iterator;
    class Example {
        private List roots;
        private Map elements;
        public Example() {
            roots = new LinkedList();
            elements = new HashMap();
        public void initRoots(String[] rows) {
            for (int i=0; i<rows.length; i++) {
                String[] parts = rows.split(" ");
    String name = parts[0];
    roots.add(name);
    elements.put(name, new Node(name));
    public void addChilds(String[] rows) {
    for (int i=0; i<rows.length; i++) {
    String[] parts = rows[i].split(" ");
    String parentId = parts[1];
    String name = parts[2];
    addNode(parentId, name);
    private void addNode(String parentId, String name) {
    Node current = (Node)elements.get(name);
    if (current == null) {
    current = new Node(name);
    elements.put(name, current);
    Node parent = (Node)elements.get(parentId);
    if (parent == null) {
    //Parent is missing, is that a problem?. Create it now.
    parent = new Node(parentId);
    elements.put(parentId, parent);
    return;
    parent.addChild(current);
    public void printTree() {
    for (Iterator it = roots.iterator(); it.hasNext(); ) {
    String id = (String)it.next();
    printChildren(id, 1);
    private void printChildren(String id, int depth) {
    Node node = (Node)elements.get(id);
    System.out.println(node);
    private static final class Node {
    private String name;
    private List children;
    private Node(String name) {
    this.name = name;
    children = new LinkedList();
    public void addChild(Node node) {
    children.add(node);
    public String toString() {
    return name + " " + children;
    public static void main(String[] args) throws Exception {
    Example test = new Example();
    test.initRoots(new String[] {
    "SU_1 1 1 1 0 0 0 0",
    "SU_2 1 1 1 0 0 0 0",
    "SU_3 1 1 1 0 0 0 0"
    test.addChilds(new String[] {
    "COM_1 SU_1 PR_1 0 0 0 0 0",
    "COM_1 PR_1 ST_1 0 0 0 0 0",
    "COM_2 SU_2 PR_2 0 0 0 0 0",
    "COM_2 PR_2 ST_2 0 0 0 0 0",
    "COM_3 SU_3 PR_3 0 0 0 0 0",
    "COM_3 PR_3 ST_3 0 0 0 0 0"
    test.printTree();
    The execution prints:
    SU_1 [PR_1 [ST_1 []]]
    SU_2 [PR_2 [ST_2 []]]
    SU_3 [PR_3 [ST_3 []]]
    /Kaj

  • Urgent pls help!! How to search for an object in vectors?

    Hi,
    I heard that a Vector can store an object right?
    So lets say I created an object called Student that has the attributes: id, name, sex, age
    1) Is vector able to store many students with all these attributes? cos the examples i have seen so far vector only seems to store one attribute
    2) how do i search for sumthin in a vector? let's say i want to key in the student id or his name and find tt student's record to display it?
    thx!

    so sorry... apparantly i didnt copy the last few brackets..
    ===============================================================
    import java.io.*;
    import java.util.*;
    class AddReservation
         static BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
         //Main Method
         public static void main (String[]args)throws IOException
              String custName, comments;
              int covers, date, startTime, endTime;
              int count = 0;
              //User can only add one reservation at a time
              do
                   //Create a new reservation
                   Reservation oneReservation=new Reservation();                         
                   System.out.println("Please enter customer's name:");
                   System.out.flush();
                   custName = stdin.readLine();
                   oneReservation.setcustName(custName);
                   System.out.println("Please enter number of covers:");
                   System.out.flush();
                   covers = Integer.parseInt(stdin.readLine());
                   oneReservation.setCovers(covers);
                   System.out.println("Please enter date:");
                   System.out.flush();
                   date = Integer.parseInt(stdin.readLine());
                   oneReservation.setDate(date);
                   System.out.println("Please enter start time:");
                   System.out.flush();
                   startTime = Integer.parseInt(stdin.readLine());
                   oneReservation.setstartTime(startTime);
                   System.out.println("Please enter end time:");
                   System.out.flush();
                   endTime = Integer.parseInt(stdin.readLine());
                   oneReservation.setendTime(endTime);
                   System.out.println("Please enter comments, if any:");
                   System.out.flush();
                   comments = stdin.readLine();
                   oneReservation.setComments(comments);
                   count++;
              while (count<1);
              class Reservation
              private Reservation oneReservation;
              private String custName, comments;
              private int covers, startTime, endTime, date;
              //Default constructor
              public Reservation()
              public Reservation(String custName, int covers, int date, int startTime, int endTime, String comments)
                   this.custName=custName;
                   this.covers=covers;
                   this.date=date;
                   this.startTime=startTime;
                   this.endTime=endTime;
                   this.comments=comments;
              //Setter methods
              public void setcustName(String custName)
                   this.custName=custName;
              public void setCovers(int covers)
                   this.covers=covers;;
              public void setDate(int date)
                   this.date=date;
              public void setstartTime(int startTime)
                   this.startTime=startTime;
              public void setendTime(int endTime)
                   this.endTime=endTime;
              public void setComments(String comments)
                   this.comments=comments;
              //Getter methods
              public String getcustName()
                   return custName;
              public int getCovers()
                   return covers;
              public int getDate()
                   return date;
              public int getstartTime()
                   return startTime;
              public int getendTime()
                   return endTime;
              public String getComments()
                   return comments;
              //Display the current reservation
              //public void displayReservation()
         //          System.out.println(custName.getcustName());
         //          System.out.println(covers.getCovers());
         //          System.out.println(date.getDate());
         //          System.out.println(startTime.getstartTime());
         //          System.out.println(endTime.getendTime());
         //          System.out.println(comments.getComments());
    ===============================================================
    import java.io.*;
    import java.util.*;
    class searchBooking
         static BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
         public static void main (String[]args)throws IOException
              int choice, date, startTime;
              String custName;
                   //Search Menu
                   System.out.println("Search By: ");
                   System.out.println("1. Date");
                   System.out.println("2. Name of Customer");
                   System.out.println("3. Date & Name of Customer");
                   System.out.println("4. Date & Start time of reservation");
                   System.out.println("5. Date, Name of customer & Start time of reservation");
                   System.out.println("Please make a selection: ");          
                   //User keys in choice
                   System.out.flush();
                   choice = Integer.parseInt(stdin.readLine());
                   if (choice==1)
                        System.out.println("Please key in Date (DDMMYY):");
                        System.out.flush();
                        date = Integer.parseInt(stdin.readLine());
                   else if (choice==2)
                             System.out.println("Please key in Name of Customer:");
                             System.out.flush();
                             custName = stdin.readLine();
                   else if (choice==3)
                             System.out.println("Please key in Date (DDMMYY):");
                             System.out.flush();
                             date = Integer.parseInt(stdin.readLine());
                             System.out.println("Please key in Name of Customer:");
                             System.out.flush();
                             custName = stdin.readLine();
                   else if (choice==4)
                             System.out.println("Please key in Date (DDMMYY):");
                             System.out.flush();
                             date = Integer.parseInt(stdin.readLine());
                             System.out.println("Please key in Start time:");
                             System.out.flush();
                             startTime = Integer.parseInt(stdin.readLine());
                   else if (choice==5)
                             System.out.println("Please key in Date (DDMMYY):");
                             System.out.flush();
                             date = Integer.parseInt(stdin.readLine());
                             System.out.println("Please key in Name of Customer:");
                             System.out.flush();
                             custName = stdin.readLine();
                             System.out.println("Please key in Start time:");
                             System.out.flush();
                             startTime = Integer.parseInt(stdin.readLine());
              public void           
    }

Maybe you are looking for