Help with simple pong program

Hi, I'm in APCS and I was wondering if you guys can help me out with my code. I'm designing Pong, except instead of having 2 paddles it will have 4. I think i have 95% of my code down, enough to get the program running. However, my compiler cannot recognize the move methods for my paddles:
--------------------Configuration: Pong - JDK version 1.6.0_02 <Default> - <Default>--------------------
F:\Documents\AP Computer Science-Java Applications\Pong\Pong\src\Pong.java:106: cannot find symbol
symbol : method paddleMove(PingPongBall)
location: class Paddle
computerPaddle1.paddleMove( ball );
^
F:\Documents\AP Computer Science-Java Applications\Pong\Pong\src\Pong.java:177: cannot find symbol
symbol : method paddleMove(int)
location: class Paddle
playerPaddle1.paddleMove( mouseY );
^
F:\Documents\AP Computer Science-Java Applications\Pong\Pong\src\Pong.java:178: cannot find symbol
symbol : method paddleMove(int)
location: class Paddle
playerPaddle2.paddleMove( mouseY );
^
Note: F:\Documents\AP Computer Science-Java Applications\Pong\Pong\src\Pong.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
3 errors
Process completed.
And I guess I also use old methods of coding, according to the deprecated API note.
What do you think could possibly be causing these errors to be thrown? I'm pretty sure I have everything spelled correctly...
Thanks for all your help. :) Any comments/advice/criticism is welcome.

1. If you're using an IDE such as NetBeans or Eclipse, do a "Clean Project", then a "Build All". See if that clears up the problem.
2. If it doesn't, then your Paddle class does not have a paddleMove(PingPongBall) or paddleMove(int) method. If other Paddle class methods are being found okay (i.e., you get no compiler errors where you use them), then it definitely means that your compiler is picking up an older version of your Paddle class, one without those methods defined. If no paddle methods are resolving okay, then that means your compiler can't find your Paddle class at all.
Open your Paddle class and carefully verify that these two methods exist. If they do, then something is wrong with your IDE configuration/Ant script/whatever you're using to compile, and it's not finding the (correct) Paddle.class file.
As for the deprecation warning, do what it says: Change your compile command to include the "-Xlint:deprecation" parameter and recompile. It will tell you the line number(s) where you're calling deprecated methods.
Post back with your results.

