Java newbie help: Need to change a graphic on screen

Hello everyone. I'm a long time C/C++ programmer, and I've been thrust into the Java world when I inherited an incomplete project. If something I mention later on sounds stupid, it's probably because it came that way, or I'm trying to force it into what I know from old experience.
FWIW, the project is being developed with Netbeans.
What I'm after is how to change a graphic object onscreen from within the code, vs. with a device such as a mouse. I'm trying to emulate an LED indicator.
What I've done so far is to try using the enable state, and defining GIFs to display. That didn't work.
I've switched gears a bit, and tried something similar with the selected property, but that will only work if I hit the item with my mouse and click. Also, the item is defined as a jToggleButton.
In general terms, what do I need to do to set this up for the displayed item to change without device input? I've been reading stuff about Buttons, ToggleButtons, Graphics, Images, and Icons, and I'm waaaaaay lost right now.
To add to the frustration is that I've done something similar with Visual C++, and that worked as intended. Harumph.
Help?!?

FWIW, the project is being developed with Netbeans.
In case you don't know, you can use any editor to develop java code.
What I'm after is how to change a graphic object onscreen from within the code, vs. with a device such as a mouse. I'm trying to emulate an LED indicator.
What I've done so far is to try using the enable state, and defining GIFs to display. That didn't work.
What happend?
I've switched gears a bit, and tried something similar with the selected property, but that will only work if I hit the item with my mouse and click. Also, the item is defined as a jToggleButton.
Is this not what you wanted?