Similar Messages

  • Need Help with Simple Chat Program

    Hello Guys,
    I'm fairly new to Java and I have a quick question regarding a simple chat program in java. My problem is that I have a simple chat program that runs from its own JFrame etc. Most of you are probably familiar with the code below, i got it from one of my java books. In any case, what I'm attempting to do is integrate this chat pane into a gui that i have created. I attempted to call an instace of the Client class from my gui program so that I can use the textfield and textarea contained in my app, but it will not allow me to do it. Would I need to integrate this code into the code for my Gui class. I have a simple program that contains chat and a game. The code for the Client is listed below.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class Client
    extends JPanel {
    public static void main(String[] args) throws IOException {
    String name = args[0];
    String host = args[1];
    int port = Integer.parseInt(args[2]);
    final Socket s = new Socket(host, port);
    final Client c = new Client(name, s);
    JFrame f = new JFrame("Client : " + name);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    c.shutDown();
    System.exit(0);
    f.setSize(300, 300);
    f.setLocation(100, 100);
    f.setContentPane(c);
    f.setVisible(true);
    private String mName;
    private JTextArea mOutputArea;
    private JTextField mInputField;
    private PrintWriter mOut;
    public Client(final String name, Socket s)
    throws IOException {
    mName = name;
    createUI();
    wireNetwork(s);
    wireEvents();
    public void shutDown() {
    mOut.println("");
    mOut.close();
    protected void createUI() {
    setLayout(new BorderLayout());
    mOutputArea = new JTextArea();
    mOutputArea.setLineWrap(true);
    mOutputArea.setEditable(false);
    add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
    mInputField = new JTextField(20);
    JPanel controls = new JPanel();
    controls.add(mInputField);
    add(controls, BorderLayout.SOUTH);
    mInputField.requestFocus();
    protected void wireNetwork(Socket s) throws IOException {
    mOut = new PrintWriter(s.getOutputStream(), true);
    final String eol = System.getProperty("line.separator");
    new Listener(s.getInputStream()) {
    public void processLine(String line) {
    mOutputArea.append(line + eol);
    mOutputArea.setCaretPosition(
    mOutputArea.getDocument().getLength());
    protected void wireEvents() {
    mInputField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String line = mInputField.getText();
    if (line.length() == 0) return;
    mOut.println(mName + " : " + line);
    mInputField.setText("");

    Thanks for ur help!i have moved BufferedReader outside the loop. I dont think i am getting exception as i can c the output once.What i am trying to do is repeat the process which i m getting once.What my method does is first one sends the packet to multicasting group (UDP) and other method receives the packets and prints.

  • Need Help with simple array program!

    Hi, I have just recently started how to use arrays[] in Java and I'm a bit confused and need help designing a program.
    What this program does, it reads in a range of letters specified by the user. The user then enters the letters (a, b or c) and stores these characters into an array, which the array's length is equal to the input range the user would enter at the start of the program. The program is then meant to find how many times (a,b and c) appears in the array and the Index it first appears at, then prints these results.
    Here is my Code for the program, hopefully this would make sense of what my program is suppose to do.
    import B102.*;
    class Letters
         static int GetSize()
              int size = 0;
              boolean err = true;
              while(err == true)
                   Screen.out.println("How Many Letters would you like to read in?");
                   size = Keybd.in.readInt();
                   err = Keybd.in.fail();
                   Keybd.in.clearError();
                   if(size <= 0)
                        err = true;
                        Screen.out.println("Invalid Input");
              return(size);
         static char[] ReadInput(int size)
              char input;
              char[] letter = new char[size];
              for(int start = 1; start <= size; start++)
                   System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
                   input = Keybd.in.readChar();
                   while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#'))
                        Screen.out.println("Invalid Input");
                        System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
                        input = Keybd.in.readChar();
                                    while(input == '#')
                                                 start == size;
                                                 break;
                   for(int i = 0; i < letter.length; i++)
                        letter[i] = input;
              return(letter);
         static int CountA(char[] letter)
              int acount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'a')
                        acount++;
              return(acount);
         static int CountB(char[] letter)
              int bcount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'b')
                        bcount++;
              return(bcount);
         static int CountC(char[] letter)
              int ccount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'c')
                        ccount++;
              return(ccount);
         static int SearchA(char[] letter)
              int ia;
              for(ia = 0; ia < letter.length; ia++)
                   if(letter[ia] == 'a')
                        return(ia);
              return(ia);
         static int SearchB(char[] letter)
              int ib;
              for(ib = 0; ib < letter.length; ib++)
                   if(letter[ib] == 'b')
                        return(ib);
              return(ib);
         static int SearchC(char[] letter)
              int ic;
              for(ic = 0; ic < letter.length; ic++)
                   if(letter[ic] == 'c')
                        return(ic);
              return(ic);
         static void PrintResult(char[] letter, int acount, int bcount, int ccount, int ia, int ib, int ic)
              if(ia <= 1)
                   System.out.println("There are "+acount+" a's found, first appearing at index "+ia);
              else
                   System.out.println("There are no a's found");
              if(ib <= 1)
                   System.out.println("There are "+bcount+" b's found, first appearing at index "+ib);
              else
                   System.out.println("There are no b's found");
              if(ic <= 1)
                   System.out.println("There are "+ccount+" c's found, first appearing at index "+ic);
              else
                   System.out.println("There are no c's found");
              return;
         public static void main(String args[])
              int size;
              char[] letter;
              int acount;
              int bcount;
              int ccount;
              int ia;
              int ib;
              int ic;
              size = GetSize();
              letter = ReadInput(size);
              acount = CountA(letter);
              bcount = CountB(letter);
              ccount = CountC(letter);
              ia = SearchA(letter);
              ib = SearchB(letter);
              ic = SearchC(letter);
              PrintResult(letter, acount, bcount, ccount, ia, ib, ic);
              return;
    }     Some errors i get with my program are:
    When reading in the letters to store into the array, I get the last letter I entered placed into the entire array. Also I believe my code to find the Index is incorrect.
    Example Testing: How many letters would you like to read? 3
    Enter letter (a, b or c) (# to quit): a
    Enter letter (a, b or c) (# to quit): b
    Enter letter (a, b or c) (# to quit): c
    It prints "There are no a's'" (there should be 1 a at index 0)
    "There are no b's" (there should be 1 b at index 1)
    and "There are 3 c's, first appearing at index 0" ( there should be 1 c at index 2)
    The last thing is that my code for when the user enters "#" that the input of letters would stop and the program would then continue over to the counting and searching part for the letters, my I believe is correct but I get the same problem as stated above where the program takes the character "#" and stores it into the entire array.
    Example Testing:How many letters would you like to read? 3
    Enter letter (a, b or c) (# to quit): a
    Enter letter (a, b or c) (# to quit): #
    It prints "There are no a's'" (should have been 1 a at index 0)
    "There are no b's"
    and "There are no c's"
    Can someone please help me??? or does anyone have a program simular to this they have done and would'nt mind showing me how it works?
    Thanks
    lou87.

    Without thinking too much...something like this
    for(int start = 0; start < size; start++) {
                System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
                input = Keybd.in.readChar();
                while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#')) {
                    Screen.out.println("Invalid Input");
                    System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
                    input = Keybd.in.readChar();
                if(input == '#') {
                        break;
                letter[start] = input;
            }you dont even need to do start = size; coz with the break you go out of the for loop.

  • Help with simple array program

    my program compiles and runs but when after i enter in 0 it says that the total cost is 0.0 any help would be great thanks
    /**Write a program that asks the user for the price and quantity of up to 10 items. The program accepts input until the user enters a price of 0. 
    *The program applies a 7% sales tax and prints the total cost.
    Sample
    Enter price 1:
    1.95
    Enter quantity 1:
    2
    Enter price 2:
    5.00
    Enter quantity 2:
    1
    Enter price 3:
    0
    Your total with tax is 9.52
    import java.util.*;
    public class Cashregister
    static Scanner input = new Scanner(System.in);
    static double userinput = 1;
    public static void main(String[] args)
      int anykey;
      int howmanyproducts;
      System.out.println("This Program will allow you to enter the price and quanity of a set of items until you press zero, and after you press zero it will put the tax on it and give you the subtotal.");
      int whichproduct = 1;//used to say what
      int whichquanity = 1;
      double beforetax = 0;
      double aftertax = 0;
      double [] finalproduct = new double [9];
      double [] finalquant = new double[9];
      double [] finalanswer = new double[9];
      double taxrate = .07;
      int index = 0;
      while(userinput !=0)
       System.out.println("Enter price " + whichproduct + ":");
       userinput = input.nextDouble();
       whichproduct ++;
       if(userinput != 0)
       finalproduct[index] = userinput;
       System.out.println("Enter quanity " + whichquanity + ":");
       userinput = input.nextInt();
       finalquant[index] = userinput;
       whichquanity ++;
       index ++;
      else
      int [] indecies = new int [index];//used for array.length purposes
       for(int j = 0; j<indecies.length; j++)
         finalanswer[index] = finalproduct[index] * finalquant[index];
      for(int k = 0; k < indecies.length; k++)
         finalanswer[k] = finalanswer[k] + finalanswer[k];
         beforetax = finalanswer[k];
         aftertax = beforetax * taxrate;
      System.out.println("The total cost with tax will be $" + aftertax);
    }

    I tried ot indent better so it is more readable and i removed the tax out of my loop along with another thing i knew wasnt supposed to be their. Ran it again and i still got the same total coast = 0.0
    import java.util.*;
    public class Cashregister
    static Scanner input = new Scanner(System.in);
    static double userinput = 1;
    public static void main(String[] args)
      int anykey;
      int howmanyproducts;
      System.out.println("This Program will allow you to enter the price and quanity of a set of items until you press zero, and after you press zero it will put the tax on it and give you the subtotal.");
      int whichproduct = 1;
      int whichquanity = 1;
      double beforetax = 0;
      double aftertax = 0;
      double [] finalproduct = new double [9];
      double [] finalquant = new double[9];
      double [] finalanswer = new double[9];
      double taxrate = .07;
      int index = 0;
      while(userinput !=0)
       System.out.println("Enter price " + whichproduct + ":");
       userinput = input.nextDouble();
       whichproduct ++;
            if(userinput != 0)
                    finalproduct[index] = userinput;
                    System.out.println("Enter quanity " + whichquanity + ":");
                    userinput = input.nextInt();
                    finalquant[index] = userinput;
                    whichquanity ++;
                    index ++;
            else
                    int [] indecies = new int [index];
                    for(int j = 0; j<indecies.length; j++)
                            finalanswer[index] = finalproduct[index] * finalquant[index];
                    for(int k = 0; k < indecies.length; k++)
                           finalanswer[0] = finalanswer[k] + finalanswer[k];
                    beforetax = finalanswer[0];
                    aftertax = beforetax * taxrate;
                    System.out.println("The total cost with tax will be $" + aftertax);
    }

  • Help with Simple JAVA program

    I'm a complete novice with Java. I want to write a Java program to run on Windows 2000 servers to write a list of certain files in a directory into a *.txt file. I hope to add complexity once I have this basic part working. Here's the code I have so far:
    //this Java application finds poll* files
    public class FindPollApp
    //Create File Object
    File dir = new File("d:/jda/windss/poll");
    //List directory
    if(dir.isDirectory())
    String[] dirContents = dir.list();
    for (int i=0; i < dirContents.length; i++)
    System.out.println(dirContents);
    //Iterate through files
    I get the following errors:
    C:\JAVA>javac FindPollApp.java
    FindPollApp.java:9: illegal start of type
    if(dir.isDirectory())
    ^
    FindPollApp.java:18: <identifier> expected
    ^
    2 errors
    Thanks.

    I'm a complete novice with Java. I want to write a
    Java program to run on Windows 2000 servers to write
    a list of certain files in a directory into a *.txt
    file. I hope to add complexity once I have this
    basic part working. Here's the code I have so far:
    //this Java application finds poll* files
    public class FindPollApp
    //Create File Object
    File dir = new File("d:/jda/windss/poll");
    //List directory
    if(dir.isDirectory())
    String[] dirContents = dir.list();
    for (int i=0; i < dirContents.length; i++)
    System.out.println(dirContents);
    //Iterate through files
    I get the following errors:
    C:\JAVA>javac FindPollApp.java
    FindPollApp.java:9: illegal start of type
    if(dir.isDirectory())
    ^
    FindPollApp.java:18: <identifier> expected
    ^
    2 errors
    Thanks.
    You need to create a method and insert your if statement in there

  • Help with simple bidding program

    I have a BiddingServer and a BiddingClient, Everytime a client connects it connects twice for some reason, and shows "New Bidder Accepted" twice... Can't work out why, any help appreciated.... I dont know whether the problem is here or in the client and i appreciate its looong so if no one spots a problem here ill post the client....
    import java.io.*;
    import java.net.*;
    import java.text.DecimalFormat;
    import java.util.*;
    public class BiddingServer
         private static ServerSocket servSocket;
         private static final int PORT = 1234;
         public static Scanner keyboard = new Scanner(System.in);
         public static String itemDescripOne = "TV", itemCodeOne = "123";
         public static String itemDescripTwo = "Toaster", itemCodeTwo = "321";
         public static float itemPriceOne = 100, itemPriceTwo = 200;
         public static Calendar deadlineOne;
         public static Calendar deadlineTwo;
         private static int clientCount =0;
         public static void main(String[] args)throws IOException
         Calendar start = Calendar.getInstance();
         int date = start.get(Calendar.DATE);
         int month = start.get(Calendar.MONTH);
         int year = start.get(Calendar.YEAR);
                   System.out.printf("\nEnter First Item's finishing bid time");
                   String timeString = BiddingServer.keyboard.nextLine();
                   String hourString = timeString.substring(0,2);
                   int hour = Integer.parseInt(hourString);
                   String minString = timeString.substring(3,5);
                   int minute = Integer.parseInt(minString);
                   BiddingServer.deadlineOne = Calendar.getInstance();//Set up Calendar object to hold deadline time...
                   BiddingServer.deadlineOne.set(year,month,date,hour,minute,0);
                   System.out.println("\nEnter Second Item's finishing bid time:\n");
                   String timeString1 = BiddingServer.keyboard.nextLine();
                   String hourString1 = timeString1.substring(0,2);
                   int hour1 = Integer.parseInt(hourString1);
                   String minString1 = timeString1.substring(3,5);
                   int minute1 = Integer.parseInt(minString1);
                   BiddingServer.deadlineTwo = Calendar.getInstance();//Set up Calendar object to hold deadline time...
                   BiddingServer.deadlineTwo.set(year,month,date,hour1,minute1,0);
                   System.out.println("Opening port...\n");
                   try
                        servSocket = new ServerSocket(PORT);
                   catch (IOException e)
                        System.out.println("\nUnable to set up port!");
                        System.exit(1);
              do
                   Socket client = servSocket.accept();
                   clientCount++;
                   //Wait for client.
                   System.out.println("\nNew bidder accepted.\n");
                   ClientHandler handler = new ClientHandler(client, clientCount);
                   handler.start();
              }while (true);
         class ClientHandler extends Thread
              private Socket client;
              private Scanner input, keyboard;
              private PrintWriter output;
              int clientNumber;
              public ClientHandler(Socket socket, int count) throws IOException
                   client = socket;
                   clientNumber = count;
                   keyboard = new Scanner(System.in);
                   input = new Scanner(client.getInputStream());
                   output = new PrintWriter(client.getOutputStream(),true);
              public void run()
                   String userInput;
                   float price, priceTwo ;
                   output.println(BiddingServer.itemDescripOne);
                   output.println(BiddingServer.itemCodeOne);
                   output.println(getDateTime(BiddingServer.deadlineOne));
                   output.println(BiddingServer.itemDescripTwo);
                   output.println(BiddingServer.itemCodeTwo);
                   output.println(getDateTime(BiddingServer.deadlineTwo));
                   do
                        userInput = input.nextLine();
                        Calendar now = Calendar.getInstance();
                        if (userInput.startsWith("number of bidders"))
                             System.out.println("Number of Bidders Online " + clientNumber);
                             output.println(clientNumber);
                        else if ((userInput.startsWith(BiddingServer.itemCodeOne)) && (userInput.endsWith("Status")))
                             System.out.println("item price one");
                             output.println(BiddingServer.itemPriceOne);
                        if ((userInput.startsWith(BiddingServer.itemCodeOne)) && (userInput.endsWith("Status")) && (now.after(BiddingServer.deadlineOne)))
                             System.out.println("-1, bidding for item ended");
                             output.println("-1");
                        else if (userInput.startsWith(BiddingServer.itemCodeOne))
                                  price = Float.parseFloat(userInput.substring(BiddingServer.itemCodeOne.length() +1));
                             if ((price > BiddingServer.itemPriceOne) && (now.before(BiddingServer.deadlineOne)))
                                  //bidForItem();
                                  System.out.println("Bid Accepted");
                                  output.println("Bid Accepted");
                                  BiddingServer.itemPriceOne = price;     
                             else if (now.after(BiddingServer.deadlineOne))
                                  System.out.println("Late Bid");
                                  output.println("Late Bid");
                             else if ((price <= BiddingServer.itemPriceOne) && (now.before(BiddingServer.deadlineOne)))
                                  System.out.println("Low Bid");
                                  output.println("Low Bid");
                        if ((userInput.startsWith(BiddingServer.itemCodeTwo)) && (userInput.endsWith("Status")))
                             System.out.println("item price one");
                             output.println(BiddingServer.itemPriceOne);
                        else if ((userInput.startsWith(BiddingServer.itemCodeTwo)) && (userInput.endsWith("Status")) && (now.after(BiddingServer.deadlineTwo)))
                             System.out.println("-1, bidding for item ended");
                             output.println("-1");
                        else if (userInput.startsWith(BiddingServer.itemCodeTwo))
                                  priceTwo = Float.parseFloat(userInput.substring(BiddingServer.itemCodeTwo.length() +1));
                                  if ((priceTwo > BiddingServer.itemPriceTwo) && (now.before(BiddingServer.deadlineTwo)))
                                       System.out.println("Bid Accepted");
                                       output.println("Bid Accepted");
                                       BiddingServer.itemPriceTwo = priceTwo;
                                  else if (now.after(BiddingServer.deadlineTwo))
                                       System.out.println("Late Bid");
                                       output.println("Late Bid");
                                  else if ((priceTwo <= BiddingServer.itemPriceTwo) && (now.before(BiddingServer.deadlineTwo)))
                                       System.out.println("Low Bid");
                                       output.println("Low Bid");
                   }while (true);
         public String getDateTime(Calendar dateTime)
              //Create DecimalFormat object to ensure 2 dec places...
              DecimalFormat decFormat = new DecimalFormat("00");
              //Now extract hours and minutes, each with 2 digits
              //(i.e., with leading zeroes if needed)...
              String hour2Digits =
                   decFormat.format(dateTime.get(Calendar.HOUR_OF_DAY));
              String min2Digits =
                   decFormat.format(dateTime.get(Calendar.MINUTE));
              return(dateTime.get(Calendar.DATE) + "/"
                        + (dateTime.get(Calendar.MONTH)+1) + "/"
                        + dateTime.get(Calendar.YEAR) + " "
                        + hour2Digits + ":" + min2Digits);
         }

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    public class BiddingClient extends JFrame implements ActionListener
         private InetAddress host;
         private final int PORT = 1234;
         private Socket link;
         private Scanner networkInput,keyboard;
         private PrintWriter output;
         private JPanel itemInfo, buttonPanel, comboPanel, headingPanel, selectItemPanel,personalPanel,biddingText;
         private JLabel label1,label2,label3, label4, label,label5, labelCode, labelDescrip,
         labelDeadline, labelPrice,bidStatus,label6,label7;
         private JComboBox itemSelection;
         private JButton bidButton, statusButton, noOfBiddersButton, quitButton;
         private JTextField bid;
         String [] code = new String [2];
         String [] desc = new String [2];
         String [] deadline = new String [2];
         public static void main(String[] args) throws IOException
              BiddingClient frame = new BiddingClient();
              frame = new BiddingClient();
              frame.setTitle("Welcome " + System.getProperty("user.name"));
              Dimension screenSize =
                   Toolkit.getDefaultToolkit().getScreenSize();
         int screenWidth = (int)screenSize.getWidth();
         int screenHeight = (int)screenSize.getHeight();
         int frameWidth=430 ,frameHeight=300;
         frame.setSize(frameWidth,frameHeight);
         frame.setLocation((screenWidth-frameWidth)/2,
                        (screenHeight-frameHeight)/2);
         frame.setVisible(true);
         frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
         public BiddingClient () throws IOException
              addWindowListener(
                        new WindowAdapter()
                             public void windowClosing(WindowEvent e)
                                  if (link != null)
                                  try
                                       link.close();
                                  catch (IOException ioEx)
                                       System.out.println(
                                            "\n*** Unable to close link!***\n");
                                       System.exit(1);
                                  System.exit(0);
              try
                   host = InetAddress.getLocalHost();
              catch(UnknownHostException uhEx)
                   System.out.println("\nHost ID not found!\n");
                   System.exit(1);
              personalPanel = new JPanel(new FlowLayout());
              setLayout(new BorderLayout());
              label6 = new JLabel("Welcome... " + System.getProperty("user.name"));
              label6.setFont (new Font("Edwardian Script ITC",Font.PLAIN,26));
              personalPanel.add(label6, BorderLayout.CENTER);
              personalPanel.setBackground(Color.lightGray);
              add(personalPanel, BorderLayout.NORTH);
              comboPanel = new JPanel(new BorderLayout());
              //comboPanel.setBorder(BorderFactory.createLineBorder(Color.red));
              itemSelection = new JComboBox();
              comboPanel.add(itemSelection, BorderLayout.EAST);
              itemSelection.addActionListener(this);
              add(comboPanel, BorderLayout.NORTH);
              selectItemPanel = new JPanel(new BorderLayout());
              label5 = new JLabel("Please Select An Item From The List:");
              selectItemPanel.add(label5, BorderLayout.CENTER);
              add(selectItemPanel, BorderLayout.WEST);
              headingPanel = new JPanel(new FlowLayout());
              String myText4 = "<HTML><b><u>Information On Item</b></u>";
              label = new JLabel(myText4);
              headingPanel.add(label);
              //headingPanel.setBorder(BorderFactory.createLineBorder(Color.white));
              add(headingPanel, BorderLayout.CENTER);
              comboPanel.add(headingPanel, BorderLayout.SOUTH);
              comboPanel.add(selectItemPanel, BorderLayout.WEST);
              comboPanel.add(personalPanel, BorderLayout.NORTH);
              itemInfo = new JPanel(new GridLayout(6,1));
              String myText = "<HTML><b><u>Description</b></u> : ";
              label1 = new JLabel(myText);
              itemInfo.add(label1);
              labelDescrip = new JLabel();
              labelDescrip.setFont (new Font("ComicSans",Font.PLAIN,12));
              itemInfo.add(labelDescrip);
              String myText1 = "<HTML><b><u>Code</b></u> : ";
              label2 = new JLabel(myText1);
              label2.setFont (new Font("Arial Narrow",Font.BOLD,13));
              itemInfo.add(label2);
              labelCode = new JLabel();
              labelCode.setFont (new Font("ComicSans",Font.PLAIN,12));
              itemInfo.add(labelCode);
              String myText2 = "<HTML><b><u>Deadline</b></u> : ";
              label3 = new JLabel(myText2);
              itemInfo.add(label3);
              labelDeadline = new JLabel();
              labelDeadline.setFont (new Font("ComicSans",Font.PLAIN,12));
              itemInfo.add(labelDeadline);
              String myText3 = "<HTML><b><u>Price</b></u> : ";
              label4 = new JLabel(myText3);
              itemInfo.add(label4);
              labelPrice = new JLabel("Click Status To View Price ");
              labelPrice.setFont (new Font("ComicSans",Font.PLAIN,12));
              itemInfo.add(labelPrice);
              bidStatus = new JLabel("");
              itemInfo.add(bidStatus);
              add(itemInfo, BorderLayout.CENTER);
              biddingText = new JPanel(new FlowLayout());
              bid = new JTextField("Enter Bid Here",10);
              bid.addActionListener(this);
              biddingText.add(bid);
              add(biddingText, BorderLayout.SOUTH);
              bidButton = new JButton("Place Bid");
              biddingText.add(bidButton);
              bidButton.addActionListener(this);
              statusButton = new JButton("Status");
              biddingText.add(statusButton);
              statusButton.addActionListener(this);
              noOfBiddersButton = new JButton("No. Of Bidders");
              biddingText.add(noOfBiddersButton);
              noOfBiddersButton.addActionListener(this);
              quitButton = new JButton("Quit");
              biddingText.add(quitButton);
              quitButton.addActionListener(this);
              add(biddingText, BorderLayout.SOUTH);
              link = new Socket(host, PORT);
              networkInput = new Scanner(link.getInputStream());
              output = new PrintWriter(link.getOutputStream(),true);
              keyboard = new Scanner(System.in);
              getItems();
              System.out.println("haha");
         public void getItems()
              for (int i = 0; i <2 ; i++)
                   desc[i] = networkInput.nextLine();
                   code[i] = networkInput.nextLine();
                   deadline[i] = networkInput.nextLine();
                   itemSelection.addItem(code);
         public void actionPerformed(ActionEvent e)
              if (e.getSource()== itemSelection)
              labelDescrip.setText(desc[itemSelection.getSelectedIndex()]);
              labelCode.setText(code[itemSelection.getSelectedIndex()]);
              labelDeadline.setText(deadline[itemSelection.getSelectedIndex()]);
              }else if ((e.getSource()== bidButton) || (e.getSource() == bid))
                   output.println(labelCode.getText() + " " + bid.getText());
                   JOptionPane.showMessageDialog(null,networkInput.nextLine());
                   //bidStatus.setText(networkInput.nextLine());
                   //System.out.println(bidStatus.getText());
              }else if (e.getSource()== statusButton)
                   output.println(labelCode.getText()+ "Status");
                   labelPrice.setText(networkInput.nextLine());
                   if (labelPrice.getText().equals("-1"))
                        labelPrice.setText("Bidding Time Is Up On This Item");
                   else
                        labelPrice.setVisible(true);
              }else if (e.getSource()== noOfBiddersButton)
                   output.println("number of bidders");
                   JOptionPane.showMessageDialog(null,"Number Of Bidders Online\n "+ networkInput.nextLine()
                                                      ,"Information", JOptionPane.INFORMATION_MESSAGE);
              }else if (e.getSource() == quitButton)
                   try
                        JOptionPane.showMessageDialog(this,"Closing down connection...",
                                  "Warning", JOptionPane.WARNING_MESSAGE);
                        System.out.println("*Connection Closed*");
                        link.close();
                        System.exit(0);
                   catch(IOException ioex)
                        System.out.println("***Disconnection problem!***");
                        System.exit(1);

  • Need help on with simple email program

    i have been set a task to create a simple email program that has the variables of the sender the recipient the subject the content and a date object representing when the email was sent (this is just to be set to the current system date)
    It also needs to include a constructor with four String arguments, i.e the sender, receiver, subject and content. The constructor has to initialise the date of the email then transfer the values of the input parameters to the relevant attributes. If any values of the strings aren'nt given, the string �Unknown� should be set as the value.
    I was given a java file to test the one i am to create, but some of the values are not given, if anyone could be of anyhelp or just point me in the right direction then i would be very greatfull, ive posted the code for the test file i have been given below, thanks.
    public class SimpleEmailTest {
         public static void main( String[] args ) {
              SimpleEmail email;     // email object to test.
              String whoFrom;          // sender
              String whoTo;          // recipient
              String subject;          // subject matter
              String content;          // text content of email
              static final String notKnown = "Unknown";
              email = new SimpleEmail
    (notKnown, notKnown, notKnown, notKnown);
              System.out.println( "SimpleEmail: " +
    "\n    From: " + email.getSender() +
    "\n      To: " + email.getRecipient() +
    "\n Subject: " + email.getSubject() +
    "\n    Date: " + 
    email.getDate().toString() +
    "\n Message: \n" + email.getContent() + "\n";
              email.setSender( "Jimmy Testsender");
              email.setRecipient( "Sheena Receiver");
              email.setSubject( "How are you today?");
              email.setContent( "I just wrote an email class!");
              System.out.println( "SimpleEmail: " +
    "\n    From: " + email.getSender() +
    "\n      To: " + email.getRecipient() +
    "\n Subject: " + email.getSubject() +
    "\n    Date: " + 
    email.getDate().toString() +
    "\n Message: \n" + email.getContent() + "\n";
         }

    Start by writing a class named SimpleEmail, implement a constructor with four arguments in it, and the methods that the test code calls, such as the get...() and set...() methods. The class probably needs four member variables too.
    public class SimpleEmail {
        // ... add member variables here
        // constructor
        public SimpleEmail(String whoFrom, String whoTo, String subject, String content) {
            // ... add code to the constructor here
        // ... add get...() and set...() methods here
    }

  • Problem with simple drawing program - please help!

    Hi,
    I've only just started using Java and would appreciate some help with a drawing tool application I'm currently trying to write.
    The problem is that when the user clicks on a button at the bottom of the frame, they are then supposed to be able to produce a square or circle by simply clicking on the canvas.
    Unfortunately, this is not currently happening.
    Please help!
    The code for both classes is as follows:
    1. DrawToolFrame Class:
    import java.awt.*;
    import java.awt.event.*;
    public class DrawToolFrame extends Frame
    implements WindowListener
    DrawToolCanvas myCanvas;
    public DrawToolFrame()
    setTitle("Draw Tool Frame");
    addWindowListener(this);
    Button square, circle;
    Panel myPanel = new Panel();
    square = new Button("square"); square.setActionCommand("square");
    circle = new Button("circle"); circle.setActionCommand("circle");
    myPanel.add(square); myPanel.add(circle);
    add("South", myPanel);
    DrawToolCanvas myCanvas = new DrawToolCanvas();
    add("Center", myCanvas);
    square.addMouseListener(myCanvas);
    circle.addMouseListener(myCanvas);
    public void windowClosing(WindowEvent event) { System.exit(0); }
    public void windowOpened(WindowEvent event) {}
    public void windowIconified(WindowEvent event) {}
    public void windowDeiconified(WindowEvent event) {}
    public void windowClosed(WindowEvent event) {}
    public void windowActivated(WindowEvent event) {}
    public void windowDeactivated(WindowEvent event) {}
    2. DrawToolCanvas Class:
    import java.awt.*;
    import java.awt.event.*;
    public class DrawToolCanvas
    extends Canvas
    implements MouseListener, ActionListener {
    String drawType="square";
    Point lastClickPoint=null;
    public void drawComponent(Graphics g) {
    if (lastClickPoint==null) {
    g.drawString("Click canvas first",20,20);
    } else {
    if (drawType.equals("square")) {
    square(g);
    else if (drawType.equals("circle")) {
    circle(g);
    public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals("square"))
    drawType="square";
    else if (event.getActionCommand().equals("circle"))
    drawType="circle";
    repaint();
    public void mouseReleased(MouseEvent e) {
    lastClickPoint=e.getPoint();
    public void square(Graphics g) {
    g.setColor(Color.red);
    g.fillRect(lastClickPoint.x, lastClickPoint.y, 40, 40);
    g.setColor(Color.black);
    public void circle(Graphics g) {
    g.setColor(Color.blue);
    g.fillOval(lastClickPoint.x, lastClickPoint.y, 40, 40);
    g.setColor(Color.black);
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {}
    Any help would be appreciated!

    Some of the problems:
    1) nothing calls drawComponent(Graphics g)
    2) Paint(Graphics g) has not been overriden
    3) myCanvas is declared twice: once as an instance variable to DrawToolFrame, and once local its constructor. Harmless but distracting.

  • Help with simple programming

    Hello everyone.
    First time posting, i hope someone would be able to help me out. There are 5 classes that i have to do, but i only need help with one of them. I've been stuck on this one pretty long and can't continue without it.
    Instructions:
    •     Has boolean data member face, either HEADS or TAILS.
    •     Has a Random data member flipper which is instantiated in the constructor.
    •     Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
    •     Method getFace() returns the face showing on the coin.
    •     void method flip() randomly selects HEADS or TAILS.
    package coinflip;
    import java.util.Random;
    * @author Blank
    public class Coin {
        boolean face = false;
        int flip_coin;
        Random flipper = new Random();
        int getFace() {
            return flip_coin;
          Coin() {
            if (flip_coin == 0) {
                face = true;
            } else {
                face = false;
        public void flip() {
            flip_coin = flipper.nextInt(2);
    }i really don't know why the random isn't working. I hope someone would be able to find my errors and instruct me on how to fix them. I would be able to continue the rest of the classes as soon as i got this figured out.
    Oh and can someone teach me how to import this class into a main one? So i can test it out. This is what i have for it.public class Main {
         * @param args the command line arguments
        public static void main(String[] args) {
         Coin flipCoin = new Coin();
         for(int i=0;i<6;i++){
         System.out.println(flipCoin.getFace());
    }Many Thanks!
    Edited by: Java_what on Feb 16, 2009 2:26 PM

    Constructors are only executed once. What im confused about is:
    • Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
    I thought i would flip() into the constructor. Mind helping me out on the whole class because it seems i am clueless about this whole class.
    Edit:
    public class Coin {
        boolean face = false;
        int flip_coin;
        Random flipper = new Random();
        int getFace() {
            flip();
            return flip_coin;
        Coin() {
           //flip();
        public void flip() {
            flip_coin = flipper.nextInt(2);
    }K i reread what you wrote about the constructor and method. So i placed flip() method in getFace(); because its being called in the main(it gives me random numbers). The problem now is following the directions.
    I just dont understand this description. • Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
    What do you think it means.
    Edited by: Java_what on Feb 16, 2009 4:14 PM

  • Need Help With D&D Program

    Hi, I'm not sure if I'm allowed to post questions on this forum but I can't find anywhere to talk to helpful people about programming.
    I'm making a dnd interface for JComponents. So far I've made a simple program that has a Component that can be lifted from a container and braught to the glass pane then later moved to anywhere on the screen and dropped into the container below it. Here's where my problems come:
    1) Rite now my 'Movable Component' is a JPanel which is just colored in. I want to either take a Graphic2d from a JComponent/Component and draw it on the JPanel or change the JPanel to the component I want to paint and disable the component.
    The problem with getting the Graphics2d is that if the component isn't on the screen it doesn't make a graphic object. I tried messing with the ui delicate and overriding parental methods for paintComponent, repaint, and that repaintChildren(forget name) but I haven't had luck getting a good graphics object. I was thinking of, at the beginning of running the program, putting 1 of each component onto the screen for a second then removing it but I'd rather not. I'd also like to change the graphics dynamicly if someone stretches the component there dropping and what not.
    The problem with disabling is that it changes some of the visual features of Components. I want to be able to update the Component myself to change how it looks and I don't want disabling to gray out components.
    I mainly just dont want the components to do any of there normal fuctions. This is for a page builder, by the way.
    Another problem I'm having is that mouseMotionListener is allowing me to select 2 components that are on top of one another when there edges are near each other. I don't know if theres a fix to this other than changing the Java Class.
    My next problem is a drop layout manager, but I'm doing pretty good with that rite now. It'll problem just move components out of the way of the falling component.
    One last thing I need help with is that I don't want the object that's being carried to go across the menu bar and certain areas. When I'm having the object being carried I have it braught up to the glass pane which allows it to move anywhere. Does anyone have any idea how I could prevent the component from being over the menu bars and other objects? I might have to make 1 panel is the movable area that can then be broken down into the 'component bank', 'building page' and whatever else I'm gonna need.
    This is all just test code to get together for when I make the real program but I need to make sure it'll be possible without a lot of hacking of code.
    Sorry for the length. Thanks for any help you can give.

    The trick to making viewable components that have no behaviour, is to render them onto an image of some sort (eg a BufferedImage). You can then display the Image on a JLabel that can be dragged around the desktop.
    Here is a piece of code that does the component rendering for you. This particular example uses a fixed component size, but you can modify that as you choose of course...public class JComponentImage
         private static GraphicsConfiguration gConfig;
         private static Dimension compSize = new Dimension(80, 22);
         private static Image image = null;
         public static Image getImage(Class objectClass)
              if (gConfig == null)
                   GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
                   GraphicsDevice gDevice = gEnv.getDefaultScreenDevice();
                   gConfig = gDevice.getDefaultConfiguration();
              image = gConfig.createCompatibleImage(compSize.width, compSize.height);
              JComponent jc = (JComponent) ObjectFactory.instantiate(objectClass);
              jc.setSize(compSize);
              Graphics g = image.getGraphics();
              g.setColor(Color.LIGHT_GRAY);
              g.fillRect(0, 0, compSize.width, compSize.height);
              g.setColor(Color.BLACK);
              jc.paint(g);
              return image;
    }And here is the class that makes the dragable JLabel using the class above...public class Dragable extends JLabel
         private static DragSource dragSource = DragSource.getDefaultDragSource();
         private static DragGestureListener dgl = new DragMoveGestureListener();
         private static TransferHandler th = new ObjectTransferHandler();
         private Class compClass;
         private Image image;
         Dragable(Class compClass)
              this.compClass = compClass;
              image = JComponentImage.getImage(compClass);
              setIcon(new ImageIcon(image));
              setTransferHandler(th);
              dragSource.createDefaultDragGestureRecognizer(this,
                                                          DnDConstants.ACTION_COPY,
                                                          dgl);
         public Class getCompClass()
              return compClass;
    }Oh and here is ObjectFactory which simply instantiates Objects of a given class and sets their text to their classname (very crudely)...public class ObjectFactory
         public static Object instantiate(Class objectClass)
              Object o = null;
              try
                   o = objectClass.newInstance();
              catch (Exception e)
                   System.out.println("ObjectFactory#instantiate: " + e);
              String name = objectClass.getName();
              int lastDot = name.lastIndexOf('.');
              name = name.substring(lastDot + 1);
              if (o instanceof JLabel)
                   ((JLabel)o).setText(name);
              if (o instanceof JButton)
                   ((JButton)o).setText(name);
              if (o instanceof JTextComponent)
                   ((JTextComponent)o).setText(name);
              return o;
    }Two more classes required by this codepublic class ObjectTransferHandler extends TransferHandler {
         private static DataFlavor df;
          * Constructor for ObjectTransferHandler.
         public ObjectTransferHandler() {
              super();
              try {
                   df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
              } catch (ClassNotFoundException e) {
                   Debug.trace(e.toString());
         public Transferable createTransferable(JComponent jC) {
              Transferable t = null;
              try {
                   t = new ObjectTransferable(((Dragable) jC).getCompClass());
              } catch (Exception e) {
                   Debug.trace(e.toString());
              return t;
         public int getSourceActions(JComponent c) {
              return DnDConstants.ACTION_MOVE;
         public boolean canImport(JComponent comp, DataFlavor[] flavors) {
              if (!(comp instanceof Dragable) && flavors[0].equals(df))
                   return true;
              return false;
         public boolean importData(JComponent comp, Transferable t) {
              JComponent c = null;
              try {
                   c = (JComponent) t.getTransferData(df);
              } catch (Exception e) {
                   Debug.trace(e.toString());
              comp.add(c);
              comp.validate();
              return true;
    public class ObjectTransferable implements Transferable {
         private static DataFlavor df = null;
         private Class objectClass;
         ObjectTransferable(Class objectClass) {
              try {
                   df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
              } catch (ClassNotFoundException e) {
                   System.out.println("ObjectTransferable: " + e);
              this.objectClass = objectClass;
          * @see java.awt.datatransfer.Transferable#getTransferDataFlavors()
         public DataFlavor[] getTransferDataFlavors() {
              return new DataFlavor[] { df };
          * @see java.awt.datatransfer.Transferable#isDataFlavorSupported(DataFlavor)
         public boolean isDataFlavorSupported(DataFlavor testDF) {
              return testDF.equals(df);
          * @see java.awt.datatransfer.Transferable#getTransferData(DataFlavor)
         public Object getTransferData(DataFlavor arg0)
              throws UnsupportedFlavorException, IOException {
              return ObjectFactory.instantiate(objectClass);
    }And of course the test class:public class DragAndDropTest extends JFrame
         JPanel leftPanel = new JPanel();
         JPanel rightPanel = new JPanel();
         Container contentPane = getContentPane();
         Dragable dragableJLabel;
         Dragable dragableJButton;
         Dragable dragableJTextField;
         Dragable dragableJTextArea;
          * Constructor DragAndDropTest.
          * @param title
         public DragAndDropTest(String title)
              super(title);
              dragableJLabel = new Dragable(JLabel.class);
              dragableJButton = new Dragable(JButton.class);
              dragableJTextField = new Dragable(JTextField.class);
              dragableJTextArea = new Dragable(JTextArea.class);
              leftPanel.setBorder(new EtchedBorder());
              BoxLayout boxLay = new BoxLayout(leftPanel, BoxLayout.Y_AXIS);
              leftPanel.setLayout(boxLay);
              leftPanel.add(dragableJLabel);
              leftPanel.add(dragableJButton);
              leftPanel.add(dragableJTextField);
              leftPanel.add(dragableJTextArea);
              rightPanel.setPreferredSize(new Dimension(500,500));
              rightPanel.setBorder(new EtchedBorder());
              rightPanel.setTransferHandler(new ObjectTransferHandler());
              contentPane.setLayout(new BorderLayout());
              contentPane.add(leftPanel, "West");
              contentPane.add(rightPanel, "Center");
         public static void main(String[] args)
              JFrame frame = new DragAndDropTest("Drag and Drop Test");
              frame.pack();
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setVisible(true);
    }I wrote this code some time ago, so it won't be perfect but hopefully will give you some good ideas.
    Regards,
    Tim

  • Problem with simple label program

    I'm getting a problem to a most basic program. I'm using the Java2 Fast And Easy Web Start book. This simple label program gives me an error when I compile. This is the program
    //Label Program
    //Danon Knox
    //Another basic program
    import java.awt.*;
    import java.applet.*;
    public class Label extends Applet{
      public void init(){
       Label firstlabel = new Label();
       Label secondlabel = new Label("This is the second label");
    //put the labels on the applet
      add(firstlabel);
      add(secondlabel);
    }// end init
    }// end appleterror when I compile is as follows:
    Microsoft Windows XP [Version 5.1.2600]
    (C) Copyright 1985-2001 Microsoft Corp.
    C:\>cd java
    C:\java>javac Label.java
    Label.java:12: cannot resolve symbol
    symbol : constructor Label (java.lang.String)
    location: class Label
    Label secondlabel = new Label("This is the second label");
    ^
    1 error
    C:\java>
    Can anyone help me?

    public class Label extends Applet{The name of your class is "Label". This choice of name hides the class named "Label" in java.awt.
    Label firstlabel = new Label();This creation of a Label is successful because the class has a default, no-argument constructor.
    Label secondlabel = new Label("This is the second label");And this one fails because there is no constructor for Label that takes a String argument.
    You probably want firstlabel and secondlabel to be java.awt.Label objects and not instances of your own Label class. Try this:
    public class Label extends java.applet.Applet{
        public void init(){
         java.awt.Label firstlabel = new java.awt.Label();
         java.awt.Label secondlabel =
             new java.awt.Label("This is the second label");
         add(firstlabel);
         add(secondlabel);
    }As a general remark, I advise programmers to stay away from
    import a.b.*;statements which import entire packages into your program namespace.
    When starting out, I believe it is better to write out the fully qualified names ot the classes and methods you are working with. This helps you learn the class hierarchy, and makes your code clearer.
    Others will disagree, but that's my opinion...

  • Beginner needs help with simple code.

    I just statrted learnind java, and I need some help with this simple program. For some reason everytime I enter my Farenheit value, the Celsius conversion returns as 0.0. Would really appreciate the help. Thanks.
    Here's the code:
    public class TempConverter
    public static void main(String[] args)
    double F = Double.parseDouble(args[0]);
    System.out.println("Temperature in Farenheit is: " + F);
    double C = 5 / 9;
    C *= (F - 32);
    System.out.println("Temperature in Celsius is: " + C);
    }

    double C = 5 / 9This considers "5" and "9" to be integers and does an integer division, discarding the remainder. The result of that division is 0. Trydouble C = 5.0/9.0;

  • Need help with my addressbook program

    hi,
    i need help with my program here. this one should works as:
    - saves user input into a txt file
    - displays name of the saved person on the jlist whenever i run the program
    - displays info about the person when clicked via textboxes given by reading the txt file where the user inputs are
    - should scroll when the list exceeds the listbox
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JList;
    import java.awt.event.ActionListener;
    import java.io.*;
    import javax.swing.event.*;
    import java.io.FilterInputStream;
    public class AddressList extends JPanel implements ActionListener
         JTextField txt1 = new JTextField();
         JTextField txt2 = new JTextField();
         JTextField txt3 = new JTextField();
         DefaultListModel mdl = new DefaultListModel();
         JList list = new JList();
         JScrollPane listScroller = new JScrollPane(list);
         ListSelectionModel listSelectionModel;
         File fob = new File("Address3.txt");
         String name;
         char[] chars;     
         public void ListDisplay()
              try
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
                   if(fob.exists())
                         while((name = rand.readLine()) != null)
                              chars = name.toCharArray();
                              if(chars[0] == '*')
                                   mdl.addElement(name);
                                   list.setModel(mdl);
                              if(chars[0] == '#')
                                   continue;
                    else
                        System.out.println("No such file..");
              catch(IOException a)
                         System.out.println(a.getMessage());
         public AddressList()
              this.setLayout(null);
              listSelectionModel = list.getSelectionModel();
            listSelectionModel.addListSelectionListener(new ListInfo());
              list.setBounds(10,40,330,270);
              listScroller.setBounds(320,40,20,100);
              add(list);
              add(listScroller);
              JLabel lbl4 = new JLabel("Name: ");
              lbl4.setBounds(400,10,80,30);
              add(lbl4);
              JLabel lbl5 = new JLabel("Cellphone #: ");
              lbl5.setBounds(400,50,80,30);
              add(lbl5);
              JLabel lbl6 = new JLabel("Address: ");
              lbl6.setBounds(400,90,80,30);
              add(lbl6);
              JLabel lbl7 = new JLabel("List ");
              lbl7.setBounds(10,10,100,30);
              add(lbl7);
              txt1.setBounds(480,10,200,30);
              add(txt1);
              txt2.setBounds(480,50,200,30);
              add(txt2);
              txt3.setBounds(480,90,200,30);
              add(txt3);
              JButton btn1 = new JButton("Add");
              btn1.setBounds(480,130,100,30);
              btn1.addActionListener(this);
              btn1.setActionCommand("Add");
              add(btn1);
              JButton btn2 = new JButton("Save");
              btn2.setBounds(480,170,100,30);
              btn2.addActionListener(this);
              btn2.setActionCommand("Save");
              add(btn2);
              JButton btn3 = new JButton("Cancel");
              btn3.setBounds(480,210,100,30);
              btn3.addActionListener(this);
              btn3.setActionCommand("Cancel");
              add(btn3);
              JButton btn4 = new JButton("Close");
              btn4.setBounds(480,250,100,30);
              btn4.addActionListener(this);
              btn4.setActionCommand("Close");
              add(btn4);
         public static void main(String[]args)
              JFrame frm = new JFrame("Address List");
              AddressList panel = new AddressList();
              frm.getContentPane().add(panel,"Center");
              frm.setSize(700,350);
              frm.setVisible(true);
              panel.ListDisplay();
         public void actionPerformed(ActionEvent e)
              String cmd;
              cmd = e.getActionCommand();
              if(cmd.equals("Add"))
                   txt1.setText("");
                   txt2.setText("");
                   txt3.setText("");
              else if(cmd.equals("Save"))
                   mdl.addElement(txt1.getText());
                   list.setModel(mdl);
                   try
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                   LineNumberReader line = new LineNumberReader(br);
                    if(fob.exists())
                              rand.seek(fob.length());
                              rand.writeBytes("* " + txt1.getText());
                              rand.writeBytes("\r\n" + "# " + txt2.getText());
                              rand.writeBytes("\r\n" + "# " + txt3.getText() + "\r\n");
                    else
                         System.out.println("No such file..");
                        txt1.setText("");
                        txt2.setText("");
                        txt3.setText("");
                    catch(IOException a)
                         System.out.println(a.getMessage());
              else if(cmd.equals("Cancel"))
                   txt1.setText("");
                   txt2.setText("");
                   txt3.setText("");
              else if(cmd.equals("Close"))
                   System.exit(0);
    class ListInfo implements ListSelectionListener
         public void valueChanged(ListSelectionEvent e)
              ListSelectionModel lsm = (ListSelectionModel)e.getSource();
              int minIndex = lsm.getMinSelectionIndex();
            int maxIndex = lsm.getMaxSelectionIndex();
              try //*this one should display the info of the person whenever i click the person's name at the list box via textbox.. but i cant seem to get it right since it always display the info of the first person inputed.. i tried to get the program to display them whenever it reads lines with * on them....
                   File fob = new File("Address3.txt");
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
                   LineNumberReader line = new LineNumberReader(br);
                   if(fob.exists())
                              for(int i = minIndex; i<=maxIndex; i++)
                                   if(lsm.isSelectedIndex(i))
                                        while((name = rand.readLine()) != null)
                                             chars = name.toCharArray();
                                             if(chars[0] == '#')
                                                  continue;
                                             if(chars[0] == '*')
                                                  txt1.setText(rand.readLine());
                                                 txt2.setText(rand.readLine());
                                                 txt3.setText(rand.readLine());
                    else
                              System.out.println("No such file..");
              catch(IOException a)
                         System.out.println(a.getMessage());
    }the only problem now is about how it should display the right info about the person whenever i click its name on the list.. something about file reading or something, i just cant figure it out.
    and also about how to make it scroll once it exceeds the list.. i cant make it work, maybe something about wrong declaration..
    thanks in advance..
    Edited by: syder on Mar 14, 2008 2:26 AM

    Like said before, do one thing at a time. At startup, something like:
    //put all the content in a list
    ArrayList<String> lines = new ArrayList<String>();
    while(String line=rand.readLine()!=null) {
        lines.add(line);
    }If you follow the good advice to create a class to encapsulate the entries, you could populate a list of such entries like this:
    static final int ENTRY_SIZE = 3;//you have 3 fields now, better to have a constant if that changes
    ArrayList<Entry> entries = new ArrayList<Entry>();
    for(int i=0; i<lines.size(); i+=ENTRY_SIZE) {
        Entry entry = new Entry(lines.get(i), lines.get(i+1), lines.get(i+2);
        entries.add(newEntry);
    }You could also do both of the above in one run, but I think you will understand better what's happening if you do one thing at a time.
    If you don't want to put the entries in an encapsulating class, you can still access this without looping:
    int listStartIdx = <desired_entry_index>*ENTRY_SIZE;
    String att1 = lines.get(listStartIdx).substring(1);
    String att2 = lines.get(listStartIdx+1).substring(1);
    String att3 = lines.get(listStartIdx+2).substring(1);

  • Help with a java program

    Hello. I'm posting in these forums because I really don't know where else to go. I have been trying for the past several days to figure out how to go about writing my program but to no avail. The project requires reading many lines each containing several different elements from a datafile named "DATA". A few examples of some lines from that file:
    Department number/Number of units received/Date on which the shipment arrived/Expiration date/Name of Object
    0 78 02/03/2001 02/12/2001 apples
    0 26 06/03/2001 06/10/2001 lemons
    3 62 03/06/2001 03/14/2001 hamburger
    What we have to do with this data is read all of it from the file, separate all the different elements, and based on input from the user, sort everything and print it out to the screen. If the user enters 03, the program will show everything that arrived and expired within the month of March, sorted by date.
    It is a pretty basic program, but my problem is that I have no idea how to go about reading in this data, putting it into a vector (probably the easiest method) or separating the different elements. I've gone to websites and looked through my textbooks but they didn't help much. If anyone has any resources that could help for writing such a program, or if anyone could offer help in writing the program, I would really appreciate it. I can also show what I've managed to write so far, or more details on how the program should work. Thanks in advance.
    Matt

    since im not a pro like some of the guys on here :),
    and believe me thiers people here, who could write your whole app in a hour.
    anyways my advice , would be to do a search on the forums for useing.bufferReader()
    i think you would need to read the file in with bufferreader then split up each line useing the stringTokenizer and then use some algorithm to compare
    the values and split them up into your vector arrays as needed.
    thier is also fileinputStream i think you can use that too.

  • Need help with a rudimentary program

    I'm sort of new at this so i need help with a few things... I'm making a program to compile wages and i need answers with three things: a.) what are the error messages im getting meaning? b.) How can i calculate the state tax as 2% of my gross pay with the first $200 excluded and c.) how can i calculate the local tax as a flat $10 with $2 deducted for each dependant. any help is appreciated
    Here is what i have so far:
    public class WagesAsign1
              public static void main(String[] args)
                   int depend=4;
                   double hrsWork=40;
                   double payRate=15;
                   double grossPay;
                   grossPay=payRate*hrsWork;
                   double statePaid;
                   double stateTax=2.0;
                   statePaid=grossPay*(stateTax/100);
                   double localPaid;
                   double localTax=10.0;
                   localPaid=grossPay*(localTax/100);
                   double fedPaid;
                   double fedTax=10.0;
                   double taxIncome;
                   fedPaid=taxIncome*(fedTax/100);
                   taxIncome=grossPay-(statePaid+localPaid);
                   double takeHome;
                   System.out.println("Assignment 1 Matt Foraker\n");
                   System.out.println("Hours worked="+hrsWork+" Pay rate $"+payRate+" per/hour dependants: "+depend);
                   System.out.println("Gross Pay $"+grossPay+"\nState tax paid $"+statePaid+"\nLocal tax paid $"+localPaid+"\nFederal tax paid $"+fedPaid);
                   System.out.println("You take home a total of $"+takeHome);
    and these are the error messages so far:
    WagesAsign1.java:23: variable taxIncome might not have been initialized
                   fedPaid=taxIncome*(fedTax/100);
    ^
    WagesAsign1.java:29: variable takeHome might not have been initialized
                   System.out.println("You take home a total of $"+takeHome);
    ^

    edit: figured it out... please delete post
    Message was edited by:
    afroryan58

Maybe you are looking for

  • Sharing an apple ID and downloading apps. HELP!!!

    My husband and I used to share one apple ID and all apps downloaded onto the same computer through that ID. We did share some of the apps but he downloaded some and I downloaded others. Now we both have out own apple ID's but I cant seem to get any u

  • Parental controls in iTunes don't work for TV Shows?

    Using parental controls - i can hide/block Movies & explict music content - but doesn't appear to work for TV Shows marked "Caution" - any ideas? Help would be appreciated. thanks       

  • ISight resolution in iChat

    Have just got my new iMac and done my first video Chat. I was surprised by the low resolution. iChat 5 displays the resolution in Connection Doctor, and I only got 176 x 144 in and out, although I have a very fast cable modem connection. The picture

  • Urgent Hepl Needed: Unable to start Control Center Service OWB 10gR2

    Hi everybody, we moved our test owb instance to a new server. Today i wanted to start the Control Center Service from sqlplus with the start_service.sql Now i am getting the following error: service startup failure using command "/ora/app/oracle/prod

  • Only 4x5 prints from Lightroom

    I'm running Lightroom 2.4 with Mac OS 10.5.7.  When I try to print a photo full-size or in several sizes using the contact sheet or picture package templates, I get a beautifully done print in 4x5 size, i.e. on one quarter of the page.  If I export t