Similar Messages

  • Java newbie help (type casting, 64bit unsigned Long)

    Hi I am java newbie and need help on my project. I have a few questions. Can you put strings in a hashtable and test for their being their with the appropriate hashtable method? I want to test for equal strings, not the same object. Second question can you use all 64 bits of an unsigned long? java doesn't seem to allow this. Any packages that do?
    Thanks,
    Dave

    Try casting it to Long instead of long. Long (capital L) is an Object, while long (lower case l) is not. You may also check to make sure the value isn't null. I would have thought that autoboxing would have worked here unless the value was null. But I am no expert on autoboxing.
    Edit >> Checking for null ain't a bad idea but has nothing to do with the problem - this is a compile time problem. Sorry.
    Also>> This code should work:
    long cTime=(Long)session.getAttribute("creationtime");Edited by: stevejluke on Jul 1, 2008 11:00 AM

  • Help needed regarding change of system CLASSPATH

    Hi All,
    I need to change the system CLASSPATH using my java programe. I tried the following code but its not working though it returns the correct CLASSPATH, but unable to do the modification. All I need is to append a new jar file in the existing CLASSPATH..
    code]
    try{
              sysMap = System.getenv();
              }catch(Exception se1){
                        System.out.println("Exception in finding Environment properties");
              Set Keys = sysMap.keySet();
              Iterator It = Keys.iterator();
              while(It.hasNext()){
                   String strNow =(String) It.next();
                   if(strNow.contains("CLASSPATH")){
                        System.setProperty("CLASSPATH", ".;C:\\Calypso\\Software\\\\Release\\jars\\calypso.jar;C:\\Calypso\\Software\\Release\\build;C:\\Calypso\\Software\\Release\\build\\calypsofx;C:\\Calypso\\Software\\Release\\resources;C:\\Calypso\\Software\\Release;C:\\Calypso\\Software\\Release\\jars\\jconn2.jar;C:\\Calypso\\Software\\Release\\jars\\jaxb-1.0.4\\;C:\\Calypso\\Software\\Release\\jars\\javacup.jar;C:\\Calypso\\Software\\Release\\jars\\antlr.jar;C:\\Calypso\\Software\\Release\\jars\\ojdbc14.zip;C:\\Calypso\\Software\\Release\\jars\\web\\servlet.jar;C:\\Calypso\\Software\\Release\\jars\\web\\webserver.jar;C:\\Calypso\\Software\\Release\\jars\\ftp.jar;C:\\Calypso\\Software\\Release\\jars\\itext-1.02b.jar;C:\\Calypso\\Software\\Release\\jars\\Jama-1.0.1.jar;C:\\jdk1.5.0_10\\bin;C:\\Calypso\\Software\\Release\\webfx\\calypsoWebFXServer.jar;C:\\XXX.jar");
                        System.out.println("Classpath changed");
    Any help will be appreciated.

    Hi Kaj ,
    Well I am in a situation where we need to extend a
    existing system and we are providing the client with
    a new jar file for every modification. Now all I need
    is that our programe automatically add (infect
    append) the jar file in the existing system
    CLASSPATH, so that the client need not to add(append)
    the new jar files all the time.
    Can you provide any help??As others have said, use -cp as argument when you start your application. It's quite common that people write a script that adds all jars in a certain directory to the argument to -cp.
    Kaj

  • Help needed for changing MATERIAL SALES TEXT

    We have a requirement where in i need to chang the existing material sales text. GOTO --> ITEM --> TEXT --> Material Sales text. iwould like to know if it would be possible to do it using a CATT program?? If yes any pointers if no what would be the best approach for this.

    You can also use a LSMW.
    You are lucky, this is exactly the eg taken in SAP help :
    http://help.sap.com/saphelp_erp2005/helpdata/en/e1/c6d30210e6cf4eac7b054a73f8fb1d/frameset.htm
    Hope this helps,
    Erwan

  • J2ME to personal Java, how much need to change

    I have an appilication that is written in J2ME. Now i'd like to experiment how it runs on PersonalJava devices, such as Nokia Communicator.
    How much I need to change. The app is small pop-mail program, that fetches emails from my mail server. It uses HttpConnection. The Gui is build with few Form.
    Am I right when I assume that just the GUI parts have to be re-written (using AWT), mostly all the rest works. If I compile existing code with Jdk 1.1, are the errors I get the changes I need to do... Or is there something else too ?
    Thanks in advance,
    P_trig

    The Idea was not to test the app on Desktop, but to convert it to PersonalJava and I wondered how much there is to change before J2ME app runs in PersonalJave Device.
    My app runs fine, I know that already, but I need to make another version of it for PersonalJava. IE, which elements of current versions have to be rewritten, that's my question, not how to emulate J2ME on desktop.
    Thanks,
    P_trig

  • Need to change the bios splash screen..

     im using lenovo B460e notebook .
    i want to change the bios splash screen..
    so pls anyone help me out.
    my biosbrand is LENOVO and its version is:4FCNA1WW

    You may check if you get the option in installed BIOS itself otherwise kindly do not try.
    Best Regards,
    Tanuj
    Did someone help you today? Press the star on the left to thank them with a Kudo!
    If you find a post helpful and it answers your question, please mark it as an "Accepted Solution".! This will help the rest of the Community with similar issues identify the verified solution and benefit from it.
    Follow @LenovoForums on Twitter!

  • Newbie help needed w/Graphics class!

    Hi everyone,
    I'm stuck on something I know is very simple to do, but I can't seem to find the right combination. I have a derived class that draws a circle using the graphics class. I'm getting compilation errors when I try to set the color and draw the circle. I have looked thru these forums as well as the API. Below is my code. Any pointers would be highly appreciated!
    import java.awt.Graphics;
    public class SmartCircle extends SmartShape
    SmartCircle(int first, int second, int third, Color c)
    super(first, second, third, c);
    public void draw(Graphics g)
    setColor(Color c);
    fillOval(first, second, size, size);
    }

    Here is SmartShape. It is located in the same directory as SmartCircle, so therefore doesn't need to be imported, correct?
    public abstract class SmartShape
    //define instance variables
    protected int positionX, positionY, size;
    protected Color theColor;
    public SmartShape()
         //initialize variables
         positionX = 20;
         positionY = 20;
         theColor = Color.white;
    public SmartShape(int first, int second, int third, Color c)
         if (first >= 0)
         positionX = first;
         else
         positionX = 0;
         if (second >= 0)
         positionY = second;
         else
         positionY = 0;
         if (third >= 0)
         size = third;
         else
         size = 0;
         theColor = c;
    public abstract void draw(Graphics g);
    Hope that helps!
    Melissa

  • Pricing : ABAP to Java conversion help needed

    Hi all.
    I am basically an ABAP developer. My recent assignment needs some java coding.
    It will be very helpful if we anybody helps me in finding the corresponding pricing fields in java.
    The abap code is as follows
    check : xkomv - kgrpe  = '  '.
    check: xkomv - xkbetr ne 0.
    check : komp - kpein ne 0.
    if komp - netwr < 0.
      komp - netpr = 0 - komp - netpr.
    endif.
    xkwert  = (        (  ( komp - netpr * ( 100000 + xkomv - xkbetr))     / 100000)
    komp-mglme / komp-kumza * komp - kumne / 1000 / komp - kpein )
      - komp-netwr.
    Please help in converting this abap code to its corresponding java code.
    Thanks and Regards
    Deepika

    Here is the code I have developed: Please check and let me know if there are any changes
    import java.math.BigDecimal;
    import com.sap.spe.pricing.customizing.PricingCustomizingConstants;
    import com.sap.spe.pricing.transactiondata.PricingTransactiondataConstants;
    import com.sap.spe.pricing.transactiondata.userexit.IPricingConditionUserExit;
    import com.sap.spe.pricing.transactiondata.userexit.IPricingItemUserExit;
    import com.sap.spe.pricing.transactiondata.userexit.ValueFormulaAdapter;
    public class ZS2S_IPC_ZDCP extends ValueFormulaAdapter {
          public BigDecimal overwriteConditionValue(
                IPricingItemUserExit item,
                IPricingConditionUserExit condition) {
                BigDecimal kompKumza = new BigDecimal(String.valueOf(condition.getFraction().getNumerator()));
                BigDecimal kompKumne = new BigDecimal(String.valueOf(condition.getFraction().getDenominator()));
                boolean xkomvKgrpe = condition.isGroupCondition();
                BigDecimal kompKpein = condition.getPricingUnit().getValue();    
                BigDecimal kompNetwr  = item.getNetValue().getValue();
                BigDecimal kompNetpr  = item.getNetPrice().getValue();
                BigDecimal xkomvKbetr = condition.getConditionRate().getValue();
                BigDecimal kompMglme = item.getBaseQuantity().getValue();
                  if ( xkomvKgrpe = true )
                      return PricingTransactiondataConstants.ZERO;
                  if ( kompKumza != PricingTransactiondataConstants.ZERO )
                    return PricingTransactiondataConstants.ZERO;
                if ( kompKumne != PricingTransactiondataConstants.ZERO )
                      return PricingTransactiondataConstants.ZERO;   
                if ( kompKpein != PricingTransactiondataConstants.ZERO )
                        return PricingTransactiondataConstants.ZERO;
                if (kompNetwr.compareTo(PricingTransactiondataConstants.ZERO) < 0 )
                      kompNetpr = (PricingTransactiondataConstants.ZERO).subtract(kompNetwr);
                 BigDecimal y = new BigDecimal("100000");
                BigDecimal a = y.add(xkomvKbetr);
                BigDecimal temp = kompNetpr.multiply(a);
                BigDecimal result1 = temp.divide(y, 2, BigDecimal.ROUND_HALF_UP);
                BigDecimal result2 = result1.multiply(kompMglme)
                                         .divide(kompKumza, 2 BigDecimal.ROUND_HALF_UP).multiply(kompKumne).divide(kompKpein, 2,  BigDecimal.ROUND_HALF_UP);
                BigDecimal Result = result2.subtract(kompNetwr);
              return Result;
    Edited by: Deepika Mallya on Aug 6, 2009 9:08 AM

  • Java Progrramming HELP, Needed Urgently, T hanks

    hey guys,
    I have this lab I need to be done tomorrow, its been weeks lol of thinking and figuring things out can someone make it work ? Pleaseeeee !
    I feel like going out and yelling for help lol I have been trying to figure this out for weeks now.
    I am pasting my Lab and My Codes I did so far, And Please I really need this done today at any rate, all help would be kindly appreciated.
    A Java program is required that will produce a number of reports based on the data from the Product file. This file contains the product name, cost, quantity and UPC. The file name must be input. Valid data from the file will be loaded into an array.
    A menu will provide the following options: (Note there are changes from previous assignment.)
    1     Display of all valid product information including extended price and GST including totals sorted by name.
    2     Display of all invalid records sorted by name.
    3     Search and display a certain product by name.
    4     Sort by UPC and use a binary search and display a certain product by UPC. (valid records)
    9 Exit.
    Processing requirements:
    Input the data from a file and load the records into an object array. Use this object array to produce the above reports.
    Code a class definition exactly as given in the following UML.
    (For specific students: you may code the UPC as an integer but if not numeric throw an exception that is handled in main. Document your choice in your submission).
    Product
    ? Name : String
    ? UPC : String
    ? Cost : Real
    ? Quantity : Integer
    + Product (Name : String, UPC : String, Cost : Real, Quantity : Integer)
    + Calculate Extended Cost() : Real
    + Calculate GST(): Real
    Input Record:
    Product name: String
    UPC: String
    Cost: real
    Quantity: integer
    Output Reports
    1. Display of all product information including extended cost and GST including totals of these 3 fields.
    Following is a sample of the output required:
    ************************ Product Cost REPORT ****************************
    Product                    Cost Quantity Extended Cost     GST     Total Cost
    Diamond Necklace 12345678901x 54,321.99 188 10,212,534.12 510,626.71 10,723,160.83
    Tissues 98989898989x 1.99 2 3.98      0.20     4.18
    TOTALS                         10,212,538.10 510,626.91 10,723,165.01
    2. Display of all invalid records and the count.
    Following is a sample of the output required:
    Invalid UPC Records = 1
    Count Record
    1          Tiara Diamond, 12345678901x, 36020.00, 2
    3. Search and display a certain product by name. Display appropriate message if not found.
    Following is a sample of the output required:
    Enter product name: CrownJewels
    CrownJewels 99999999991x     100,000.00 1 100,000.00 5,000.00 $105,000.00
    6. Display the product information sorted by name
    Following is a sample of the output required:
    ************************ Product Cost REPORT ****************************
    Product                    Cost Quantity Extended Cost     GST     Total Cost
    CrownJewels 99999999991x 100,000.00 1 100,000.00 5,000.00 $105,000.00
    Diamond Necklace 12345678901x 54,321.99 188 10,212,534.12 510,626.71 $10,723,160.83
    Pearls      88888888881x 10,000.00 1 10,000.00 500.00 $10,500.00
    RubyRing      77777777771x 10,000.00 1 10,000.00 500.00 $10,500.00
    Tissues      98989898989x 1.99 2 3.98 0.20     $4.18
    TOTALS          (complete these values)           xxx           xxx      xxx
    Java coding requirements for this assignment
    Main methods required
    1.     Load array with all records. Display exception messages only for records that have invalid data in any of the fields. Return array of valid records and logical size.
    2.     Validate the UPC. Display each report when requested from the menu.
    3.     Justify the data in the columns. Right justify numeric fields; left justify the alpha fields.
    4.     A method for each report required in the menu.
    Class methods
    5.     Use the object method for the extended cost.
    6.     Use the object method for the GST.
    You may use additional methods in the main program but do not add any methods in the class definition.
    Use DecimalFormat for rounding.
    Create an array to hold the objects. Assume that we only need to process a file of a maximum of 500 records but the file may be larger than 500 records.
    A Universal Product Code consists of 12 digits. The first digit (from the left) is the UPC type. The next five digits are the Manufacturer code. The next five digits are the product code which is assigned by the manufacturer. The final digit is the check digit. A person can determine the check digit of a Universal Product Code by doing the following:
    Step 1: Sum all of the digits in the odd positions together.
    0+4+0+1+5+9 = 19
    Step 2: Multiply the sum from Step 1 by 3.
    3 * 19 = 57
    Step 3: Sum all of the digits in the even positions together.
    6+2+0+1+8 = 17
    Step 4: Sum together the results from Step 2 and Step 3.
    17 + 57 = 74
    Step 5: Subtract the sum from the next highest multiple of 10.
    80 - 74 = 6 [check digit]
    TEST DATA:
    Step 1: Create 5 or MORE additional records that will test all conditions. Include these in your documentation. Identify what field is tested in your test data. (Example: error in each field of the record, rounding up, rounding down, valid UPC, invalid UPC, formatting of report, file too large
    Step 2: Use the file attached.
    GODDDDDDDDDDDDDD lol pasting it made me go crazy,
    these are my codes so far, HOwever the problem is ONLY DISPLAY MENU SHOWS, nothing else even though i have enough codes that it can show something,
    My codes are as follows:
    I am working on Eclipse.
    import java.util.Arrays;
    import java.util.Scanner;
    import java.io.*;
    import java.util.*;
    import java.io.IOException;
    * Name : Sana Ghani
    * Date : July 10
    public class lab56
         public static Scanner file;
         public static Scanner parse;
         public static Scanner input = new Scanner(System.in);
         public static Scanner searchInput = new Scanner(System.in);
         public static void main(String[] args) throws Exception
              Product1[] validProduct = new Product1[500];
              int logicalSize = 0;
              int menuChoice=0;
              String FileName = getFileName();
              displayMenu();
              switch(menuChoice)
              case 1:
                   displayAllValidRecords(validProduct, logicalSize);
                   try
                   // Open an output stream
                   OutputStream fout = new FileOutputStream ("myfile.txt");
                   // Print a line of text
                   new PrintStream(fout).println ("hello world!");
                   // Close our output stream
                   fout.close();          
                   // Catches any error conditions
                   catch (IOException e)
                        System.err.println ("Unable to write to file");
                        System.exit(-1);
                   break;
              case 2:
                   break;
              case 3:
                   binarySearchByName( validProduct,logicalSize);
                   break;
              case 4:
                   break;
              case 5:
                   break;
              menuChoice = displayMenu();
         public static void display(Product1[]validProduct, int logicalSize)throws Exception
              String Product, UPC;
              double Cost;
              int Quantity;
              for(int index =0; index<logicalSize; index++)
                   Product = validProduct[index].GetName();
                   UPC = validProduct[index].GetUPC();
                   Cost=validProduct[index].GetCost();
                   Quantity=validProduct[index].GetQuantity();
                   System.out.println(Product+"\t\t"+UPC+"\t\t"+Cost+"\t\t"+Quantity);
         public static String getFileName()
              String fileName;
              Scanner input = new Scanner(System.in);
              System.out.print("Please enter a file name: ");
              fileName = input.next();
              return fileName;
         public static int displayMenu()
              int menuChoice;
              boolean validFlag = false;
              do
                   System.out.println("\n\n*************************************");
                   System.out.println(" Product Display Menu ");
                   System.out.println("*************************************");
                   System.out.println("(1)Display All Records");
                   System.out.println("(2)Display All Invalid Records");
                   System.out.println("(3)Search by Product Name");
                   System.out.println("(4)Sort by Product Name");
                   System.out.println("(5)Exit");
                   System.out.println("*************************************");
                   System.out.print("Enter your choice(1-5): ");
                   menuChoice = input.nextInt();
                   if ((menuChoice >= 1) && (menuChoice <= 5))
                        validFlag = true;
                   if (!validFlag)
                        System.out.println("You have chosen " + menuChoice + ", " + menuChoice +
                        " is not valid. Please try again");
              }while(!validFlag);
              return menuChoice;
         public static String loadArray(Product1 [] ValidProduct, String fileName)throws Exception
              int logicalSize=0;//will always have to declare
              String record;//will always have to declare
              String Product, UPC;//variable names from
              double Quantity;
              double Cost;
              Scanner file = new Scanner(new File(fileName));//open
              record = file.nextLine();//read a line
              record = file.nextLine();//read a line
              for(int index = 0; index < ValidProduct.length && file.hasNext(); index++)//check to see if the file has data
                   record = file.nextLine();
                   parse = new Scanner(record).useDelimiter(",");
                   String Name = parse.next();
                   UPC = parse.next();
                   Cost = parse.nextDouble();
                   Quantity=parse.nextDouble();
                   ValidProduct[index] = new Product1 ( Name, UPC, Cost, (int) Quantity);
    //               create the object-- call the constructor and pass info
                   logicalSize++;
              return logicalSize+".txt";
         public static double roundDouble(double value, int position)
              java.math.BigDecimal bd = new java.math.BigDecimal(value);
              bd = bd.setScale(position,java.math.BigDecimal.ROUND_UP);
              return bd.doubleValue();
         * This method will print report about valid records
         public static void displayAllRecords( Product1[]valid, int ValidProduct,
                   Product1[] invalid, int InvalidProduct)
    //          Print valid records
              displayAllValidRecords(valid, ValidProduct);
    //          Print invalid UPC records
              displayAllValidRecords(invalid, InvalidProduct);
         public static void displayOneRecord(Product1[]valid, int index)
              double extendedCost, GST, SumofGST = 0, // Total Extended Cost
              totalCost, SumOfTotalCost = 0; // Total Extended Cost + GST
    //          Print title
              System.out.println(leftJustify("Product", 50) +
                        leftJustify("UPC", 15) +
                        rightJustify("Cost", 10) +
                        rightJustify("Quantity", 5) +
                        rightJustify("Extended Cost", 15) +
                        rightJustify("GST", 5) +
                        rightJustify("Total Cost", 13));
              extendedCost = valid[index].CalculateExtendedCost();
              extendedCost = roundDouble(extendedCost, 2);
              GST = valid[index].CalculateGST();
              GST = roundDouble(GST, 2);
              totalCost = extendedCost + GST;
              totalCost = roundDouble(totalCost, 2);
    //          justify method ensures all values are of the same size
              System.out.println(//leftJustify(i+"",3) + ": " +
                        leftJustify(valid[index].GetName(), 50) +
                        leftJustify(valid[index].GetUPC(), 15) +
                        rightJustify(valid[index].GetCost()+"", 10) +
                        rightJustify(valid[index].GetQuantity()+"", 5) +
                        rightJustify(extendedCost+"", 10) +
                        rightJustify(GST+"", 10) +
                        rightJustify(totalCost+"", 10));
         * This method will print report about valid records
         public static void displayAllValidRecords( Product1[]valid, int validCounter)
              double extendedCost, sumOfExtendedCost = 0, // Total Extended Cost
              GST, sumOfGST = 0, // Total GST
              totalCost, sumOfTotalCost = 0; // Total Extended Cost + GST
              System.out.println("************************ XYZ Product " +
                        "Cost REPORT ****************************" +
    //          Print title
              System.out.println(leftJustify("Product", 50) +
                        leftJustify("UPC", 15) +
                        rightJustify("Cost", 10) +
                        rightJustify("Qty", 5) +
                        rightJustify("Extended Cost", 15) +
                        rightJustify("GST", 5) +
                        rightJustify("Total Cost", 13));
    //          Print Records
              for(int i=0; i<validCounter; i++)
                   extendedCost = valid.CalculateExtendedCost();
                   extendedCost = roundDouble(extendedCost, 2);
                   GST = valid[i].CalculateGST();
                   GST = roundDouble(GST, 2);
                   totalCost = extendedCost + GST;
                   totalCost = roundDouble(totalCost, 2);
    //               justify method ensures all values are of the same size
                   System.out.println(//leftJustify(i+"",3) + ": " +
                             leftJustify(valid[i].GetName(), 50) +
                             leftJustify(valid[i].GetUPC(), 15) +
                             rightJustify(valid[i].getClass()+"", 10) +
                             rightJustify(valid[i].GetQuantity()+"", 5) +
                             rightJustify(extendedCost+"", 10) +
                             rightJustify(GST+"", 10) +
                             rightJustify(totalCost+"", 10));
                   sumOfExtendedCost += extendedCost;
                   sumOfGST += GST;
                   sumOfTotalCost += totalCost;
         private static void sortByName(Product1 [] ValidProduct, int logicalSize) throws Exception
              Product1 temp;
              for (int outer = logicalSize-1; outer > 1; outer --)
                   for (int inner = 0; inner < outer; inner ++)
                        if (ValidProduct[inner].GetName().compareToIgnoreCase(ValidProduct[inner+1].GetName())>0)
                             temp = ValidProduct[inner];
                             ValidProduct[inner] = ValidProduct[inner + 1];
                             ValidProduct [+ 1] = temp;
         public static void binarySearchByName(Product1 [] ValidProduct, int logicalSize)
              int high = logicalSize - 1;
              int low = 0;
              int mid = 0;
              int count = 0;
              int compare = 0;
              boolean found = false;
              System.out.print("Enter a product name");
              String product = input.nextLine();
              while (high >= low && !found)
                   count += 1;
                   mid = (high + low) / 2;
                   compare = ValidProduct[mid].GetName().compareToIgnoreCase(product);
                   if (compare == 0)
                        System.out.println("Found: " + ValidProduct[mid].GetName());
                        found = true;
                   else if (compare < 0)
                        low = mid + 1;
                   else
                        high = mid - 1;
              if (!found)
                   System.out.println(product + " not found.");
              System.out.println(count + " steps");
              System.out.println();
         public static String leftJustify(String field, int width)
              StringBuffer buffer = new StringBuffer(field);
              while (buffer.length() < width)
                   buffer.append(' ');
              return buffer.toString();
         public static String rightJustify(String field, int width)
              StringBuffer buffer = new StringBuffer(field);
              while (buffer.length() < width)
                   buffer.append(' ');
              return buffer.toString();
         public static void displayValidRecords(Product1 [] ValidProduct, int logicalSize) throws Exception {
              long longMAX_POSSIBLE_UPC_CODE = 999999999999L;
              // set input stream and get number
              Scanner stdin = new Scanner(System.in);
              System.out.print("Enter a 12-digit UPC number: ");
              long input =stdin.nextLong();
              long number = input;
              // determine whether number is a possible UPC code
              if ((input < 0)|| (input > longMAX_POSSIBLE_UPC_CODE)) {
                   // not a UPC code
                   System.out.println(input +"is an invalid UPC code");
              else {   
                   // might be a UPC code
                   // determine digits
                   int d12 = (int) (number % 10);
                   number /= 10;
                   int d11 = (int) (number % 10);
                   number /= 10;
                   int d10 = (int) (number % 10);
                   number /= 10;
                   int d9 = (int) (number % 10);
                   number /= 10;
                   int d8 = (int) (number % 10);
                   number /= 10;
                   int d7 = (int) (number % 10);
                   number /= 10;
                   int d6 = (int) (number % 10);
                   number /= 10;
                   int d5 = (int) (number % 10);
                   number /= 10;
                   int d4 = (int) (number % 10);
                   number /= 10;
                   int d3 = (int) (number % 10);
                   number /= 10;
                   int d2 = (int) (number % 10);
                   number /= 10;
                   int d1 = (int) (number % 10);
                   number /= 10;
                   // compute sums of first 5 even digits and the odd digits
                   int m = d2 + d4 d6 d8 + d10;
                   int n = d1 + d3 d5 d7 + d9 + d11;
                   // use UPC formula to determine required value for d12
                   int r = 10 - ((m +3*n) % 10);
                   // based on r, can test whether number is a UPC code
                   if (r == d12) {
                        // is a UPCcode
                        System.out.println(input+" is a valid UPC code");
                   else {   
                        // not a UPCcode
                        System.out.println(input+" is not valid UPC code");
    Any help would be great thanks !!
    Take care,

    1) It's your problem that you waited until the last minute before you went for help...not ours. We'll give your problem the same attention as anyone elses...therefore your problem isn't any more urgent than any other problem here.
    2) I don't intend on doing your entire assignment. Nor do I intend on reading all of it. If you need help with a specific requirement, then post the information/code relevant to that requirement. I don't know how to help you when you bury the problem inside a 9 mile long essay.
    3) Post code in tags so it's formatted and readable. (there's a *code* button up above that makes the tags for you).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Java Calendar Help Needed :)

    Hi,
    I am trying to develop a Java Event Calendar which is able to display the calendar weekly. So the JPanel will be setup with 7 JLists for the days of the week. Buttons will allow switching of the days of the week, months and year.
    Each JList corresponding to the day of the week will have its data obtained from the database using JDBC and loaded upon 're-drawing' of the lists.
    However i am having trouble with the GUI side in understanding how to implement this, i am confident with the JList and database side of things, i have just used a similar example using the Calendar API for monthly displays, however i am unsure how to convert this to a weekly calendar.
    Ideally 7 JLists will always be available in the panel in order M,T,W,T,F,S,S but some will be set to inactive (for example in the first and last weeks of the month).
    If anyone has any suggestions please could you help me out :)
    Sorry if what im trying to do is a bit confusing.
    I've included the code i've been using for the monthly calendar
    THANKS!!
    public class CalendarPanel extends JPanel implements ActionListener {
      private Calendar panelDate;
      private Label monthLabel;
      private Label yearLabel;
      private Panel daysPanel;
      private Vector calendarListeners;
      private static final String days[] = {"S","M","T","W","T","F","S"};
      public CalendarPanel(){
        super(new BorderLayout());
        panelDate = Calendar.getInstance();
        buildUI();
      public CalendarPanel(Calendar date){
        super(new BorderLayout());
        panelDate = (date != null) ? (Calendar)date.clone() : Calendar.getInstance();
        buildUI();
      public CalendarPanel(Date date){
        super(new BorderLayout());
        panelDate = Calendar.getInstance();
        if(date != null) panelDate.setTime(date);
        buildUI();
      public Calendar getCalendar(){ return panelDate;}
      public void setCalendar(Calendar date){
        if(date != null){
          panelDate = (Calendar)date.clone();
          redrawPanel();
      public void setCalendar(Date date){
        if(date != null){
          panelDate.setTime(date);
          redrawPanel();
      public int getYear(){ return panelDate.get(Calendar.YEAR);}
      public String getMonthName(){
        switch(panelDate.get(Calendar.MONTH)){
        case Calendar.JANUARY: return "January";
        case Calendar.FEBRUARY: return "February";
        case Calendar.MARCH: return "March";
        case Calendar.APRIL: return "April";
        case Calendar.MAY: return "May";
        case Calendar.JUNE: return "June";
        case Calendar.JULY: return "July";
        case Calendar.AUGUST: return "August";
        case Calendar.SEPTEMBER: return "September";
        case Calendar.OCTOBER: return "October";
        case Calendar.NOVEMBER: return "November";
        case Calendar.DECEMBER: return "December";
        case Calendar.UNDECIMBER: return "Undecimber";
        default: return "Unknown";
      private void buildUI(){
        this.add(buildHeaderPanel(), BorderLayout.NORTH);
        daysPanel = new Panel(new GridBagLayout());
        redrawPanel();
        this.add(daysPanel, BorderLayout.CENTER);
      // build the part of the gui that contains the month and year
      // labels with their incrementors / decrementors
      private Panel buildHeaderPanel(){
        monthLabel = new Label(getMonthName(), Label.CENTER);
        yearLabel = new Label(Integer.toString(panelDate.get(Calendar.YEAR)),
                     Label.CENTER);
        GridBagConstraints gbc = new GridBagConstraints();
        Panel headerPanel = new Panel(new GridBagLayout());
        // month label and buttons
        Panel panel = new Panel(new GridBagLayout());
        Button button = new Button("-");
        button.setActionCommand("decrease month");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.EAST;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(monthLabel, gbc);
        button = new Button("+");
        button.setActionCommand("increase month");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.WEST;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.weightx = 1;
        headerPanel.add(panel, gbc);
        // year label and buttons
        panel = new Panel(new GridBagLayout());
        button = new Button("-");
        button.setActionCommand("decrease year");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.EAST;
        gbc.weightx = 0;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(yearLabel, gbc);
        button = new Button("+");
        button.setActionCommand("increase year");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.WEST;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.weightx = 1;
        headerPanel.add(panel, gbc);
        return headerPanel;
      // redraws the entire panel, including relaying out of
      // the days buttons
      private void redrawPanel(){
        monthLabel.setText(getMonthName());
        yearLabel.setText(Integer.toString(getYear()));
        // redraw days panel
        GridBagConstraints gbc = new GridBagConstraints();
        // clear current days panel
        daysPanel.removeAll();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1;
        gbc.weighty = 1;
        // add days of week
        for(int i = 0; i < days.length; i++, gbc.gridx++)
          daysPanel.add(new Label(days, Label.CENTER), gbc);
    gbc.gridx = 0;
    gbc.gridy++;
    // days of month
    Button button; // day buttons
    JTable day = new JTable();
    Calendar today = Calendar.getInstance();
    Calendar cellDay = (Calendar)today.clone();
    int month = panelDate.get(Calendar.MONTH);
    int year = panelDate.get(Calendar.YEAR);
    // start with first of panels month
    cellDay.set(year, month, 1);
    gbc.gridx = cellDay.get(Calendar.DAY_OF_WEEK) - 1;
    while( cellDay.get(Calendar.MONTH) == month ){
    if(gbc.gridx > 6){
         gbc.gridy++;
         gbc.gridx = 0;
    button = new Button(Integer.toString(cellDay.get(Calendar.DATE)));
    button.addActionListener(this);
    if( cellDay.equals(today)){
         button.setForeground(Color.red);
    daysPanel.add(button, gbc);
    gbc.gridx++;
    cellDay.add(Calendar.DAY_OF_MONTH, 1);
    // re validate entire panel
    validate();
    // implementation of ActionListener interface
    // currently no real need to create subclassed action
    // events for calendar. All actions generated by this
    // are action events (generated from the buttons).
    // the action command will be one of the four below
    // or a number (the label of the day button!).
    public void actionPerformed(ActionEvent ae){
    String command = ae.getActionCommand();
    if(command.equals("increase month")){
    panelDate.add(Calendar.MONTH, 1);
    redrawPanel();
    } else if(command.equals("decrease month")){
    panelDate.add(Calendar.MONTH, -1);
    redrawPanel();
    } else if(command.equals("increase year")){
    panelDate.add(Calendar.YEAR, 1);
    redrawPanel();
    } else if(command.equals("decrease year")){
    panelDate.add(Calendar.YEAR, -1);
    redrawPanel();
    notifyCalendarListeners(ae);
    // methods for keeping track of interested listeners
    public void addCalendarActionListener(ActionListener al){
    if(al != null){
    if(calendarListeners == null) calendarListeners = new Vector();
    calendarListeners.addElement(al);
    public void removeCalendarActionListener(ActionListener al){
    if((calendarListeners != null) && (al != null)){
    calendarListeners.removeElement(al);
    private void notifyCalendarListeners(ActionEvent ae){
    if((calendarListeners != null) && (!calendarListeners.isEmpty())){
    java.util.Enumeration e = calendarListeners.elements();
    while(e.hasMoreElements())
         ((ActionListener)e.nextElement()).actionPerformed(ae);

    Hi,
    Sorry for the change of screen name, i'm having trouble with my old account.
    I have now got most of the system working. However I am having trouble working out how to stop the last days of the previous month appearing in the first week of the next month. For example on 'July 2008' , days 29 and 30 of June are present in the first week of July. How can i get rid of this? And also for the last week of the month, how to get rid of the first days of the next month?
    import java.awt.BorderLayout;
    import java.awt.Button;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Label;
    import java.awt.Panel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Vector;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.EtchedBorder;
    * @category CalendarSystem
    * @author Daniel Barrett
    public class CalendarSystem extends JPanel implements ActionListener, MouseListener, KeyListener   {
         JPanel events = new JPanel();
         JPanel action = new JPanel();
              //Events Panel
         DateComboBox eventDateChooser = new DateComboBox();
         JTextField ref = new JTextField(10);
         JTextArea eventDetails = new JTextArea();
         JScrollPane scrollingArea = new JScrollPane(eventDetails);
         JTextField dateF = new JTextField(15);
         JTextField timeF = new JTextField(15);
         String[] minutes = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"};
         String[] hours = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"};
         JComboBox minsComb = new JComboBox(minutes);
         JComboBox hourComb = new JComboBox(hours);
              //Actions Panel
         JButton delete = new JButton("Delete");
         JButton purge = new JButton("Purge");
         JButton add = new JButton("Add");
         JButton edit = new JButton("Edit");
         JButton mview = new JButton("Month View");
         protected JLabel monthLabel;
         protected JLabel weekLabel;
         protected JLabel lmonday = new JLabel("");
         protected JLabel ltuesday = new JLabel("");
         protected JLabel lwednesday = new JLabel("");
         protected JLabel lthursday = new JLabel("");
         protected JLabel lfriday = new JLabel("");
         protected JLabel lsaturday = new JLabel("");
         protected JLabel lsunday = new JLabel("");
         protected Calendar calendar;
         protected SimpleDateFormat monthFormat = new SimpleDateFormat("MMM yyyy");
         protected SimpleDateFormat dayFormat = new SimpleDateFormat("MMM");
         JPanel monthCont = new JPanel();
         JPanel weekCont = new JPanel();
         JPanel yearCont = new JPanel();
         JPanel daysOfWeek = new JPanel();
         JPanel monday = new JPanel();
         JPanel tuesday = new JPanel();
         JPanel wednesday = new JPanel();
         JPanel thursday = new JPanel();
         JPanel friday = new JPanel();
         JPanel saturday = new JPanel();
         JPanel sunday = new JPanel();
         JList mondayEvents = new JList();
         JScrollPane mondayEventsScroll = new JScrollPane(mondayEvents);
         JList tuesdayEvents = new JList();
         JScrollPane tuesdayEventsScroll = new JScrollPane(tuesdayEvents);
         JList wednesdayEvents = new JList();
         JScrollPane wednesdayEventsScroll = new JScrollPane(wednesdayEvents);
         JList thursdayEvents = new JList();
         JScrollPane thursdayEventsScroll = new JScrollPane(thursdayEvents);
         JList fridayEvents = new JList();
         JScrollPane fridayEventsScroll = new JScrollPane(fridayEvents);
         JList saturdayEvents = new JList();
         JScrollPane saturdayEventsScroll = new JScrollPane(saturdayEvents);
         JList sundayEvents = new JList();
         JScrollPane sundayEventsScroll = new JScrollPane(sundayEvents);
         protected Color selectedBackground;
         protected Color selectedForeground;
         protected Color background;
         protected Color foreground;
         public CalendarSystem(){
              setupDays();
              setupHeaders();
              setupEvents();
              setupActions();
              this.calendar = Calendar.getInstance();
              this.calendar.setFirstDayOfWeek(Calendar.SUNDAY);
              this.add(this.monthCont);
              this.add(this.daysOfWeek);
              this.add(this.weekCont);
              this.add(this.events);
              this.add(this.action);
              this.setLayout(new BoxLayout(this,1));
              this.setMaximumSize(new Dimension(400,30));
              this.updateCalendar();
         private void setupActions() {
              this.action.setBorder(BorderFactory.createTitledBorder("Actions"));
              this.action.add(this.add);
              this.action.add(this.edit);
              this.action.add(this.delete);
              this.action.add(this.purge);
              this.action.add(this.mview);
         private void setupEvents() {
              this.events.setBorder(BorderFactory.createTitledBorder("Event Details"));
              this.events.setLayout(new BoxLayout(this.events,1));
              JPanel row1 = new JPanel();
              JPanel row2 = new JPanel();
              JPanel row3 = new JPanel();
              JLabel la = new JLabel("Reference");
              JLabel da = new JLabel("Date");
              JLabel time = new JLabel("Time");
              JLabel det = new JLabel("Details");
              this.ref.setEditable(false);
              this.dateF.setEditable(false);
              this.timeF.setEditable(false);
              this.eventDetails.setEditable(false);
              row1.add(la);
              row1.add(this.ref);
              row1.add(da);
              row1.add(this.dateF);
              row1.add(time);
              row1.add(this.timeF);
              row2.add(det);
              scrollingArea.setPreferredSize(new Dimension(600,50));
              row3.add(this.scrollingArea);
              this.events.add(row1);
              this.events.add(row2);
              this.events.add(row3);
         protected JLabel createUpdateButton(final int field, final int amount, final boolean month) {
             final JLabel label = new JLabel();
             final Border selectedBorder = new EtchedBorder();
             final Border unselectedBorder = new EmptyBorder(selectedBorder.getBorderInsets(new JLabel()));
             label.setBorder(unselectedBorder);
             label.setForeground(foreground);
             label.addMouseListener(new MouseAdapter() {
                  public void mouseReleased(MouseEvent e) {
                   calendar.add(field, amount);
                   if(month){
                   updateMCalendar();}
                   else{
                        updateCalendar();
                   public void mouseEntered(MouseEvent e) {
                   label.setBorder(selectedBorder);
                  public void mouseExited(MouseEvent e) {
                   label.setBorder(unselectedBorder);
             return label;
         private void updateMCalendar() {
              this.calendar.set(Calendar.DAY_OF_MONTH, 1);
              updateCalendar();     
         private void setupHeaders() {
              //MONTH CONTROLS
             monthCont.setLayout(new BoxLayout(monthCont, BoxLayout.X_AXIS));
             monthCont.setBackground(background);
             monthCont.setOpaque(true);
             JLabel label;
             label = createUpdateButton(Calendar.YEAR, -1,false);
             label.setText("<<");
             label.setToolTipText("Previous Year");
             monthCont.add(Box.createHorizontalStrut(12));
             monthCont.add(label);
             monthCont.add(Box.createHorizontalStrut(12));
             label = createUpdateButton(Calendar.MONTH, -1,true);
             label.setText("< ");
             label.setToolTipText("Previous Month");
             monthCont.add(label);
             monthLabel =new JLabel("", JLabel.CENTER);
             monthLabel.setForeground(foreground);
             //monthCont.add(Box.createHorizontalGlue());
             monthCont.add(Box.createHorizontalStrut(12));
             monthCont.add(monthLabel);
             monthCont.add(Box.createHorizontalStrut(12));
             //monthCont.add(Box.createHorizontalGlue());
             label =createUpdateButton(Calendar.MONTH, 1,true);
             label.setText(" >");
             label.setToolTipText("Next Month");
             monthCont.add(label);
             label = createUpdateButton(Calendar.YEAR, 1,false);
             label.setText(">>");
             label.setToolTipText("Next Year");
             monthCont.add(Box.createHorizontalStrut(12));
             monthCont.add(label);
             monthCont.add(Box.createHorizontalStrut(12));
             //WEEK CONTROLS
             weekCont.setLayout(new BoxLayout(weekCont, BoxLayout.X_AXIS));
             weekCont.setBackground(background);
             weekCont.setOpaque(true);
             JLabel label1;
             label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, -1,false);
             label1.setText("<<");
             label1.setToolTipText("Previous Week");
             weekCont.add(label1);
             weekLabel =new JLabel("", JLabel.CENTER);
             weekLabel.setForeground(foreground);
             JLabel lweek =new JLabel("Week:  ", JLabel.CENTER);
             lweek.setForeground(foreground);
             //monthCont.add(Box.createHorizontalGlue());
             weekCont.add(Box.createHorizontalStrut(12));
             weekCont.add(lweek);
             weekCont.add(weekLabel);
             weekCont.add(Box.createHorizontalStrut(12));
             //monthCont.add(Box.createHorizontalGlue());
             label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, 1,false);
             label1.setText(">>");
             label1.setToolTipText("Next Week");
             weekCont.add(label1);
         public void setupDays(){
              monday.setLayout(new BoxLayout(monday,1));
              tuesday.setLayout(new BoxLayout(tuesday,1));
              wednesday.setLayout(new BoxLayout(wednesday,1));
              thursday.setLayout(new BoxLayout(thursday,1));
              friday.setLayout(new BoxLayout(friday,1));
              saturday.setLayout(new BoxLayout(saturday,1));
              sunday.setLayout(new BoxLayout(sunday,1));
              monday.add(this.lmonday);
              monday.add(this.mondayEventsScroll);
              monday.setBorder(BorderFactory.createTitledBorder("Monday"));
              tuesday.add(this.ltuesday);
              tuesday.add(this.tuesdayEventsScroll);
              tuesday.setBorder(BorderFactory.createTitledBorder("Tuesday"));
              wednesday.add(this.lwednesday);
              wednesday.add(this.wednesdayEventsScroll);
              wednesday.setBorder(BorderFactory.createTitledBorder("Wednesday"));
              thursday.add(this.lthursday);
              thursday.add(this.thursdayEventsScroll);
              thursday.setBorder(BorderFactory.createTitledBorder("Thursday"));
              friday.add(this.lfriday);
              friday.add(this.fridayEventsScroll);
              friday.setBorder(BorderFactory.createTitledBorder("Friday"));
              saturday.add(this.lsaturday);
              saturday.add(this.saturdayEventsScroll);
              saturday.setBorder(BorderFactory.createTitledBorder("Saturday"));
              sunday.add(this.lsunday);
              sunday.add(this.sundayEventsScroll);
              sunday.setBorder(BorderFactory.createTitledBorder("Sunday"));
              this.mondayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.monday.setPreferredSize(new Dimension(145,300));
              this.tuesdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.tuesday.setPreferredSize(new Dimension(145,300));
              this.wednesdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.wednesday.setPreferredSize(new Dimension(145,300));
              this.thursdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.thursday.setPreferredSize(new Dimension(145,300));
              this.fridayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.friday.setPreferredSize(new Dimension(145,300));
              this.saturdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.saturday.setPreferredSize(new Dimension(145,300));
              this.sundayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.sunday.setPreferredSize(new Dimension(145,300));
              daysOfWeek.add(this.sunday);
              daysOfWeek.add(this.monday);
              daysOfWeek.add(this.tuesday);
              daysOfWeek.add(this.wednesday);
              daysOfWeek.add(this.thursday);
              daysOfWeek.add(this.friday);
              daysOfWeek.add(this.saturday);
        private void updateCalendar() {
             monthLabel.setText(monthFormat.format(calendar.getTime()) );
             weekLabel.setText(String.valueOf(this.calendar.get(calendar.WEEK_OF_MONTH)));
             //Blank out / empty strings for first elements that do not start on sunday
             Calendar setupCalendar = (Calendar) calendar.clone();
             setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.getFirstDayOfWeek());
           // while(setupCalendar.get(Calendar.DAY_OF_WEEK) < calendar.getActualMaximum(Calendar.DAY_OF_WEEK)) {
                //System.out.println("day of month: " + setupCalendar.get(Calendar.DAY_OF_MONTH));
                //System.out.println("day of week: " + (setupCalendar.get(Calendar.DAY_OF_WEEK)));
                //System.out.println("week of month: " + calendar.get(Calendar.WEEK_OF_MONTH) + "\n");
                  setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
        public void setDayLabels(int day, int dayOfWeek){
             if(dayOfWeek == 1){
                  this.lsunday.setText(String.valueOf(day));
             if(dayOfWeek == 2){
                  this.lmonday.setText(String.valueOf(day));
             if(dayOfWeek == 3){
                  this.ltuesday.setText(String.valueOf(day));
             if(dayOfWeek == 4){
                  this.lwednesday.setText(String.valueOf(day));
             if(dayOfWeek == 5){
                  this.lthursday.setText(String.valueOf(day));
             if(dayOfWeek == 6){
                  this.lfriday.setText(String.valueOf(day));
             if(dayOfWeek == 7){
                  this.lsaturday.setText(String.valueOf(day));
         @Override
         public void actionPerformed(ActionEvent arg0) {
         @Override
         public void mouseClicked(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyPressed(KeyEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyReleased(KeyEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyTyped(KeyEvent arg0) {
              // TODO Auto-generated method stub
         public static void main(String args[]){
              JFrame frame = new JFrame();
              frame.setSize(1100, 670);
              frame.add(new CalendarSystem());
              frame.setVisible(true);
    }Thanks
    Dan

  • Java SDK Help Needed URGENTLY!

    Hi, as part of my uni course I am required to learn Java. Until now, I have only used it at uni and everything works fine. However, I decided to download Java 2 SDK from the Sun website (version 1.3.1_01).
    I am using Textpad as the editor and just installed Java by running the 32mb installer file. Textpad works fine and Java was installed to c:\jdk1.3.1_01
    Now, i created this simple program (from my tutorial notes) in Textpad:
    // The code below is held in a file called Exmpl1.java
    // This is Example1
    // The program requires you to type in your name.
    // Your name and a welcome message are then output to the screen
    import java.io.*;
    class Exmpl1M
    static BufferedReader keyboard = new
    BufferedReader (new InputStreamReader(System.in));
    static PrintWriter screen = new PrintWriter(System.out,true);
    public static void main (String[] args) throws IOException
    String name; // The place to store data entered from the keyboard
    // Prompt to the user of the program
    screen.print("Please enter your name ");
    screen.flush();
    // Get the data (a name) entered at the keyboard
    name = keyboard.readLine();
    screen.print("\n\nHello " + name );
    screen.println(" - Welcome to programming with Java\n\n");
    String lab; // The place to store data entered from the keyboard
    screen.print("What lab are you working in? ");
    screen.flush();
    // Get the data (a lab) entered at the keyboard
    lab = keyboard.readLine();
    screen.println("\n\n" + lab + "is a nice place to work!" );
    } // End of method main
    } // End of class Exmpl1M
    I know this file works ok because i have tested it on the uni computers. The Exmpl1M.class file is created where the Exmpl1M.java file is stored. It will compile fine using the Tools>Compile Java menu option.
    Now, here is the problem: when i go to Tools>Run Java Application, I get the message
    "Exception in thread "main" java.lang.NoClassDefFoundError: Exmpl1M
    Press any key to continue..."
    Now, seeing as how i am new to Java, i have no idea why i am getting this message. Should I have changed any settings when i installed Java? I'm guessing it may have something to do with "method main" in the coding, but we have always been told to put this but not told why.
    Please help cause i need to be able to write the progs at home too

    Is the name of the class the same as the class file
    Maybe you mixed up Exmple1 and Exmpl1M
    If this is ok then try this:
    I do not know Textpad so
    open Terminal/Console/DOS-Box go to directory where your Exmpl1.class file is located.
    Type in
    java Exmpl1
    If the program runs now some configuration in Textpad is wrong.
    Horst
    Hi, as part of my uni course I am required to learn
    Java. Until now, I have only used it at uni and
    everything works fine. However, I decided to download
    Java 2 SDK from the Sun website (version 1.3.1_01).
    I am using Textpad as the editor and just installed
    Java by running the 32mb installer file. Textpad works
    fine and Java was installed to c:\jdk1.3.1_01
    Now, i created this simple program (from my tutorial
    notes) in Textpad:
    I know this file works ok because i have tested it on
    the uni computers. The Exmpl1M.class file is created
    where the Exmpl1M.java file is stored. It will compile
    fine using the Tools>Compile Java menu option.
    Now, here is the problem: when i go to Tools>Run Java
    Application, I get the message
    "Exception in thread "main"
    java.lang.NoClassDefFoundError: Exmpl1M
    Press any key to continue..."
    Now, seeing as how i am new to Java, i have no idea
    why i am getting this message. Should I have changed
    any settings when i installed Java? I'm guessing it
    may have something to do with "method main" in the
    coding, but we have always been told to put this but
    not told why.
    Please help cause i need to be able to write the progs
    at home too

  • Help, need to change IP address on host database for Portal

    Hi folks,
    Rather urgent assistance (as usual) needed. I have an installation working correctly on a pair of Win2k machines, one as the 9i database, one as the 9iAS/Portal. The app server has 2 NIC cards, one with public IP address (which is ok), one on the LAN. I need to reconfigure the LAN addresses on both the machines. Initial Portal install done without DNS, i.e. actual server/host addresses entered in the configuration.
    I have tried changing all of the TNS/Listner settings and the NIC card IP addresses and restarting the machines. The likes of SQLPlus work ok, with the TNS connect name allowing over the LAN access into the database with the new LAN addresses. I cannot seem to get the 9iAS/Portal to find the repository with the new addresses.
    Can someone help please? I can't find the answer in any documentation or other postings.
    Thanks in advance
    Rob

    There are other modes of operation for the plasst as well. I am listing them below but the formatting will make it difficult to read. If you like I can email it to you.
    Bill G...
    Configuring Portal when the HTTP server host name of the Infrastructure is changed
    Run the following from the $ORACLE_HOME/assistants/opca dir
    ptlasst.bat -mode SSOPARTNERCONFIG -i typical -sdad portal -host myApache.domain.com -port 7777 -silent -verbose
    NOTE:
    (1) This command would create a new Portal partner application in the SSO to reflect the changes of the Infrastructure. Before running this command please ensure to configure the SSO with the correct hostname by running the ssocfg.bat script located in the Infrastructure install (<infra_home>\sso\bin).
    The value for -host parameter will be the IP address of the infrastructure server and -port will be the port where the infrastructure http server is running on.
    Configuring Portal when the HTTP server host name of the Middle tier is changed
    ptlasst.bat -mode MIDTIER -i typical -host myApache.domain.com -port 7777 -ldap_h myOID.domain.com -ldap_p 389 -ldap_w welcome -pwd secret123 -portal_only -oh /home/oracle -chost myHostname.domain.com -cport_i 8001 -cport_a 8000 -wc_i_pwd invalidator -mc false -mi true -silent -verbose
    NOTE :
    (1) The -host value should match the serverName value of the httpd.conf
    (2) The -chost should be updated with the correct webcache hostname. In a default iAS midtier install the -host is same as the -chost.
    The value for -host parameter will be the IP address of the midtier(portal) server and -port will be the port where the portal is running on.
    Parameter Description Default Value Mandatory
    -i install_type Installation Type
    In the typical mode, the OPCA would get the Infrastructure information like the Portal schema name, Portal schema password, connect string to the Portal repository, SSO Partner application schema and password, SSO Password store schema and password and connect string to the SSO repository from the Repository Access API's.
    In the custom mode, the OPCA would take whatever is passed as the command line arguments.
    CUSTOM
    -mode mode The different install modes are : PORTAL, SSO, SSOPARTNERCONFIG, LANGUAGE, MIDTIER, ALL, SYSOBJECTS , DEINSTALL
    -s portal_schema Oracle Database schema for Portal database objects. In an iAS 9.0.2 install
    the default Portal schema name is portal portal
    -sp portal_password Password for Portal schema. In an iAS 9.0.2 install the portal schema password is randomized by default. Refer to the note "How to get the Portal schema password of the Infrastructure database ?" for details. <portal_schema>
    -c portal_connect Connect string to connect to the Portal repository <hostname>:<port>:<sid>
    -p sys_password The Oracle Database password for the Oracle SYS user MANDATORY
    -sdad portal_dad DAD for the Portal schema. Create the DAD to the Portal repository through the OEM. Refer to the note "How to create and manage the Portal and SSO DAD ?" for details. <portal_schema>
    -host portal_host Hostname of the HTTP server for Portal. This should match byte to byte with whatever is present in the ServerName attribute in the $OH/Apache/Apache/conf/httpd.conf file of the midtier. MANDATORY
    -port portal_port Port of the HTTP server for Portal. The Port attribute in the $OH/Apache/Apache/conf/httpd.conf file of the midtier would provide the value. 7777
    -ldap_h oid_host_name Host name of the OID server MANDATORY
    -ldap_p oid_port_number Port number of the OID server 389
    -ldap_d oid_admin_DN Admininstration DN cn=orcladmin
    -ldap_w oid_admin_pw Password for DN welcome
    -pwd initial_password Initial Password for seeded OID users. In iAS 9.0.2 install this is defaulted to the iAS instance password of the midtier installation. MANDATORY (for ALL or MIDTIER)
    -das_public Add Portal Groups to DAS Public Groups. The values could be Y or N. The default is Y. The setting publishes the Portal groups that the user can add to when creating the new user in OID. Y
    -u default_tablespace Install Portal objects in this tablespace. The default tablespace selected should have atleast 75 MB of free available space and should have autoextend on. Refer to the note "What are the recommended tablespace size required for Portal installation ?" for details. The default tablespace selected by default is users tablespace. users
    -t temporary_tablespace Use this tablespace for temporary objects. The temporary tablespace selected should have atleast 20 MB of free available space and should have autoextend on. Refer to the note "What are the recommended tablespace size required for Portal installation ?" for details. The temporary tablespace selected by default is temp tablespace. temp
    -d document_tablespace Install Portal document table in this tablespace. The document tablespace selected should have atleast 4 MB of free available space and should have autoextend on. Refer to the note
    "What are the recommended tablespace size required for Portal installation ?" for details. The documented tablespace selected by default is users tablespace. <default_tablespace>
    -l logging_tablespace Install Portal logging tables in this tablespace. The Logging tablespace selected should have atleast 4 MB of free available space and should have autoextend on. Refer to the note "What are the recommended tablespace size required for Portal installation ?" for details. The Logging tablespace selected by default is users tablespace. <default_tablespace>
    -in index_tablespace Install Portal index in this tablespace. The Index tablespace selected should have atleast 20 MB of free available space and should have autoextend on. Refer to the note "What are the recommended tablespace size required for Portal installation ?" for details. The Index tablespace selected by default is users tablespace. <default_tablespace>
    -lang language Abbreviation for the language to install us
    -m language_mode Specifies the mode for language installation
    if sso, translations only for Login server.
    if portal, translations only for Portal.
    if -m not specified, translations are installed for Both
    -demo Install Portal webview demos
    -silent Run mode for Portal Configuration Assistant. There is no UI provided by OPCA in the iAS 9.0.2 install. Use -silent option always
    -verbose Log mode for Portal Configuration Assistant. If this parameter is not set, logging information would be in brief and the OPCA would abort the install if it encounters any errors of kind
    ORA-, PLS- or SP2 errors.
    -report Install reports integration with Portal
    -owa Install OWA packages along with Portal This option behaves the same as the SYSOBJECTS mode.
    -sso_only Configure only SSO in mid-tier mode
    -portal_only Configure only Portal in mid-tier mode
    -available Language will be available for user translation
    -chost cache_host Cache host for Web Cache <hostname>
    -cport_i cache_inv_port Cahe port for Web Cache Invalidation 1100
    -cport_a cache_adm_port Cahe port for Web Cache Administration 1000
    -wc_i_pwd wc_inv_passwd Web Cache invalidator password invalidator
    -wc wc_on_off_flag Web Cache ON/OFF flag to enable or disable WC. The default is ON. If set to OFF Portal would not use Webcache though Web Cache may be up and running. on
    -o sso_schema Oracle Database schema for Login Server objects. In an iAS 9.0.2 install the default SSO schema name is orasso orasso
    -op sso_password Password for Login Server Schema. In an iAS 9.0.2 install the SSO schema password is randomized by default. Refer to the note "How to get the Portal schema password of the Infrastructure database ?" for more details. Use similar steps to get the password of the orasso. MANDATORY for the following modes:
    -MIDTIER: except when '-portal_only' is specified
    -LANGUAGE: except when '-m portal' is specified
    -DEINSTALL: except when '-drop PORTAL' is specified
    -odad sso_dad DAD for Login Server objects. Create the DAD to the SSO repository through the OEM. Refer to the note "How to create and manage the Portal and SSO DAD ?" for details. <sso_schema>
    -sso_c sso_connect Connect string to connect to the SSO repository If the Portal and SSO use the same database this option need not be passed and would default to the -c argument. <hostname>:<port>:<sid>
    -sso_h sso_host Hostname of the HTTP server for the SSO. If Portal and SSO use the same HTTP server this option need not be passed. It would default the HTTP server used for the Portal.
    -sso_p sso_port Port of the HTTP server for the SSO. If Portal and SSO use the same HTTP server this option need not be passed. It would default the HTTP port used for the Portal.
    -pa papp_schema SSO Partner Application Registration Schema. In an iAS 9.0.2 install the default Password store schema name is orasso_pa <sso_schema>_PA  
    -pap papp_password SSO PA Schema Password. In an iAS 9.0.2 install the SSO schema password is randomized by default. Refer to the note "How to get the Portal schema password of the Infrastructure database ?" for more details. Use similar steps to get the password of the orasso_pa <papp_schema>
    -ps pstore_schema Password Store Schema. In an iAS 9.0.2 install the default Password store schema name is orasso_ps <sso_schema>_PS  
    -pp pstore_password Password Store Password. In an iAS 9.0.2 install the SSO schema password is randomized by default. Refer to the note "How to get the Portal schema password of the Infrastructure database ?" for more details. Use similar steps to get the password of the orasso_ps. <ptore_schema>
    -pd pstore_dblink Database link from Portal schema to Password store. If the Portal and SSO use the same database this option need not be passed. <portal_schema>_DBLINK  
    -p_tns pstore_tns TNS connect string to Password Store. If the Portal and SSO use the same database this option need not be passed. The tnsalias should be created in the iAS 9.0.2 Portal middle tier.
    -s_tns portal_tns TNS connect string to Portal
    -ssotype ssotype SSO install type. Valid values are repository, midtier, all Repository
    -ultrasearch Ultrasearch configuration
    -drop drop_obj Drops either PORTAL or SSO or ALL (Both)
    if PORTAL, drops Portal schema and OID entries.
    if SSO,drops Portal schema and OID entries.
    if ALL, drops Portal and SSO schema and OID entries
    -oh oracle_home Oracle Home
    -mi midtier_install Midtier Installation
    -mc midtier_config Midtier Configuration
    -ssl Use SSL protocol for configuration. Pass this parameter only if SSL configuration is required. If this parameter is passed the -port passed should also be the SSL port of the HTTP server. Bt default this is not passed.
    -emhost em_host Enterprise Manager host for monitoring <hostname>
    -emport em_port Enterprise Manager port for monitoring 1810
    -iasname ias_name Name of the iAS instance that the install is installing on

  • Help, Need to change NAT from moderate to open for WRT54GS2

    just like to the topic says i used these methods:
    Open an Internet Explorer browser page on your wired computer(desktop).In the address bar type - 192.168.1.1 and press Enter...Leave Username blank & in Password use admin in lower case...
    On the set-up tab change the MTU Size to 1365 and click Save Settings...
    Click on "Administration" tab and disable the option UPnP and click Save Settings...
    Click on "Applications and Gaming" tab and then click on "Port Range Forwarding" subtab...
    1) On the first line in Application box type in ABC, in the start box type in 53 and End box type in 3074, leave the protocol as both and under ip address type in 192.168.1.20 and check the enable box, click Save Settings once done...
    2) Once you return to the set up page click on the Security tab and uncheck Block Anonymous Internet Requests and click on Save Settings...
    3)Click on the Status tab and take note of DNS1 and DNS2 Addresses...
    4) Goto the XBox Network Settings and IP Address Settings and select manual IP Settings and assign the following on your Xbox IP Address :- 192.168.1.20, Subnet Mask :- 255.255.255.0, Default Gateway :- 192.168.1.1...
    5) Also assign the DNS Addresses on the Xbox, Use DNS1 and DNS2 Addresses you took note off of the router status tab as Primary DNS & Secondary DNS for the xbox...
    6) Turn off your modem, router, and Xbox...Wait for a minute...
    7) Plug the modem power first, wait for another minute and plug the router power cable, wait another minute and turn on the Xbox and test it...it will connect...     i have firmare 1.0.01. i am using 2 Pluglink 9650 Powerline Ethernet Adapters to connect to my xbox for xbox live. if u need anything else let me know. PLEASE SOMEONE HELP 

    What device is upstream from the router?  If you have a modem that acts as a router as well, then you might have a double NAT problem.  It's a well documented problem and can usually be solved by bridging the modem or configuring the router to work as a switch only.

  • Newbie help needed with Applet

    I am having a problem with the following Applet. I have highlighted it in bold.
    How can I ensure that all of the conditions are met regardless of the order they are inserted on the graph,within the program?
    At the moment I have to do them in the exact order they are in the code in order to get the "Winner" message.
    Also if I insert an image at any time at the point if(x >= 290 && x <= 350 && y >= 290 && y <= 350) I also receive the "Winner" message. I realise this happens because it is the last line of code in this statement.
    However I am very new to this and dont know how to fix it. Indeed I dont even know if this is the correct way to do this.
    Hope this makes sense.
    Any help would be very much appreciated
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class MyDraughts extends Applet implements MouseListener,ActionListener,
                   MouseMotionListener{
                        public MyDraughts(){
                             points = new ArrayList();
                             pawncount = 0;
                             pawncount1 = 14;
                             message = "";
                             message1 = "";
                             title = new Font ("Arial", Font.BOLD, 18);
         private Point square1, square2, square3, square4, square5, square6, square7,square8,square9,
         square10,square11,square12,square13,square14,square15,square16,square17,square18,square19,
         square20,square21,square22,square23,square24,square25,square26,square27,square28,square29,
         square30,square31,square32,mouse;
         private int select;
         private Image pawn;
         private Point icon;
         private ArrayList points;
         private int x;
         private int y;
         private int pawncount;
         private int pawncount1,pawncount2;
         private Button undoButton;
         private String message,message1;
         private Font title;
         public void init(){
              setBackground(new Color(210,255,210));
              this.addMouseMotionListener(this);
              this.addMouseListener(this);
              select = 0;
              square1=new Point(50,10);
              square2=new Point(130,10);
              square3=new Point(210,10);
              square4=new Point(290,10);
              square5=new Point(10,50);
              square6=new Point(90,50);
              square7=new Point(170,50);
              square8=new Point(250,50);
              square9=new Point(50,90);
              square10=new Point(130,90);
              square11=new Point(210,90);
              square12=new Point(290,90);
              square13=new Point(10,130);
              square14=new Point(90,130);
              square15=new Point(170,130);
              square16=new Point(250,130);
              square17=new Point(50,170);
              square18=new Point(130,170);
              square19=new Point(210,170);
              square20=new Point(290,170);
              square21=new Point(10,210);
              square22=new Point(90,210);
              square23=new Point(170,210);
              square24=new Point(250,210);
              square25=new Point(50,250);
              square26=new Point(130,250);
              square27=new Point(210,250);
              square28=new Point(290,250);
              square29=new Point(10,290);
              square30=new Point(90,290);
              square31=new Point(170,290);
              square32=new Point(250,290);
              undoButton = new Button("Undo");
    add(undoButton);
    undoButton.addActionListener(this);
              mouse= new Point();
              icon = new Point();
              pawn = getImage(getCodeBase(), "pawn.gif");
    public void actionPerformed(ActionEvent actionevent){
    if(actionevent.getSource() == undoButton){
    int a = points.size();
    int b = a - 1;
    points.remove(b);
    a = points.size();
    repaint();
    public void paint (Graphics g){
         drawBox(g);
         g.fillRect(square1.x, square1.y,40,40);
         g.fillRect(square2.x, square2.y,40,40);
         g.fillRect(square3.x, square3.y,40,40);
         g.fillRect(square4.x, square4.y,40,40);
         g.fillRect(square5.x, square5.y,40,40);
         g.fillRect(square6.x, square6.y,40,40);
         g.fillRect(square7.x, square7.y,40,40);
         g.fillRect(square8.x, square8.y,40,40);
         g.fillRect(square9.x, square9.y,40,40);
         g.fillRect(square10.x, square10.y,40,40);
         g.fillRect(square11.x, square11.y,40,40);
         g.fillRect(square12.x, square12.y,40,40);
         g.fillRect(square13.x, square13.y,40,40);
         g.fillRect(square14.x, square14.y,40,40);
         g.fillRect(square15.x, square15.y,40,40);
         g.fillRect(square16.x, square16.y,40,40);
         g.fillRect(square17.x, square17.y,40,40);
         g.fillRect(square18.x, square18.y,40,40);
         g.fillRect(square19.x, square19.y,40,40);
         g.fillRect(square20.x, square20.y,40,40);
         g.fillRect(square21.x, square21.y,40,40);
         g.fillRect(square22.x, square22.y,40,40);
         g.fillRect(square23.x, square23.y,40,40);
         g.fillRect(square24.x, square24.y,40,40);
         g.fillRect(square25.x, square25.y,40,40);
         g.fillRect(square26.x, square26.y,40,40);
         g.fillRect(square27.x, square27.y,40,40);
         g.fillRect(square28.x, square28.y,40,40);
         g.fillRect(square29.x, square29.y,40,40);
         g.fillRect(square30.x, square30.y,40,40);
         g.fillRect(square31.x, square31.y,40,40);
         g.fillRect(square32.x, square32.y,40,40);
         g.setFont(title);
         g.drawString(message, 350, 300);
         g.drawString(message1, 350, 320);
         for(int i = 0; i < points.size(); i++){
    icon = (Point)points.get(i);
    g.drawImage(pawn, icon.x, icon.y, 25, 25, this);
         g.drawImage(pawn,175,135,25,25,this);
         g.drawImage(pawn,135,175,25,25,this);
         g.setFont(title);
         g.drawString("Click A Square To Place A Pawn", 350, 50);
    public void mouseDragged(MouseEvent e){}
    public void mouseMoved(MouseEvent e){}
    //require for the interface
    public void mousePressed(MouseEvent mouseevent){
    setBackground(new Color(210,255,210));
    x = mouseevent.getX();
    y = mouseevent.getY();
    if(x > 19 && x < 312 && y > 19 && y < 312){
    pawncount = pawncount + 1;
    points.add(mouseevent.getPoint());
    if(pawncount > pawncount1){
    setBackground(Color.red);
    message = "Too Many Pawns!You can only place 14";
    message1 = "Hit restart to play again";
    pawncount1 = 14;
    if(x >= 10 && x <= 50 && y >= 290 && y <= 330){
    setBackground(Color.red);
    message = "A Pawn Can't be placed here";
    pawncount = 15;
    if(x >= 50 && x <= 90 && y >= 250 && y <= 290){
    setBackground(Color.red);
    message = "A Pawn Can't be placed here";
    pawncount = 15;
    if(x >= 90 && x <= 130 && y >= 210 && y <= 250){
    setBackground(Color.red);
    message = "A Pawn Can't be placed here";
    pawncount = 15;
    //This is the solution for the puzzle
    if(x >= 90 && x <= 130 && y >= 10 && y <= 50);
    if(x >= 250 && x <= 290 && y >= 10 && y <= 50);
    if(x >= 90 && x <= 130 && y >= 50 && y <= 90);
    if(x >= 170 && x <= 210 && y >= 50 && y <= 90);
    if(x >= 10 && x <= 50 && y >= 90 && y <= 130);
    if(x >= 50 && x <= 90 && y >= 90 && y <= 130);
    if(x >= 250 && x <= 290 && y >= 130 && y <= 170);
    if(x >= 50 && x <= 90 && y >= 170 && y <= 210);
    if(x >= 210 && x <= 250 && y >= 210 && y <= 250);
    if(x >= 290 && x <= 350 && y >= 210 && y <= 250);
    if(x >= 10 && x <= 50 && y >= 250 && y <= 290);
    if(x >= 130 && x <= 170 && y >= 250 && y <= 290);
    if(x >= 210 && x <= 250 && y >= 290 && y <= 350);
    if(x >= 290 && x <= 350 && y >= 290 && y <= 350){
    setBackground(Color.green);
    message = "Winner";
    pawncount = 14;
    repaint();
    //required for the interface
    public void mouseClicked(MouseEvent event){}
    public void mouseReleased(MouseEvent event){}
    public void mouseEntered(MouseEvent event){}
    public void mouseExited(MouseEvent event){}
    public void drawBox(Graphics g){
         for(int i=10;i<=350;i+=40){
    g.drawLine(i,10,i,330);
    g.drawLine(10,i,330,i);
    }

    Since your code is heavilly dependant on which square is clicked on I'd define a class extending JComponent to represent a square. You can make this an inner class, which would simplify access to other squares etc. Then lay these out in your JPanel, and each will have it's own paint method which will paint it with or without a pawn.
    At the same time you add all these as a two dimensional array for logical access. Each square has (or is) it's own mouseListener so that you can let awt figure out which you clicked on.
    private static final int CELL_SIZE=50;
    private static final int BOARD_SIZE= 8;
    private class Square extends JComponent implements MouseListener {
        public boolean hasPawn;
        private Square(int row, int col) {
             Rectangle where = new Rectangle(col * CELL_SIZE, row * CELL_SIZE,
    CELL_SIZE, CELL_SIZE);
            setBounds(where);
           addMousListener(this);
       public void addPawn() {
         if(!hasPawn) {
           hasPawn = true;
           repaint();
      public void paint(Graphics g) {
    } // end of inner class
    Square[][]board = new Square[BOARD_SIZE][BOARD_SIZE];}

  • Newbie - help needed with array and dictionary objects

    Hi all
    Please see the code below. I've posted this code in another thread however the original issue was resolved and this is now a new issue I'm having although centered around the same code.
    The issue is that I'm populating an array with dictionary objects. each dictionary object has a key and it's value is another array of custom objects.
    I've found that the code runs without error and I end up with my array as I'm expecting however all of the dictionary objects are the same.
    I assume it's something to do with pointers and/or re-using the same objects but i'm new to obj-c and pointers so i am a bit lost.
    Any help again is very much appreciated.
    // Open the database connection and retrieve minimal information for all objects.
    - (void)initializeDatabase {
    NSMutableArray *authorArray = [[NSMutableArray alloc] init];
    self.authors = authorArray;
    [authorArray release];
    // The database is stored in the application bundle.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"books.sql"];
    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
    // Get the primary key for all books.
    const char *sql = "SELECT id, author FROM author";
    sqlite3_stmt *statement;
    // Preparing a statement compiles the SQL query into a byte-code program in the SQLite library.
    // The third parameter is either the length of the SQL string or -1 to read up to the first null terminator.
    if (sqlite3preparev2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
    // We "step" through the results - once for each row.
    // We start with Letter A...we're building an A - Z grouping
    NSString *letter = @"A";
    NSMutableArray *tempauthors = [[NSMutableArray alloc] init];
    while (sqlite3_step(statement) == SQLITE_ROW) {
    author *author = [[author alloc] init];
    author.primaryKey = sqlite3columnint(statement, 0);
    author.title = [NSString stringWithUTF8String:(char *)sqlite3columntext(statement, 0)];
    // FOLLOWING WAS LEFT OVER FROM ORIGINAL COMMENTS IN SQLBooks example....
    // We avoid the alloc-init-autorelease pattern here because we are in a tight loop and
    // autorelease is slightly more expensive than release. This design choice has nothing to do with
    // actual memory management - at the end of this block of code, all the book objects allocated
    // here will be in memory regardless of whether we use autorelease or release, because they are
    // retained by the books array.
    // if the author starts with the Letter we currently have, add it to the temp array
    if ([[author.title substringToIndex:1] compare:letter] == NSOrderedSame){
    [tempauthors addObject:author];
    } // if this is different letter, then we need to deal with that too...
    else {
    // create a dictionary to store the current tempauthors array in...
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
    // add the dictionary to our appDelegate-level array
    [authors addObject:tempDictionary];
    // now prepare for the next loop...
    // set the new letter...
    letter = [author.title substringToIndex:1];
    // remove all of the previous authors so we don't duplicate...
    [tempauthors removeAllObjects];
    // add the current author as this was the one that didn't match the Letter and so
    // never went into the previous array...
    [tempauthors addObject:author];
    // release ready for the next loop...
    [author release];
    // clear up the remaining authors that weren't picked up and saved in the "else" statement above...
    if (tempauthors.count > 0){
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
    [authors addObject:tempDictionary];
    else {
    printf("Failed preparing statement %s
    ", sqlite3_errmsg(database));
    // "Finalize" the statement - releases the resources associated with the statement.
    sqlite3_finalize(statement);
    } else {
    // Even though the open failed, call close to properly clean up resources.
    sqlite3_close(database);
    NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
    // Additional error handling, as appropriate...
    Message was edited by: dotnetter

    Ok, so I know what the issue is now...I just don't know enough to be able to resolve it!
    it's the tempAuthors objects.
    It's an NSMutableArray which is create on the line before the start of the WHILE loop.
    Having looked through the debugger, I can see that each dictionary object is created (with different codes which I assume are memory addresses) so all is well there. However, on each iteration of the loop in the middle there is an IF...ELSE... statement which in the ELSE section is clearing all objects from the tempAuthors array and beginning to repopulate it again.
    Looking at the containing dictionary objects in the debugger I can see that the tempAuthors object that each contains has the same code (again, I'm assuming this is a memory address) - so if I understand correctly, it's the same object...I assumed that when I created the dictionary using the dictionWithObject call that I would be passing in a copy of the object, but it's referencing back to the object which I then go on to change.
    Assuming the above is correct, I've tried several "stabs in the dark" at fixing it.
    I've tried relasing the tempAuthors object within the ELSE and initialising it again via an alloc...init - but this didn't work and again looking through the debugger it looks as though it was confused as to which object it was supposed to be using on the following iteration of the WHILE loop (it tried to access the released object).
    Having read a little more about memory management can someone tell me if I'm correct in saying that the above is because the tempAuthors object is declare outside the scope of the WHILE loop yet I then try to re-instantiate it within the loop (does that make sense???).
    Sorry for the long post...the more I can understand the process the less I can hopefully stop relying on others for help so much.
    I am continuing to read up on memory management etc but just not there yet.
    Regards
    Wayne

Maybe you are looking for