Help with Integer.toString or casting

I'm kinda new to this java stuff. I'm trying to pass information from stockReturnNumber to a string variable called stringHolder. This method is declared as a void. Is that part of the problem? What can i do to convert stockReturnNumber to a string?
Thank you
nick
void enterSampleData()
int stockElement = 0;
int stockHigh = 1;
int stockReturnNumber = 0;
String stringHolder;
while(stockElement < stockElementCounter)
while(stockHigh<=181)
stringHolder = Integer.toString(stockReturnNumber); // <-- program will not go beyond here
stockNames[stockElement][stockHigh] = stringHolder;
stockHigh++;
stockReturnNumber++;
stockElement++;
}

Here is some more information that i did not tell you about before.
i'm using NetBeans IDE 3.6 for my debugger... When i run the program
i have it run all the way and have it stop just before it tries to convert
the string and have it step into the
stringHolder = String.valueOf(stockReturnNumber);
The error message has a caption in the box that says
"Question"
then the error message says..
"Debugger has been stopped at
java.lang.String.valueOf, line 2236.
Source of class has not been found in mounted filesystems.
select an action that will be performed upon stepping
into a method without source:
Stop
Step out
Stop at the first line with source
I declared at the begining of the program
#import java.lang.*;
is there any thing else i have to do to make sure that the
source class is available? I know that i'm successfuly
declareing string variables cause i have been able to add
strings into it from a file in a previous method.
Thanks for helping me out with this. I really appreciate it.

Similar Messages

  • Please help with integer variable matching frame numbers

    hi :-) , could someone please hepl a newbie ?
    I am trying to write a short AS3 script in CS4 that allows me to step backwards and forwards  through an animation.
    I have a stop button a play button , rewind button and a forward button.
    the buttons work ok apart from when I hit the rewind button sometimes it jumps to the start of the timeline rather than just step back a frame at a time.
    when I use the stop button and the timeline stops where it is, the rewind button steps back as required. but, if the rewind button is clicked first it jumps to the start of the timeline, I know the theory as to why I cant get this to work.  I need to know how to increment an integer variable (counter) to increment as the animation playes. i.e. the counter variable to match the frame number.  below is the code I have, could someone please tell me how to match an integer variable to the current frame and tell me where to insert the line of code on the listing. I have added a dummy line or psuedo line of code to show what I am trying to do, but the syntax is wrong .
    var counter = 1;
    gotoAndStop(counter);
    function setupevents()
        buttonplay.addEventListener(MouseEvent.CLICK, playbutton);
        buttonstop.addEventListener(MouseEvent.CLICK, stopbutton);
        buttonrewind.addEventListener(MouseEvent.CLICK, rewindbutton);
        buttonforward.addEventListener(MouseEvent.CLICK, forwardbutton);
    setupevents();
    //this is the dummy or psuedo line of code i mentioned in the question above....
    counter = frame;
    //function to play the movie
    function playbutton(event:MouseEvent)
        play();
    //function to stop the movie using the stop button
    function stopbutton(event:MouseEvent)
        stop();
    //function to step backwards through movie using the rewind button
    function rewindbutton(event:MouseEvent)
        if(counter > 1)
            counter = counter - 1
        gotoAndStop(counter);
    //function to step forward through movie using the forward button. I have used the value of 60 as this is the amount of frames in the timeline
    //I dont know if this is correct way to do things or not
    function forwardbutton(event:MouseEvent)
        if(counter < 60)
            counter = counter + 1
        gotoAndStop(counter);
    I know the code is rough and basic but any help would be greatly appreciated, I have tried to attach the .fla file for anyone who needs more info on this.  But this webpage returned an error "The content type of this attachment is not allowed."
    Auldy66

    var counter = 1;
    gotoAndStop(counter);
    function setupevents()
        buttonplay.addEventListener(MouseEvent.CLICK, playbutton);
        buttonstop.addEventListener(MouseEvent.CLICK, stopbutton);
        buttonrewind.addEventListener(MouseEvent.CLICK, rewindbutton);
        buttonforward.addEventListener(MouseEvent.CLICK, forwardbutton);
    setupevents();
    //this is the dummy or psuedo line of code i mentioned in the question above....
    counter = frame;
    //function to play the movie
    function playbutton(event:MouseEvent)
        play();
    //function to stop the movie using the stop button
    function stopbutton(event:MouseEvent)
        stop();
    //function to step backwards through movie using the rewind button
    function rewindbutton(event:MouseEvent)
    prevFrame();
    function forwardbutton(event:MouseEvent)
    nextFrame();

  • Please Help with Integer type

    Hello, all!
    Please help!
    Please take a look to this code. Why 3rd string is not in the output but №5 does?
    public static void main (String [] args) {
            Integer x = new Integer(10);
            Integer y = new Integer(10);
            if (x==10)
                System.out.println("1. x=10");
            if (y==10)
                System.out.println("2. y=10");
            if (x==y)
                System.out.println("3. x=y");
            if (x.equals(y))
                System.out.println("4. x.equals(y)");
            x=10;
            y=10;
            if (x==y)
                System.out.println("5. x=y");
        }Results
    1. x=10
    2. y=10
    4. x.equals(y)
    5. x=y

    Sorry!
    how i can replace this thread to category: Java Essentials
    and take a look at this code and results
    public static void main (String [] args) {       
            Integer x1;
            Integer y1;
            Integer a;
            a = new Integer(127);
            x1 = a.intValue();
            y1 = a.intValue();       
            System.out.println("x1==y1 " + (x1==y1));
            System.out.println("x1.equals(y1) " + (x1.equals(y1)));
            a = new Integer(128);
            x1 = a.intValue();
            y1 = a.intValue();
            System.out.println("x1==y1 " + (x1==y1));
            System.out.println("x1.equals(y1) " + (x1.equals(y1)));
        }results
    x1==y1 true
    x1.equals(y1) true
    x1==y1 false
    x1.equals(y1) true

  • Help with Integer

    The following code gives me this error.... what should I do to resolve this problem?
    Thanks.
    Pier.
    --------------------------- Compiler Output ---------------------------
    Widget.java:38: cannot resolve symbol
    symbol : constructor Integer (Widget)
    location: class java.lang.Integer
              int hc = (new Integer(this)).hashCode();
    ^
    Widget.java:41: cannot resolve symbol
    symbol : constructor Integer (Widget)
    location: class java.lang.Integer
                   hc += (new Integer(tw.w)).hashCode();
    ^
    2 errors
    import java.lang.Integer.*;
    class Widget implements Cloneable {
         int n;
         Widget w;
         Widget(int n) {this.n = n;
         public Object clone() throws CloneNotSupportedException {
              Widget newWidget = new Widget(this.n);
              Widget y = newWidget;
              Widget t = this.w;
              while (t != null) {
                   y.w = new Widget(t.n);
                   y = y.w;
                   t = t.w;
         return newWidget;
         public boolean equals(Object object) {
              if (object == this) return true;
              if (object.getClass() != this.getClass()) return false;
              Widget y = (Widget)object;
              Widget t = this;
              while (y != null || t != null)  {
                   if (y == null || t == null) return false;
                   if (y.n != t.n) return false;
                   y = y.w;
                   t = t.w;
              return true; // if all the tests prove true
         public int hashCode() {
              int hc = (new Integer(this)).hashCode();
              Widget tw = this.w;
              while (tw != null) {
                   hc += (new Integer(tw.w)).hashCode();
                   tw = tw.w;
         return hc;
    class testDriver  {
         public static void main(String args[]) {
              Widget x = new Widget(66);
              Widget y = new Widget(66);
              System.out.println(x.equals(y));

    Change your hashCode() method to look like this:public int hashCode() {
         int hc = Integer.parseInt(new Integer(this.hashCode()).toString());
         Widget tw = this.w;
         while (tw != null) {
              hc += Integer.parseInt(new Integer(tw.w.hashCode()).toString());
              tw = tw.w;
         return hc;
    }The way you have it coded, you are producing Integer
    objects which are not the same as int's.
    Mark

  • Apache Compilation Problem: makes pointer from integer without a cast -HELP

    Every time I try to compile apache with ssl I get this error message below. I'm pulling my hair out over it! I've installed current versions of gcc, libgcc, glib, make, m4, & flex.. which havent helped. I am running Solaris 9 sparc.
    I'm honestly baffled by this error and have found no help on the web. Does anyone know what I need to do in order to fix this? Any specific libraries I need to install etc??
    <apache compiles up to this point>
    gcc -c -I../../os/unix -I../../include -DSOLARIS2=290 -DMOD_SSL=208116 -DEAPI -DUSE_EXPAT -I../../lib/expat-lite `../../apaci` -fPIC -DSHARED_MODULE -DSSL_COMPAT -DSSL_ENGINE -I/tmp/web/sweeney/Third_Party/apache/openssl-0.9.7d/include -DMOD_SSL_VERSION=\"2.8.16\" ssl_expr_scan.c && mv ssl_expr_scan.o ssl_expr_scan.lo
    lex.ssl_expr_yy.c:1900: parse error before numeric constant
    lex.ssl_expr_yy.c: In function `ssl_expr_yy_scan_string':
    lex.ssl_expr_yy.c:1901: number of arguments doesn't match prototype
    lex.ssl_expr_yy.c:293: prototype declaration
    lex.ssl_expr_yy.c:1903: warning: passing arg 1 of `strlen' makes pointer from integer without a cast
    lex.ssl_expr_yy.c:1903: warning: passing arg 1 of `ssl_expr_yy_scan_bytes' makes pointer from integer without a cast
    make[4]: *** [ssl_expr_scan.lo] Error 1
    make[3]: *** [all] Error 1
    make[2]: *** [subdirs] Error 1
    make[2]: Leaving directory `/tmp/apache_1.3.29/src'
    make[1]: *** [build-std] Error 2
    make[1]: Leaving directory `/tmp//apache_1.3.29'
    make: *** [build] Error 2
    they key being, "makes pointer from integer without a cast"
    Help me Obi Wan Kenobi, you're my only hope! Thank you much!

    I retried, here is the screen output:
    util.c: In function `ap_find_token':
    util.c:1367: error: `test_char_table' undeclared (first use in this function)
    util.c:1367: error: (Each undeclared identifier is reported only once
    util.c:1367: error: for each function it appears in.)
    util.c:1367: error: `T_HTTP_TOKEN_STOP' undeclared (first use in this function)
    util.c: In function `ap_escape_logitem':
    util.c:1444: error: `test_char_table' undeclared (first use in this function)
    util.c:1444: error: `T_ESCAPE_LOGITEM' undeclared (first use in this function)
    util.c: In function `ap_escape_errorlog_item':
    util.c:1496: error: `test_char_table' undeclared (first use in this function)
    util.c:1496: error: `T_ESCAPE_LOGITEM' undeclared (first use in this function)
    util.c: In function `ap_escape_shell_cmd':
    util.c:1567: error: `test_char_table' undeclared (first use in this function)
    util.c:1567: error: `T_ESCAPE_SHELL_CMD' undeclared (first use in this function)
    util.c: In function `ap_escape_path_segment':
    util.c:1671: error: `test_char_table' undeclared (first use in this function)
    util.c:1671: error: `T_ESCAPE_PATH_SEGMENT' undeclared (first use in this function)
    util.c: In function `ap_os_escape_path':
    util.c:1700: error: `test_char_table' undeclared (first use in this function)
    util.c:1700: error: `T_OS_ESCAPE_PATH' undeclared (first use in this function)
    *** Error code 1
    make: Fatal error: Command failed for target `util.o'
    Current working directory /source/apache_1.3.33/src/main
    *** Error code 1
    make: Fatal error: Command failed for target `subdirs'
    Current working directory /source/apache_1.3.33/src
    *** Error code 1
    make: Fatal error: Command failed for target `build-std'
    Current working directory /source/apache_1.3.33/
    *** Error code 1
    make: Fatal error: Command failed for target `build'
    Current working directory /appl/apa_ssl/apache_1.3.33/src
    *** Error code 1
    make: Fatal error: Command failed for target `build-std'
    Current working directory /appl/apa_ssl/apache_1.3.33
    *** Error code 1
    make: Fatal error: Command failed for target `build'
    root@host #
    the include-line in util.c is:
    #include "test_char.h" (vi: line 43)
    file exists:
    -rw-r--r-- 1 root other 0 Nov 8 16:02 test_char.h
    but, as you can see, it is empty

  • Trouble with primitive arrays and casting, lesson 521

    hi everyone!
    there is a problem i discovered right now - after years with java where was no necessity to do this.....
    and i'm shure this must have been the topic already, but i couldn't find any helpful resource :-/
    right here we go:
    1. an array is a (special) kind of object.
    2. there are "primitive" arrays and such containing references to objects. of course - and i imagine why - they are treated differently by the VM.
    3. then both are - somehow - subclasses of Object. whereas primitive types are not really, primitive-arrays are. this is hidden to the programmer....
    4. any array can be "pointed" at via local Object variable, like this:
    Object xyz = new int[6];
    5. arrays of Objects (with different dimensions) can be casted, like this:
      Object pointer = null;
      Object[]   o  = new SomeClass[42] ;
      Object[][] oo = new OtherClass[23] [2] ;
      Object[][][] ooo = new OtherClass[23] [2] [9] ;
      o = oo = ooo;     // this is save to do,
                                   //because "n-dimensional" object-arrays
                                  // are just arrays of  other arrays, down to simple array
    pointer = o;         // ok, we are referencing o via Object "pointer"6. but, you cannot do this with primitive types:
      int[]  i1 = new int [99] ;
      int[][] i2 = new int [1] [3] ;
      i1 = i2                  // terror: impossible. this is awful, if you ask me.
                                   // ok, one could talk about "special cases" and
                                   // "the way the VM works", but this is not of interest to me as
                                   // a programmer. i'm not happy with that array-mess!
      pointer = i2;       // now this is completely legal. i2, i1 etc is an object!7. after the preparation, let's get into my main trouble (you have the answer, i know!) :
    suppose i have a class, with methods that should process ANY kind of object given. and - i don't know which. i only get it at runtime from an unknown source.
    let's say: public void BlackBox( Object x );
    inside, i know that there might be regular objects or arrays, and for this case i have some special hidden method, just for arrays... now try to find it out:
    public void BlackBox( Object x )
      if ( x == null)
           return;
       Class c = x.getClass();
       if ( c.isArray() )
              // call the array method if it's an array.........
              BlackBoxes(     (Object [] )  x );         // wait: this is a cast! and it WILL throw an exception, eventually!
              return;
       else
               DoSpecialStuffWith( x );
    }ok ? now, to process any kind of array, the special method you cannot reach from outside:
    private void BlackBoxes( Object[] xs )
       if ( xs != null )
            for ( Object x : xs )
                 BlackBox( x );
    // this will end up in some kind of recursion with more than one array-dimension, or when an Object[] has any other array as element!this approach is perfectly save when processing any (real) Object, array or "multi-dimensional" arrays of Objects.
    but, you cannot use this with primitive type arrays.
    using generics wouldn't help, because internally it is all downcasted to Object.
    BlackBox( new Integer(3) ) ---- does work, using a wrapper class
    BlackBox( new Integer[3] ) ----- yep!
    BlackBox( 3 ) ---- even this!
    BlackBox( new int[42] ) ---- bang! ClassCastException, Object[] != int[]
    i'm stuck. i see no way to do this smoothly. i could write thousands of methods for each primitive array - BlackBox( int[] is ) etc. - but this wouldn't help. because i can't cast an int[][] to int[], i would also have to write countless methods for each dimension. and guess, how much there are?
    suppose, i ultimately wrote thousands of possible primitive-type methods. it would be easy to undergo any of it, writing this:
    BlackBox( (Object) new int[9] [9] );
    the method-signature would again only fit to my first method, so the whole work is useless. i CAN cast an int[] to Object, but there seems no convenient way to get the real array out of Object - in a generic way.
    i wonder, how do you write a serialisation-engine? and NO, i can't rely on "right usage" of my classes, i must assume the worst case...
    any help appreciated!

    thanks, brigand!
    your code looks weird to me g and i think there's at least one false assumption: .length of a multidimensional array returns only the number of "top-level" subarrays. that means, every length of every subarray may vary. ;)
    well i guess i figured it out, in some way:
    an int is no Object;
    int[ ] is an Object
    the ComponentType of int [ ] is int
    so, the ComponentType of an Object int[ ] is no Object, thus it cannot be casted to Object.
    but the ComponentType of int [ ] [ ] IS Object, because it is int [ ] !
    so every method which expects Object[], will work fine with int[ ] [ ] !!
    now, you only need special treatment for 1-dimensional primitive arrays:
    i wrote some code, which prints me everything of everything:
        //this method generates tabs for indentation
        static String Pre( int depth)
             StringBuilder pre = new StringBuilder();
             for ( int i = 0; i < depth; i++)
                  pre.append( "\t" );
             return pre.toString();
        //top-level acces for any Object
        static void Print( Object t)
             Print ( t, 0);
        //the same, but with indentation depth
        static void Print( Object t, int depth)
            if ( t != null )
                 //be shure it is treated exactly as the class it represents, not any downcast
                 t = t.getClass().cast( t );
                if ( t.getClass().isArray() )
                     //special treatment for int[]
                     if ( t instanceof int[])
                          Print( (int[]) t, depth);
                     // everything else can be Object[] !
                     else
                          Print( (Object[]) t, depth );
                     return;
                else
                    System.out.println( Pre(depth) + " [ single object:] " + t.toString() );
            else
                System.out.println( Pre(depth) + "[null!]");
        // now top-level print for any array of Objects
        static void Print( Object [] o)
             Print( o, 0 );
        // the same with indentation
        static void Print( Object [] o, int depth)
            System.out.println( Pre(depth) + "array object " + o.toString() );
            for ( Object so : o )
                    Print( so, depth + 1 );
        //the last 2 methods are only for int[] !
        static void Print( int[] is)
             Print( is, 0 );
        static void Print( int[] is, int depth)
            System.out.println( Pre(depth) + "primitive array object " + is.toString() );
            // use the same one-Object method as every other Object!
            for ( int i : is)
                 Print ( i, depth + 1 );
            System.out.println( "-----------------------------" );
        }now, calling it with
    Print ( (int) 4 );
    Print ( new int[] {1,2,3} );
    Print( new int[][] {{1,2,3}, {4,5,6}} );
    Print( new int[][][] {{{1,2,3}, {4,5,6}} , {{7,8,9}, {10,11,12}}, {{13,14,15}, {16,17,18}} } );
    Print( (Object) (new int[][][][] {{{{99}}}} ) );
    produces this fine array-tree:
    [ single object:] 4
    primitive array object [I@9cab16
          [ single object:] 1
          [ single object:] 2
          [ single object:] 3
    array object [[I@1a46e30
         primitive array object [I@3e25a5
               [ single object:] 1
               [ single object:] 2
               [ single object:] 3
         primitive array object [I@19821f
               [ single object:] 4
               [ single object:] 5
               [ single object:] 6
    array object [[[I@addbf1
         array object [[I@42e816
              primitive array object [I@9304b1
                    [ single object:] 1
                    [ single object:] 2
                    [ single object:] 3
              primitive array object [I@190d11
                    [ single object:] 4
                    [ single object:] 5
                    [ single object:] 6
         array object [[I@a90653
              primitive array object [I@de6ced
                    [ single object:] 7
                    [ single object:] 8
                    [ single object:] 9
              primitive array object [I@c17164
                    [ single object:] 10
                    [ single object:] 11
                    [ single object:] 12
         array object [[I@1fb8ee3
              primitive array object [I@61de33
                    [ single object:] 13
                    [ single object:] 14
                    [ single object:] 15
              primitive array object [I@14318bb
                    [ single object:] 16
                    [ single object:] 17
                    [ single object:] 18
    array object [[[[I@ca0b6
         array object [[[I@10b30a7
              array object [[I@1a758cb
                   primitive array object [I@1b67f74
                         [ single object:] 99
    -----------------------------and i'll have to write 8 methods or so for every primitive[ ] type !
    sounds like a manageable effort... ;-)

  • Help with getting Images to show in a Rock, Paper, Scissors game

    Hi
    I am working on this Rock, paper, scissors java game and the program works, but I can not figure out how to get the images to load onto the program. So my question is how do I get the images to load up with the program? I am using JCreator for this project. I have created the Basic Java Application project, and then added in the 3 .java files that I need to run the program, but I just can not figure out how or where I need to upload the files. The game works without the images, but I would really like them to show up.
    This is the .java file that calls up the images:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class pss extends JPanel implements ActionListener, ItemListener
    private final Color clrBackground = new Color(163,243,255);
    private final Color clrForeground = new Color(0,0,0);
    private JComboBox cboxWeapon;
    private JTextField txtCPUWeapon, txtWins, txtLoses, txtDraws;
    private JLabel lblPlayerWeapon, lblCPUWeapon, lblWins, lblLoses, lblDraws, lblStatus, lblPlayerWeaponIcon, lblCPUWeaponIcon;
    private JButton cmdPlay, cmdReset;
    private ImageIcon[] imgWeapon;
    private JPanel panRoot, panPlayerArea, panPlayerWeapon, panCPUArea, panCPUWeapon, panStatusArea, panGo, panCounters, panWins, panLoses, panDraws;
    private pssEngine engine = new pssEngine();
    private objCreateAppletImage createImage = new objCreateAppletImage();
    private boolean errorWithImages = false;
    public static void main(String[] args) //With applications, you have to specify a main method (not with applets)
    JFrame.setDefaultLookAndFeelDecorated(true); //Make it look nice
    JFrame frame = new JFrame("Paper Stone Scissors"); //Title
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false); //Stops the user resizing the window
    JComponent paneMain = new pss();
    paneMain.setOpaque(true);
    paneMain.setPreferredSize(new Dimension(420,350));
    frame.setContentPane(paneMain);
    frame.pack();
    frame.setVisible(true);
    public pss ()
    cboxWeapon = new JComboBox(engine.getWeapon());
    cboxWeapon.addItemListener(this);
    txtCPUWeapon = new JTextField(engine.getStrCPUWeapon(), 5);
    txtWins = new JTextField("0", 5);
    txtLoses = new JTextField("0", 5);
    txtDraws = new JTextField("0", 5);
    txtCPUWeapon.setEditable(false);
    txtWins.setEditable(false);
    txtLoses.setEditable(false);
    txtDraws.setEditable(false);
    lblPlayerWeapon = new JLabel("Choose your weapon", JLabel.CENTER);
    lblCPUWeapon = new JLabel("The CPU's weapon", JLabel.CENTER);
    lblWins = new JLabel("Amount of wins:", JLabel.RIGHT);
    lblLoses = new JLabel("Amount of loses:", JLabel.RIGHT);
    lblDraws = new JLabel("Amount of Drawss:", JLabel.RIGHT);
    lblStatus = new JLabel("", JLabel.CENTER);
    lblPlayerWeaponIcon = new JLabel("", JLabel.CENTER);
    lblCPUWeaponIcon = new JLabel("", JLabel.CENTER);
    lblPlayerWeaponIcon.setPreferredSize(new Dimension(150,150));
    lblCPUWeaponIcon.setPreferredSize(new Dimension(150,150));
    cmdPlay = new JButton("Go!");
    cmdReset = new JButton("Restart");
    cmdPlay.addActionListener(this);
    cmdReset.addActionListener(this);
    try
    imgWeapon = new ImageIcon[3];
    for (int i = 0; i < 3; i++)
    imgWeapon[i] = createImage.getImageIcon(this, ".src/images/" + engine.getWeapon(i) + ".gif", "Icon for " + engine.getWeapon(i), 13000);
    lblPlayerWeaponIcon.setIcon(imgWeapon[0]);
    lblCPUWeaponIcon.setIcon(imgWeapon[0]);
    catch (Exception ex) //The game works without the images, so carry on
    errorWithImages = true;
    setLayout(new BorderLayout());
    panRoot = new JPanel(new BorderLayout());
    panPlayerArea = new JPanel(new BorderLayout());
    panPlayerWeapon = new JPanel(new BorderLayout());
    panCPUArea = new JPanel(new BorderLayout());
    panCPUWeapon = new JPanel(new BorderLayout());
    panStatusArea = new JPanel(new BorderLayout());
    panGo = new JPanel();
    panCounters = new JPanel(new GridLayout(3,1,2,2));
    panWins = new JPanel();
    panLoses = new JPanel();
    panDraws = new JPanel();
    add(panRoot, BorderLayout.CENTER);
    panRoot.add(panPlayerArea, BorderLayout.WEST);
    panPlayerArea.add(panPlayerWeapon, BorderLayout.NORTH);
    panPlayerWeapon.add(lblPlayerWeapon, BorderLayout.NORTH);
    panPlayerWeapon.add(cboxWeapon, BorderLayout.SOUTH);
    panPlayerArea.add(lblPlayerWeaponIcon, BorderLayout.SOUTH);
    panRoot.add(panCPUArea, BorderLayout.EAST);
    panCPUArea.add(panCPUWeapon, BorderLayout.NORTH);
    panCPUWeapon.add(lblCPUWeapon, BorderLayout.NORTH);
    panCPUWeapon.add(txtCPUWeapon, BorderLayout.SOUTH);
    panCPUArea.add(lblCPUWeaponIcon, BorderLayout.SOUTH);
    panRoot.add(panStatusArea, BorderLayout.SOUTH);
    panStatusArea.add(panGo, BorderLayout.NORTH);
    panGo.add(cmdPlay);
    panGo.add(cmdReset);
    panGo.add(lblStatus);
    panStatusArea.add(panCounters, BorderLayout.SOUTH);
    panCounters.add(panWins);
    panWins.add(lblWins);
    panWins.add(txtWins);
    panCounters.add(panLoses);
    panLoses.add(lblLoses);
    panLoses.add(txtLoses);
    panCounters.add(panDraws);
    panDraws.add(lblDraws);
    panDraws.add(txtDraws);
    panRoot.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    setBackground(clrBackground);
    panRoot.setBackground(clrBackground);
    panPlayerArea.setBackground(clrBackground);
    panPlayerWeapon.setBackground(clrBackground);
    panCPUArea.setBackground(clrBackground);
    panCPUWeapon.setBackground(clrBackground);
    panStatusArea.setBackground(clrBackground);
    panGo.setBackground(clrBackground);
    panCounters.setBackground(clrBackground);
    panWins.setBackground(clrBackground);
    panLoses.setBackground(clrBackground);
    panDraws.setBackground(clrBackground);
    lblPlayerWeapon.setForeground(clrForeground);
    lblCPUWeapon.setForeground(clrForeground);
    lblWins.setForeground(clrForeground);
    lblLoses.setForeground(clrForeground);
    lblDraws.setForeground(clrForeground);
    txtWins.setForeground(clrForeground);
    txtLoses.setForeground(clrForeground);
    txtDraws.setForeground(clrForeground);
    txtCPUWeapon.setForeground(clrForeground);
    public void reset ()
    cboxWeapon.setSelectedIndex(0);
    lblStatus.setText("");
    engine.reset();
    public void actionPerformed (ActionEvent e)
    if (e.getSource() == cmdReset)
    reset();
    else
    lblStatus.setText(engine.play(cboxWeapon.getSelectedIndex()));
    txtCPUWeapon.setText(engine.getStrCPUWeapon());
    txtWins.setText(Integer.toString(engine.getWins()));
    txtLoses.setText(Integer.toString(engine.getLoses()));
    txtDraws.setText(Integer.toString(engine.getDraws()));
    if (!errorWithImages)
    lblCPUWeaponIcon.setIcon(imgWeapon[engine.getCPUWeapon()]);
    public void itemStateChanged (ItemEvent e)
    if (!errorWithImages)
    lblPlayerWeaponIcon.setIcon(imgWeapon[cboxWeapon.getSelectedIndex()]);
    }Here is the other .java file that calls on the Images:
    import java.awt.*;
    import java.io.*;
    import javax.swing.ImageIcon;
    public class objCreateAppletImage
    public void objCreateAppletImage ()
    //If an error occurs (or is thrown by me) it will be thrown to the next level up, and either caught or thrown
    public ImageIcon getImageIcon (Object parentClass, String path, String description, int fileSize) throws Exception
    int count = 0;
    BufferedInputStream imgStream = new BufferedInputStream(parentClass.getClass().getResourceAsStream(path));
    byte buff[] = new byte[fileSize];
    if (imgStream == null) //If doesn't exist
    throw new Exception("File not Found");
    try
    count = imgStream.read(buff);
    imgStream.close(); //Closes the stream
    catch (IOException ex)
    throw new Exception("Corrupt file");
    return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buff), description); //Creates the image from the byte array
    }Could someone please help me? I really have no idea and I would like this to work.
    Thank you
    Frank

    Oh, thank you. I will not do that in the future.
    I am not entirely sure how I would use the getImage method in an Applet. I would prefer to just use the code that I have currently, unless the addition of making the program an Applet only adds a small amount of code. But then even still, I am not entirely sure what I would write in the .class file to make the images load. And then I would not really know how to properly incorporate the pss.java file and the .class file together so they read off of each other.

  • URGENT!!! Need help with drawImage program.

    Hi...,
    This is my first time dealing with drawImage. This is my program:
    public void init ()
    img=getImage (getDocumentBase (), "knight.gif");
    do
    row=Integer.parseInt (JOptionPane.showInputDialog ("Enter starting row: "));
    while (row<1 || row>8);
    do
    col=Integer.parseInt (JOptionPane.showInputDialog ("Enter starting col: "));
    while (col<1 || col>8);
    moves=1;
    board=new int[9][9];
    public void paint (Graphics g)
    createBoard (g);
    if (checkPos (col+1, row+1))
    board[row][col]=moves;
    g.drawImage (img, col*50, row*50, this);
    g.drawString (Integer.toString(moves), ((col*50)+25), ((row*50)+25));
    moves++;
    makeMove ();
    I just include these 2 mehtods because there is something wrong when I execute this. In the paint method, I only do the drawImage once, but I don't know why it draws twice when I execute it. And when I put the "g.drawImage" line in comment, it's doing ok.
    I hope you guys understand me.
    Please help me. Thx

    Hi JeroenBoven,
    Thanks for your help. But, this is what I put in the createBoard method.
    private void createBoard (Graphics g)
              g.setColor (Color.black);
              for (int l=1; l<=9; l++)
                   g.drawLine (50*l, 50, 50*l, 450);
                   g.drawLine (50, 50*l, 450, 50*l);
    From what I think, the createBoard only drawLines and make a 8 * 8 board.

  • Please help with newline non-printing character in JTextPane.

    Hi.
    I need to implement "View non-printing characters" feature in my JTextPane.
    So when this feature is toggled, the newline character is displayed at the end of every line like in Microsot Word editor.
    I been digging around for few hours now and I cant find a solution for this.
    Please help me with any tips guys.

    StanislavL:
    ok i digged around and i found code example... i got my code to show "X" at the end of every line as a newline character. here is code I used:
    import javax.swing.text.StyledEditorKit;
    import javax.swing.text.ViewFactory;
    import javax.swing.text.Element;
    import javax.swing.text.View;
    import javax.swing.text.AbstractDocument;
    import javax.swing.text.LabelView;
    import javax.swing.text.IconView;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.ComponentView;
    import javax.swing.text.BoxView;
    import java.awt.Graphics;
    import java.awt.Shape;
    import java.awt.Rectangle;
    class MyEditorKit extends StyledEditorKit
         public ViewFactory getViewFactory()
              return new MyRTFViewFactory();
    class MyRTFViewFactory implements ViewFactory
         public View create(Element elem)
              String kind = elem.getName();
              if (kind != null)
                   if (kind.equals(AbstractDocument.ContentElementName)) {
              return new LabelView(elem);
                   } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
    //              return new ParagraphView(elem);
                        return new MyParagraphView(elem);
                   } else if (kind.equals(AbstractDocument.SectionElementName)) {
    //              return new BoxView(elem, View.Y_AXIS);
                        return new MySectionView(elem, View.Y_AXIS);
                   } else if (kind.equals(StyleConstants.ComponentElementName)) {
                        return new ComponentView(elem);
                   } else if (kind.equals(StyleConstants.IconElementName)) {
                        return new IconView(elem);
                   // default to text display
                   return new LabelView(elem);
    class MySectionView extends BoxView {
         public MySectionView(Element e, int axis)
              super(e,axis);
         public void paintChild(Graphics g,Rectangle r,int n) {
              if (n>0) {
                   MyParagraphView child=(MyParagraphView)this.getView(n-1);
                   int shift=child.shift+child.childCount;
                   MyParagraphView current=(MyParagraphView)this.getView(n);
                   current.shift=shift;
              super.paintChild(g,r,n);
    class MyParagraphView extends javax.swing.text.ParagraphView
         public int childCount;
         public int shift=0;
         public MyParagraphView(Element e)
              super(e);
              short top=0;
              short left=20;
              short bottom=0;
              short right=0;
              this.setInsets(top,left,bottom,right);
         public void paint(Graphics g, Shape a)
              childCount=this.getViewCount();
              super.paint (g,a);
              int rowCountInThisParagraph=this.getViewCount(); //<----- YOU HAVE REAL ROW COUNT FOR ONE PARAGRAPH}
              System.err.println(rowCountInThisParagraph);
         public void paintChild(Graphics g,Rectangle r,int n) {
              super.paintChild(g,r,n);
              //g.drawString(Integer.toString(shift+n+1),r.x-20,r.y+r.height-3); // line number
              g.drawString("X",r.x+r.width,r.y+r.height-3);
    }this line here draws "X":
    g.drawString("X",r.x+r.width,r.y+r.height-3);How would I modify this to draw a small picture there?
    Thanx a lot.

  • Need help with constructors

    Here is my InventoryMain.java, Inventory.java, and Maker.java.
    I am having trouble with my constructors in Maker.java. Here is the line (this line is at the bottom of my Maker.java)
    Maker r = new Maker(txtfield1[1].getText(),txtfield1[4].getText(), 0.05, Integer.parseInt(txtfield1[2].getText()), txtfield1[3].getText(), Integer.parseInt(txtfield1[5].getText()),
                   Double.parseDouble(txtfield1[6].getText()));here is my error when compiling:
    symbol : constructor Maker(java.lang.String,java.lang.String,double,int,java.lang.String,int,double)
    location: class inventorymain.Maker
    Maker r = new Maker(txtfield1[1].getText(),txtfield1[4].getText(), 0.05, Integer.parseInt(txtfield1[2].getText()), txtfield1[3].getText(), Integer.parseInt(txtfield1[5].getText()),
    1 error
    BUILD FAILED (total time: 0 seconds)
    I have tried all kinds of different orders trying to match my constructors for Inventory(). Nothing seems to work. Can anyone help????
    InventoryMain.java
    package inventorymain;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.io.IOException;
    import javax.swing.JFrame;
    public class InventoryMain
        // main method begins execution of java application
        public static void main(String[] args)
            //variables
            double restockFee = 0.05;
            //create array for products in inventory
            //enter elements into array
            Maker p = new Maker( 5186521, "pens", 1.59, 346, "Bic", restockFee);
            Maker q = new Maker( 9486452, "pencils", .59, 487,"Mead", restockFee);
            Maker r = new Maker( 6317953, "markers", 1.29, 168,"Sharpie", restockFee);
            Maker s = new Maker( 5152094, "paperclips", 1.19, 136,"Dennison", restockFee);
            Maker t = new Maker( 4896175, "glue", .79, 72,"Elmer's", restockFee);
            Maker u = new Maker( 5493756, "tape", .49, 127,"3m", restockFee);
            Maker v = new Maker( 6537947, "paper", 1.79, 203,"Mead", restockFee);
            Maker w = new Maker( 7958618, "staples", 1.19, 164,"Pentech", restockFee);
            Maker x = new Maker( 5679139, "folders", .49, 238,"Mead", restockFee);
            Maker y = new Maker( 7689110, "rulers", .17, 123,"Stanley", restockFee);       
            p.ShowInventory();
         p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         p.setVisible(true);
         p.setSize(520, 490);
          }//end main
    }//end class Inventory____________________________
    Inventory.java
    package inventorymain; //file assigned to inventorymain package
    import javax.swing.JFrame;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.NumberFormat;
    import javax.swing.border.*;
    import java.net.*;
    import java.util.StringTokenizer;
    public class Inventory extends JFrame
            // set variables
            private Container cp = getContentPane();
            private static int itemNum[] = new int[100];
            private static String name[] = new String[100];
            private static int units[] = new int[100];
            private static double price[] = new double[100];      
            private static int i = 0;
            public Inventory()
                setLayout(new FlowLayout());
            public Inventory(int _itemNum, String _name, double _price, int _units)//varibles for constructor
                itemNum[i] = _itemNum;//variable initialized
                name[i] = _name;//variable initialized
                units[i] = _units;//variable initialized
                price[i] = _price;//variable initialized
                i = i + 1;
            // All setters and getters
            public static int getItemNum(int k)
                return itemNum[k];
            public static String getItemName(int k)
                return name[k];
            public static int getItemUnits(int k)
                return units[k]; 
            public static double getItemPrice(int k)
                return price[k];
            public static void setItemNum(int k, int value)
                itemNum[k] = value;
            public static void setItemName(int k, String value)
                name[k] = value;
            public static void setItemUnits(int k, int value)
                units[k] = value;
            public static void setItemPrice(int k, double value)
                price[k] = value;
            public static void DeleteItem(int k)
                for(int j=k; j<getCount()-1; j++)
                    setItemNum(j, getItemNum(j + 1));
                    setItemName(j,getItemName(j+1));
              setItemUnits(j,getItemUnits(j+1));
              setItemPrice(j,getItemPrice(j+1));
                }//end for
                i-=1;
            }//end DeleteItem
            public static int SearchItem(String value)
                int k = -1;
                for(int j=0;j<getCount();j++)
              if(getItemName(j).equals(value))
                        k = j;
                }//end for
                return k;
         }//end SearchItem
            public  static double totalOfInventory(double p, int u)//computes value of all merchandise in inventory
                return p * u;
            }//end method totalOfInventory
            public static void swap(int j, int min)
                String tmp;
                tmp = name[j];
                name[j] = name[min];
                name[min] = tmp;
                int temp = itemNum[j];
                itemNum[j] = itemNum[min];
                itemNum[min]= temp;
                temp = units[j];
                units[j] = units[min];
                units[min] = temp;
                double temp1 = price[j];
                price[j] = price[min];
                price[min]= temp1;
            }//ends swap method
            public double showTotalOfInventory()
                double totalValue = 0;
                for (int j = 0; j < getCount(); j++)
                    totalValue = totalValue + totalOfInventory(price[j], units[j]);
                return totalValue;
            }//end showTotalOfInventory
            public static int getCount()
                return i;
    }// end class Inventory
    class Products
        public static double totalOfInventory(double p, double u, double rf)
            double tOfI = (p * u) + (p * u * rf);
            return (tOfI);
        public static double totalOfRestockFee(double p, double rf)
            double percent = 0;
            percent = (p * 5) / 100;
            return percent;       
    }//end class Products_______________________________
    Maker.java
    package inventorymain;
    import javax.swing.JFrame;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.NumberFormat;
    import javax.swing.border.*;
    import java.net.*;
    import java.util.StringTokenizer;
    class Maker extends Inventory implements ActionListener
    {//begins Class Maker
        static String manufact[] = new String[100];
        static double restockingFee[] = new double[100];
        static int i;
        static double TotalVal;
        static int navItem;
        static Boolean isRecordLoadedFromFile = false;
        private Container cp = getContentPane();
        GridBagConstraints c;
        GridBagConstraints cconstraint;
        Border titledborder;
        JPanel pan;
        String labels[] = {"Product Name:", "Manufacturer:", "Product ID Number:", "Units in Stock:", 
                           "Price Per Unit:                                                      $",
                           "Restocking Fee:                                                   $",
                           "Value of Product in Stock:                                $",
                           "Value of All Merchandise Plus Restocking: $"};
        int len1 = labels.length;
        JLabel lbl[] = new JLabel[len1];
        JTextField txtfield1[] = new JTextField[len1];
        String blabels[] = {"First", "Previous", "Next", "Last"};
        int blen = blabels.length;
        JButton navigate[] = new JButton[blen];
        String cmdlabels[] ={"Load File", "Add", "Modify", "Delete", "Search", "Save","Cancel" };
        int cmdlen = cmdlabels.length;
        JButton cmdbutton[] = new JButton[cmdlen];
        JLabel lblImg;
        File file;
        public String FileName;
        public Maker(int Item_Number, String Item_Name, double Item_Price, int Items_in_Stock, String manufact, double restockingFee)// Constructor for varibles
            super(Item_Number, Item_Name, Item_Price, Items_in_Stock);
            this.manufact[i] = manufact;
            this.restockingFee[i] = restockingFee;
            i = i + 1;
        public static void setManufact(int k, String value)
            manufact[k] = value;
        public static double getRestockFee(int val)
            return restockingFee[val];
        public void ShowInventory()
            setLayout(new FlowLayout());
            GridBagLayout contlayout = new GridBagLayout();//layout for container
            GridBagConstraints cconstraint = new GridBagConstraints();//constraint for container
            GridBagLayout gblayout = new GridBagLayout();//layout for panel
            GridBagConstraints gbconstraint = new GridBagConstraints();
            FileName = "C://dat//inventory.dat";
            try
                String strDirectoy = "C://dat";
                boolean success = (new File(strDirectoy)).mkdir();
                file = new File(FileName);
                success = file.createNewFile();
                //ADD SAVE CANCEL DELETE EXIT
                pan = new JPanel();
                gblayout = new GridBagLayout();
                gbconstraint = new GridBagConstraints();
                pan.setLayout(gblayout);
                gbconstraint.gridwidth = 1;
                gbconstraint.gridheight = 1;
                gbconstraint.gridy = 0;
                for (int i = 0; i < cmdlen; i++)
                    cmdbutton[i] = new JButton(cmdlabels);
              cmdbutton[i].addActionListener(this);
              gbconstraint.gridx = i;
              pan.add(cmdbutton[i], gbconstraint);
    }//end for
    titledborder = BorderFactory.createTitledBorder("Confirmation");
    pan.setBorder(titledborder);
    //ADD PANEL TO CONTAINER
    cconstraint.gridwidth = 4;
    cconstraint.gridheight = 1;
    cconstraint.gridx = 0;
    cconstraint.gridy = 2;
    cp.add(pan, cconstraint);
    //ADDITION COMPLETE
    //first panel
    pan = new JPanel();
    gblayout = new GridBagLayout();
    gbconstraint = new GridBagConstraints();
    pan.setLayout(gblayout);
    for (int i = 0; i < 2; i++)
    for (int j = 0; j < len1; j++)
    int x = i;
    int y = j;
    if (x == 0)
    lbl[j] = new JLabel(labels[j]);
    lbl[j].setHorizontalAlignment(JLabel.LEFT);
    lbl[j].setPreferredSize(new Dimension(250, 15));
    gbconstraint.insets = new Insets(10, 0, 0, 0);
    gbconstraint.gridx = x;
    gbconstraint.gridy = y;
    pan.add(lbl[j], gbconstraint);
    }//end if
    else
    txtfield1[j] = new JTextField(15);
    txtfield1[j].setPreferredSize(new Dimension(300, 15));
    txtfield1[j].setHorizontalAlignment(JLabel.LEFT);
    txtfield1[j].setEnabled(false);
    lbl[j].setLabelFor(txtfield1[j]);
    gbconstraint.gridx = x;
    gbconstraint.gridy = y;
    pan.add(txtfield1[j], gbconstraint);
    }//end else
    }//end for
    }//end for
    Border titledborder = BorderFactory.createTitledBorder("Current Inventory Records");
    pan.setBorder(titledborder);
    //adds panel to container
    cconstraint.gridwidth = 1;
    cconstraint.gridheight = 1;
    cconstraint.gridx = 0;
    cconstraint.gridy = 0;
    cp.add(pan, cconstraint);
    //add icon to display
    pan = new JPanel();
    gblayout = new GridBagLayout();
    gbconstraint = new GridBagConstraints();
    pan.setLayout(gblayout);
    gbconstraint.gridwidth = 1;
    gbconstraint.gridheight = 1;
    gbconstraint.gridy = 0;
    lblImg = new JLabel((new ImageIcon(getClass().getResource("logo111.jpg"))));
    lblImg.setPreferredSize(new Dimension(70, 70));
    pan.add(lblImg);
    cconstraint.gridwidth = 1;
    cconstraint.gridheight = 1;
    cconstraint.gridx = 0;
    cconstraint.gridy = 1;
    cp.add(pan, cconstraint);
    //ends icon insert
    //navigation panel
    pan = new JPanel();
    gblayout = new GridBagLayout();
    gbconstraint = new GridBagConstraints();
    pan.setLayout(gblayout);
    gbconstraint.gridwidth = 1;
    gbconstraint.gridheight = 1;
    gbconstraint.gridy = 1;
    for (int i = 0; i < blen; i++)
    navigate[i] = new JButton(blabels[i]);
    gbconstraint.gridx = i;
    pan.add(navigate[i], gbconstraint);
    navigate[i].addActionListener(this);
    }//end for
    titledborder = BorderFactory.createTitledBorder("Navigation Panel");
    pan.setBorder(titledborder);
    //add panel to container
    cconstraint.gridwidth = 4;
    cconstraint.gridheight = 1;
    cconstraint.gridx = 1;
    cconstraint.gridy = 1;
    cp.add(pan, cconstraint);
    }//end try
    catch (Exception e)
    e.printStackTrace();
    }//end catch
    }//end showInventory
    public void setContents(File aFile, String aContents)
    BufferedWriter output = null;
         try
    //use buffering
    //FileWriter always assumes default encoding is OK!
    output = new BufferedWriter(new FileWriter(aFile, true));
    output.write(aContents);
    String newLine = System.getProperty("line.separator");
    output.write(newLine);
    }//end try
    catch (Exception ex)
    ex.printStackTrace();
    }//end catch
    finally
    try
    //flush and close both "output" and its underlying FileWriter
              if (output != null) output.close();
    }//end try
    catch (java.io.IOException e)
    e.printStackTrace();
    }//end catch
    public void AddModifyInventory(String Mode)
    if (Mode.equals("Insert"))
    String Content = txtfield1[1].getText() + "\t"
    + txtfield1[2].getText() + "\t" + txtfield1[3].getText()
    + "\t" + txtfield1[4].getText();
    setContents(file, Content);
    JOptionPane.showMessageDialog(null, "Record Successfully Inserted");
    }//end if
    }//end AddModifyInventory
    public void ShowInventory(int ItemNo)
    txtfield1[0].setText(Integer.toString(ItemNo));
    txtfield1[0].setText(Inventory.getItemName(ItemNo));
    txtfield1[1].setText(manufact[ItemNo]);
    txtfield1[2].setText(Integer.toString(Inventory.getItemNum(ItemNo)));
    txtfield1[3].setText(Integer.toString(Inventory.getItemUnits(ItemNo)));
    txtfield1[4].setText(Double.toString(Inventory.getItemPrice(ItemNo)));
    txtfield1[5].setText(String.format("%3.2f",
    Products.totalOfRestockFee(Inventory.getItemPrice(ItemNo),
    getRestockFee(ItemNo))));
    txtfield1[6].setText(String.format("%3.2f",
    Products.totalOfInventory(Inventory.getItemPrice(ItemNo),
    Inventory.getItemUnits(ItemNo), getRestockFee(ItemNo))));
    txtfield1[7].setText(String.format("%3.2f", GetTotalInvVal()));
    }//end ShowInventory(int ItemNo)
    public void EnableFields(boolean bflag)
    txtfield1[1].setEnabled(bflag);
    txtfield1[2].setEnabled(bflag);
    txtfield1[3].setEnabled(bflag);
    txtfield1[4].setEnabled(bflag);
    txtfield1[5].setEnabled(bflag);
    }//end EnableFields
    public double GetTotalInvVal()
    TotalVal = 0;
    for(int j = 0; j < Inventory.getCount(); j++)
    TotalVal += Products.totalOfInventory(Inventory.getItemPrice(j),
    Inventory.getItemUnits(j), getRestockFee(j));
    return TotalVal;
    }//end GetTotalInvVal
    public Integer GetRecordCount()
         FileReader fr;
         BufferedReader br;
         LineNumberReader lnr;
         String line;
         int lno = 0;
         try
    lnr = new LineNumberReader(new BufferedReader(new FileReader(FileName)));
    while ((line = lnr.readLine()) != null)
              lno = lnr.getLineNumber();
         lnr.close();
         }//end try
         catch (IOException ioErr)
    System.out.println(ioErr.toString());
    System.exit(100);
         return lno;
    public void showInventory(int itemNo)
    int i;
    FileReader fr;
    BufferedReader br;
    LineNumberReader lnr;
    StringTokenizer st;
    String line;
    int item = itemNo + 1;
    int ItemNo = 0;
    int Units = 0;
    String ItemGenre = "";
    String ItemName = "";
    String ItemRating = "";
    double UnitPrice = 0;
    double Total = 0;
    Integer rFee = 0;
    int lno;
    try
              lnr = new LineNumberReader(new BufferedReader(new FileReader(FileName)));
              while ((line = lnr.readLine()) != null)
    lno = lnr.getLineNumber();
    String s1[];
    if (item == lno)
                   s1 = new String[lno];
                   s1[0] = line;
                   st = new StringTokenizer(s1[0]);
                   //ItemNo = lno;
                   ItemGenre = st.nextToken();                         
                   ItemNo = Integer.parseInt(st.nextToken());
                   ItemName = st.nextToken();
                   ItemRating = st.nextToken();
                   Units = Integer.parseInt(st.nextToken());
                   UnitPrice = Double.parseDouble(st.nextToken());
                   //rFee = Integer.parseInt(st.nextToken());
    }//end if
    s1 = new String[lno];
    s1[0] = line;
    st = new StringTokenizer(s1[0]);
    st.nextToken();
    st.nextToken();
    st.nextToken();
    st.nextToken();
    Integer units = Integer.parseInt(st.nextToken());
    Double price = Double.parseDouble(st.nextToken());
    Total += Products.totalOfInventory(price, units, 0.05);
    }//end while
    lnr.close();
    }//end try
    catch (IOException ioErr)
              System.out.println(ioErr.toString());
              System.exit(100);
    }//end catch
    txtfield1[0].setText(Integer.toString(itemNo));
    txtfield1[0].setText(ItemName);
    txtfield1[1].setText(manufact[ItemNo]);
    txtfield1[2].setText(Integer.toString(ItemNo));
    txtfield1[3].setText(Integer.toString(Units));
    txtfield1[4].setText(Double.toString(UnitPrice));
    txtfield1[5].setText(String.format("%3.2f", Products.totalOfRestockFee(UnitPrice, 0.05)));
    txtfield1[6].setText(String.format("%3.2f", Products.totalOfInventory(UnitPrice, Units, 0.05)));
    txtfield1[7].setText(String.format("%3.2f", Total));          
         }//end showInventory
    public void actionPerformed(ActionEvent e)//button actions
    String btnClicked = ((JButton)e.getSource()).getText();
    if(btnClicked.equals("First"))
    EnableFields(false);
    if (isRecordLoadedFromFile)
              navItem = 0;
              showInventory(navItem);
    }//end if
    else
              navItem = 0;
              ShowInventory(navItem);
    }//end else
         }//end if
         if (btnClicked.equals("Next"))
    EnableFields(false);
    if (isRecordLoadedFromFile)
              if (navItem == GetRecordCount() - 1)
    navItem = 0;
              }//end if
    else
    navItem += 1;
              }//end else
              if ((GetRecordCount() - 1) >= navItem)
    showInventory(navItem);
    else
    showInventory(GetRecordCount() - 1);
    }//end if
    else
    if (navItem == getCount() - 1)
    navItem = 0;
    }//end if
    else
    navItem += 1;
    }//end else
    ShowInventory(navItem);
    }//end else
         }//end if
    if (btnClicked.equals("Previous"))
    EnableFields(false);
    if (isRecordLoadedFromFile)
    if (navItem == 0)
    navItem = GetRecordCount() - 1;
              }//end if
    else
    navItem = navItem - 1;
              }//end else
    showInventory(navItem);
    }//end if
    else
              if (navItem == 0)
    navItem = getCount() - 1;
              }//end if
    else
    navItem = navItem - 1;
              }//end else
    ShowInventory(navItem);
    }//end else
         }//end if
    if (btnClicked.equals("Last"))
    EnableFields(false);
    if (isRecordLoadedFromFile)
    navItem = GetRecordCount() - 1;
              showInventory(navItem);
    }//end if
    else
              navItem = getCount() - 1;
              ShowInventory(navItem);
    }//end else
         }//end if
    if (btnClicked.equals("Save"))
    AddModifyInventory("Insert");
         }//end if
    if (btnClicked.equals("Load File"))
    isRecordLoadedFromFile = true;
    if (GetRecordCount() == 0)
              JOptionPane.showMessageDialog(null, "No Records Found in the File");                    
    }//end if
    else
              showInventory(0);
    }//end else
    if (btnClicked.equals("Cancel"))
              EnableFields(false);
              cmdbutton[4].setText("Search");
              cmdbutton[2].setText("Modify");
              cmdbutton[1].setText("Add");
    if(isRecordLoadedFromFile)
    showInventory(navItem);
              else
    ShowInventory(navItem);
    }//end if
    if(btnClicked.equals("Delete"))
              Inventory.DeleteItem(Integer.parseInt(txtfield1[0].getText()));
              navItem = getCount() -1;
              JOptionPane.showMessageDialog(null, "Record Successfully deleted");
              ShowInventory(navItem);
    }//end if
    if(btnClicked.equals("Search"))
              cmdbutton[4].setText("GO!");
              txtfield1[3].setEnabled(true);     
    }//end if
    if(btnClicked.equals("GO!"))
              boolean valid = true;
    if (txtfield1[3].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Product Name Required");
    valid = false;
              }//end if
    if(valid)
    int k = Inventory.SearchItem(txtfield1[3].getText().trim());
    if(k>=0)
                   txtfield1[0].setText(Integer.toString(k));
                   txtfield1[0].setText(Inventory.getItemName(k));
    txtfield1[1].setText(manufact[k]);
    txtfield1[2].setText(Integer.toString(Inventory.getItemNum(k)));
                   txtfield1[3].setText(Integer.toString(Inventory.getItemUnits(k)));
                   txtfield1[4].setText(Double.toString(Inventory.getItemPrice(k)));
                   txtfield1[5].setText(String.format("%3.2f", Products.totalOfRestockFee(Inventory.getItemPrice(k), getRestockFee(k))));
                   txtfield1[6].setText(String.format("%3.2f", Products.totalOfInventory(Inventory.getItemPrice(k ), Inventory.getItemUnits(k), getRestockFee(k))));
                   txtfield1[7].setText(String.format("%3.2f",GetTotalInvVal()));
                   EnableFields(false);
                   cmdbutton[4].setText("Search");                              
    }//end if
    else
    JOptionPane.showMessageDialog(null, "No Matches found");     
    cmdbutton[4].setText("Search");     
    EnableFields(false);
    }//end else
              }//end if               
    }//end if
    if(btnClicked.equals("Modify"))
              EnableFields(true);                         
              cmdbutton[2].setText("Click to Modify!");
    }//end if
    if(btnClicked.equals("Click to Modify!"))
              Boolean valid = true;
    if (txtfield1[1].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Genre Required");
    valid = false;
              }//end if
    try
    Integer.parseInt(txtfield1[2].getText());
              }//end try
              catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Item Number (Only Numbers allowed)");
    txtfield1[2].setText("");
    valid = false;
              }//end catch
              if (txtfield1[3].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Product Name Required");
    valid = false;
              }//end if
              if (txtfield1[4].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Rating Required");
    valid = false;
              }//end if
              try
    Integer.parseInt(txtfield1[5].getText());
              }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Units in Stock (Only Numbers allowed)");
    txtfield1[4].setText("");
    valid = false;
              }//end catch
    try
    Double.parseDouble(txtfield1[6].getText());
              }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Price (Only Numbers allowed)");
    txtfield1[5].setText("");
    valid = false;
              }//end catch
              if (valid)
    //setItemNum,setItemName,setItemUnits,setItemPrice
    Inventory.setItemNum(navItem,Integer.parseInt(txtfield1[1].getText()));
    Inventory.setItemName(navItem,txtfield1[2].getText());
    Inventory.setItemUnits(navItem,Integer.parseInt(txtfield1[4].getText()));
    Inventory.setItemPrice(navItem,Double.parseDouble(txtfield1[5].getText()));     
    txtfield1[6].setText(String.format("%3.2f", Products.totalOfRestockFee(Inventory.getItemPrice(navItem), getRestockFee(navItem))));
    txtfield1[7].setText(String.format("%3.2f", Products.totalOfInventory(Inventory.getItemPrice(navItem ), Inventory.getItemUnits(navItem), getRestockFee(navItem))));
    txtfield1[8].setText(String.format("%3.2f",GetTotalInvVal()));
    EnableFields(false);
    cmdbutton[2].setText("Modify");
              }//end if
    }//end if
    if (btnClicked.equals("Add"))
              EnableFields(true);
              txtfield1[0].setText(Integer.toString(getCount()));
              txtfield1[1].setText("");
              txtfield1[2].setText("");          
              txtfield1[3].setText("0");
              txtfield1[4].setText("0.00");
              cmdbutton[1].setText("Click to Add!");
    }//end if
    if (btnClicked.equals("Click to Add!"))
    Boolean valid = true;
    try
    Integer.parseInt(txtfield1[2].getText());
              }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Item Number (use numbers only)");
    txtfield1[2].setText("");
    valid = false;
              }//end catch
              if (txtfield1[0].getText().trim().length() == 0)
    JOptionPane.showMessageDialog(null, "Product Name Required");
    valid = false;
              }//end if
              try
    Integer.parseInt(txtfield1[3].getText());
              }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, "Invalid Units in Stock (use numbers only)");
    txtfield1[3].setText("");
    valid = false;
              }//end catch
    try

    You do not need to post that massive amount of code to ask about a compile-time error.
    I (and many others here) won't even consider looking at it. Create a small example that demonstrates what you're having trouble with.

  • Please help with SSL POST: Servlet returns Error 500

    I am struggling for many days to get a Java program to log in to an SSL page. The program is supposed to track ADSL usage statistics from https://secure.telkomsa.net/titracker/, but I never seem to get around Server returned Error 500.
    Could anyone please help me understand what I am doing wrong by looking at the method I used. (It seems on the server side it is a jsp servlet that handles authentication).
    Any help is deeply appreciated!
    I copy-paste the method directly from NetBeans:
    CODE>
    void connectHTTPS(String url){
    try {
    URL page = new URL(url); // login page necessary to get a jsp session cookie
    //------------ SET UP SSL - is it right?
    System.setProperty("java.protocol.handler.pkgs",
    "com.sun.net.ssl.internal.www.protocol");
    try {
    //if we have the JSSE provider available,
    //and it has not already been
    //set, add it as a new provide to the Security class.
    final Class clsFactory = Class.forName("com.sun.net.ssl.internal.ssl.Provider");
    if( (null != clsFactory) && (null == Security.getProvider("SunJSSE")) )
    Security.addProvider((Provider)clsFactory.newInstance());
    } catch( ClassNotFoundException cfe ) {
    throw new Exception("Unable to load the JSSE SSL stream handler." +
    "Check classpath." + cfe.toString());
    URLConnection urlc = page.openConnection();
    urlc.setDoInput(true);
    *Get the session id cookie set by the TelkomInternet java server
    String cookie = urlc.getHeaderField("Set-Cookie");
    //textpane.setText(totextpane);
    textpane.setText(cookie);
    //---------------- form an auth request and post it with the cookie
    String postdata =URLEncoder.encode("ID_Field","UTF-8")+"="+URLEncoder.encode("myusrname","UTF-8")+"&"+URLEncoder.encode("PW_Field","UTF-8")+"="+URLEncoder.encode("mypwd","UTF-8")+"&"+URLEncoder.encode("confirm","UTF-8")+"="+URLEncoder.encode("false","UTF-8");
    // set the servlet that handles authentication as target
    URL page2 = new URL("https://secure.telkomsa.net/titracker/servlet/LoginServlet");
    // cast to httpConn to enable setRequestMethod()
    HttpURLConnection urlc2 = (HttpURLConnection)page2.openConnection();
    // formulate request with POST data urlc2.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    urlc2.setRequestMethod("POST"); // experimental
    urlc2.setRequestProperty("Content-Length",""+postdata.length());
    urlc2.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)");
    urlc2.setRequestProperty("Accept-Language","en-us");
    urlc2.setUseCaches(false);
    urlc2.setDoOutput(true);
    urlc2.setDoInput(true);
    urlc2.setFollowRedirects(true); // ??
    //send cookies
    urlc2.setRequestProperty("Set-Cookie", cookie); // or "Cookie" - doesn't work either
    //write other data
    PrintWriter out = new PrintWriter(urlc2.getOutputStream());
    out.print(postdata); // username and password here
    out.flush();
    out.close();
    //---------------- get the authenticated page with real ADSL statistics
    BufferedReader br = new BufferedReader(new InputStreamReader(urlc2.getInputStream()));
    String totextpane = "";
    String buffer = "";
    while (buffer != null) {
    try {
    totextpane = totextpane + "\n" + buffer;
    buffer = br.readLine();
    } catch (IOException ioe) {
    ioe.printStackTrace();
    break;
    textpane.setText(totextpane);
    } catch (Exception ex) {
    System.err.println(ex.getMessage());
    ---- END CODE---
    Thank you very much for any attempt at helping with this problem!

    I am struggling for many days to get a Java program to log in to an SSL page. The program is supposed to track ADSL usage statistics from https://secure.telkomsa.net/titracker/, but I never seem to get around Server returned Error 500.
    Could anyone please help me understand what I am doing wrong by looking at the method I used. (It seems on the server side it is a jsp servlet that handles authentication).
    Any help is deeply appreciated!
    I copy-paste the method directly from NetBeans:
    CODE>
    void connectHTTPS(String url){
    try {
    URL page = new URL(url); // login page necessary to get a jsp session cookie
    //------------ SET UP SSL - is it right?
    System.setProperty("java.protocol.handler.pkgs",
    "com.sun.net.ssl.internal.www.protocol");
    try {
    //if we have the JSSE provider available,
    //and it has not already been
    //set, add it as a new provide to the Security class.
    final Class clsFactory = Class.forName("com.sun.net.ssl.internal.ssl.Provider");
    if( (null != clsFactory) && (null == Security.getProvider("SunJSSE")) )
    Security.addProvider((Provider)clsFactory.newInstance());
    } catch( ClassNotFoundException cfe ) {
    throw new Exception("Unable to load the JSSE SSL stream handler." +
    "Check classpath." + cfe.toString());
    URLConnection urlc = page.openConnection();
    urlc.setDoInput(true);
    *Get the session id cookie set by the TelkomInternet java server
    String cookie = urlc.getHeaderField("Set-Cookie");
    //textpane.setText(totextpane);
    textpane.setText(cookie);
    //---------------- form an auth request and post it with the cookie
    String postdata =URLEncoder.encode("ID_Field","UTF-8")+"="+URLEncoder.encode("myusrname","UTF-8")+"&"+URLEncoder.encode("PW_Field","UTF-8")+"="+URLEncoder.encode("mypwd","UTF-8")+"&"+URLEncoder.encode("confirm","UTF-8")+"="+URLEncoder.encode("false","UTF-8");
    // set the servlet that handles authentication as target
    URL page2 = new URL("https://secure.telkomsa.net/titracker/servlet/LoginServlet");
    // cast to httpConn to enable setRequestMethod()
    HttpURLConnection urlc2 = (HttpURLConnection)page2.openConnection();
    // formulate request with POST data urlc2.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    urlc2.setRequestMethod("POST"); // experimental
    urlc2.setRequestProperty("Content-Length",""+postdata.length());
    urlc2.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)");
    urlc2.setRequestProperty("Accept-Language","en-us");
    urlc2.setUseCaches(false);
    urlc2.setDoOutput(true);
    urlc2.setDoInput(true);
    urlc2.setFollowRedirects(true); // ??
    //send cookies
    urlc2.setRequestProperty("Set-Cookie", cookie); // or "Cookie" - doesn't work either
    //write other data
    PrintWriter out = new PrintWriter(urlc2.getOutputStream());
    out.print(postdata); // username and password here
    out.flush();
    out.close();
    //---------------- get the authenticated page with real ADSL statistics
    BufferedReader br = new BufferedReader(new InputStreamReader(urlc2.getInputStream()));
    String totextpane = "";
    String buffer = "";
    while (buffer != null) {
    try {
    totextpane = totextpane + "\n" + buffer;
    buffer = br.readLine();
    } catch (IOException ioe) {
    ioe.printStackTrace();
    break;
    textpane.setText(totextpane);
    } catch (Exception ex) {
    System.err.println(ex.getMessage());
    ---- END CODE---
    Thank you very much for any attempt at helping with this problem!

  • Basic help with ArrayLists

    I'm doing a project in Java where I have to put numbers in a list, then shuffle them. Then I have to access those numbers and create a Bingo card. I've got everything down except for the accessing the numbers part. How exactly do I access integers from an array list? I read online that I should cast the elements in the ArrayList to an int, but I try that and get an incovertible types error message when I try to compile. Here is my code so far:
    import java.util.ArrayList;
    import java.util.Random;
    import java.util.Collections;
    * Numbers class -- will generate a list of numbers, shuffle them, and then have a method to return them to the Bingo card.
    public class Numbers
        private ArrayList bingoB;
        int cnt;
        String testString;
        public Numbers()
           bingoB = new ArrayList();
           resetNumbers();
        public int getNumberB()
             int test = (int) bingoB.get(0);
             testString = "b-" + test;
             return testString;
        public void resetNumbers()
            for(cnt = 1; cnt <= 15; cnt++)
            bingoB.add(new Integer(cnt));
            Collections.shuffle(bingoB);I really need help with the casting/accessing integer part, but any other tips about what I've got going on in the int getNumberB method would be helpful as well. Thanks in advance.

    You don't cast to 'int', you cast to 'Integer'. You put 'Integer' in, so you take 'Integer' out.
    To get the 'int' value from an 'Integer', use the "intValue()" method in the Integer class.
    testString should be local to getNumberB--it should not be an instance variable. Is getNumberB supposed to return an int or a String? If you want the String, you need:
    public String getNumberB() { ...}

  • Need help with class I'm trying to write for school

    Hi,I'm taking my first Java class, and we're learning how to write classes. I've got MOST of the program and class to work, but I'm still having trouble with it.
    In the class I wrote, if I delete the "getWindTempF(strAlt)" the program runs fine, other than not doing the conversion to Fahrenheit. So, I'm guessing that there's a problem with my getWindTempF method. However, it is almost exactly a duplicate of my getWindTempC method, so I can't figure out what I'm doing wrong. The errors I get when I keep the "getWindTempF(strAlt)" in the prtWindInfo method are:
    java.lang.NumberFormatException: For input string: " "
         at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
         at java.lang.Integer.parseInt(Integer.java:426)
         at java.lang.Integer.parseInt(Integer.java:476)
         at NWSFD.getWindTempF(NWSFD.java:94)
         at NWSFD.prtWindInfo(NWSFD.java:162)
         at a19004.main(a19004.java:30)
    Exception in thread "main"
    ----jGRASP wedge2: exit code for process is 1.
    Again, the program and class work perfectly except for the getWindTempF. Any ideas would be greatly appreciated, and sorry for such a long post
    Here is the main program:
    import cs1.Keyboard;
    import java.text.NumberFormat;
    import java.text.SimpleDateFormat;
    import java.text.DateFormat;
    import java.util.Date;
    public class a19004
         // Instantiates the windsAloft object by using the NWSFD class
         public static void main (String[] args)
              final String FAA_FD="SAN 1405 2908+26 2911+19 2809+11 1307-09 0308-20 " +
              "032433 012543 352853";
              NWSFD windsAloft = new NWSFD(FAA_FD);     //Instantiate the NWSFD object
              System.out.println ("Winds Aloft");
              System.out.println ("as of " + windsAloft.getDate());
              System.out.println ("");
              System.out.println ("STA Alt Dir Speed TempC TempF");
              System.out.println ("");
              System.out.println (windsAloft.prtWindInfo("03"));
              System.out.println (windsAloft.prtWindInfo("06"));
              System.out.println (windsAloft.prtWindInfo("09"));
              System.out.println (windsAloft.prtWindInfo("12"));
              System.out.println (windsAloft.prtWindInfo("18"));
              System.out.println (windsAloft.prtWindInfo("24"));
              System.out.println (windsAloft.prtWindInfo("30"));
              System.out.println (windsAloft.prtWindInfo("34"));
              System.out.println (windsAloft.prtWindInfo("39"));
    And for the sake of brevity, just a part of the NWSFD class:
    import java.text.*;
    import java.util.Date;
    public class NWSFD
         // Set up variables
         private String strWea;
         // 3.a. Constructor
         public NWSFD (String strVar)
              strWea=strVar + " ";
         // 3.d.
         public String getWindTempC (String strAlt)
              String strVar;
              strVar = strWea.substring(getPos(strAlt) + 4, getPos(strAlt) + 7);
              if (strAlt.equals("03"))
                   strVar = strWea.substring(getPos(strAlt) +4, getPos(strAlt) + 5);
              if (strAlt.equals("30"))
                   strVar = "-" + strWea.substring(getPos(strAlt) +4, getPos(strAlt) + 6);
              if (strAlt.equals("34"))
                   strVar = "-" + strWea.substring(getPos(strAlt) +4, getPos(strAlt) + 6);
              if (strAlt.equals("39"))
                   strVar = "-" + strWea.substring(getPos(strAlt) +4, getPos(strAlt) + 6);
              if (strVar.equals(" "))
                   strVar = "N/A";
              return strVar;
         // 3.ed.
         public String getWindTempF (String strAlt)
              String strVar;
              String strFar;
              int intRet;
              int intFar;
              strFar = strWea.substring(getPos(strAlt) + 5, getPos(strAlt) + 7);
              if (strAlt.equals("03"))
                   strFar = strWea.substring(getPos(strAlt) +4, getPos(strAlt) + 5);
              if (strAlt.equals("30"))
                   strFar = "-" + strWea.substring(getPos(strAlt) +4, getPos(strAlt) + 6);
              if (strAlt.equals("34"))
                   strFar = "-" + strWea.substring(getPos(strAlt) +4, getPos(strAlt) + 6);
              if (strAlt.equals("39"))
                   strFar = "-" + strWea.substring(getPos(strAlt) +4, getPos(strAlt) + 6);
              if (strFar.equals(" "))
                   strVar = "N/A";
              intRet = Integer.parseInt(strFar);
              intFar = intRet * (9/5) + 32;
              strVar = Integer.toString(intRet++);
              return strVar;
         // 3.h.
         public String prtWindInfo (String strAlt)
              String strRet;
              strRet = strWea.substring(0,3) + " " + strAlt + "000" + " " +
                   getWindDir(strAlt) + " " + getWindSpeed(strAlt) + " " +
                   getWindTempC(strAlt) + "C " + getWindTempF(strAlt) + "F";
              return strRet;
    }

    Thank you for the reply, soni29. here is the code:
    public int getPos(String strAlt)
              int intAlt;
              int intRet;
              intAlt = Integer.parseInt(strAlt);
              switch (intAlt)
                   case 3:
                        intRet = 4;
                        break;
                   case 6:
                        intRet = 9;
                        break;
                   case 9:
                        intRet = 17;
                        break;
                   case 12:
                        intRet = 25;
                        break;
                   case 18:
                        intRet = 33;
                        break;
                   case 24:
                        intRet = 41;
                        break;
                   case 30:
                        intRet = 49;
                        break;
                   case 34:
                        intRet = 56;
                        break;
                   default:
                        intRet = 63;
              } //     Close switch
              return intRet;
    However, I really don't think there's a problem with any of the coding there. The only times I have problems with the program is when I'm trying to display the data from getWindTempF. If I omit that method, the program works perfectly. Basically, what the program is supposed to do, is hand a string (FAA_FD) to the NWSFD class, which then extracts data from it. Thank you again for the help...any other advice?

  • Need help with paint (here my code)

    hi, i have problem with my paint method, if i put super.paint(g); all work perfectly but when you draw the program refresh all time, and does like flash effect taht i dotn want (test the code you'll see what im talking about) , and if i dont put super.paint(g) my component didnt paint... please help me, i know taht is a little bug, but i didnt have any kind of problem with swing before..
    thx
    //Debut imports
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    //Fin imports
    //  Class: soudure
    public class soudure extends JApplet implements MouseListener, MouseMotionListener, ChangeListener
        //Debut Declarations
        boolean dessinConfig = false; //Savoir quand on utilise paint pour config
        Image img; //Image a dessiner
        int x = -1; //Sert pour savoir le point x de la souris
        int y = -1; //Sert pour savoir le point y de la souris
        int ovalHeight = 10; //Set la hauteur de l'oval
        int ovalWidth = 10; //Set la largeur de l'oval
        JLabel xCoord, //Coordonner de la souris X
               yCoord, //Coordonner de la souris Y
               lVoltage, //Identifie le voltage
               lAmperage; //Indeitifie l'amperage
        JPanel config, //Panel de configuration
               dessin, //Panel de dessin
               info; //Panel d'info
        JSlider voltage, //Set le voltage
                amperage; //Set l'amperage
        Vector sauvOvalXY; //Sauvegarde les points x et y des ovals
        Vector sauvOvalWH;  //Sauvegarde les largeur et hauteur des ovals
        //Fin Declarations
        //  Fonction: init()
        public void init()
            //Debut Initialisations
            config = new JPanel();   
            dessin = new JPanel();
            info = new JPanel();
            xCoord = new JLabel("X Coord.: ");
            yCoord = new JLabel("Y Coord.: ");
            voltage = new JSlider(JSlider.VERTICAL, 15,30,15);
            lVoltage = new JLabel("Voltage  15 :");
            amperage = new JSlider(JSlider.VERTICAL, 100,400,100);
            lAmperage = new JLabel("Amperage  100 :");
    //      img = new Image();
          sauvOvalXY = new Vector();
          sauvOvalWH = new Vector();
            //Fin Initialisations
            //Debut set Background
            config.setBackground(Color.lightGray);       
            dessin.setBackground(Color.white);
            //Fin set Background
            //Debut set layout
            dessin.setLayout(null);
            //Fin Set Layout
            //Add les listener
            dessin.addMouseListener(this);
            dessin.addMouseMotionListener(this);
            voltage.addChangeListener(this);
            amperage.addChangeListener(this);       
            //Fin Add listener
            //Divers settings
            dessin.setBorder(new MatteBorder(1,1,1,1,Color.black));
            config.setBorder(new MatteBorder(1,1,1,1,Color.black));
            info.setBorder(new MatteBorder(1,1,1,1,Color.black));
            voltage.setSize(20,10);
            amperage.setSize(20,10);
            //Set Size
            getContentPane().setSize(500,500);
            config.setBounds(0,0,500,100);
            dessin.setBounds(0,100,500,300);
            info.setBounds(0,400,500,100);       
            //Fin set Size
            //Debut ajout Panel
            info.add(xCoord);
            info.add(yCoord);
            config.add(lVoltage);
            config.add(voltage);
            config.add(lAmperage);
            config.add(amperage);
            getContentPane().add(config,"North");
            getContentPane().add(dessin,"Center");
            getContentPane().add(info,"South");       
            //Fin ajout Panel       
        //Fin Fonction init()
        //  Fonction: mouseClicked(MouseEvent)
        public void mouseClicked(MouseEvent e)
        //Fin Fonction mouseClicked(MouseEvent)
        //  Fonction: mouseDragged(MouseEvent)
        public void mouseDragged(MouseEvent e)
            //Prend l'objet sur lequel l'event est fait
            Object obj = e.getSource();
            x = e.getX();
            y = e.getY();
            //JPanel Dessin
            if(obj == dessin)
                repaint();
                positionSouris(e);
            //Fin JPanel dessin
        //Fin Fonction mouseDragged(MouseEvent)
        //  Fonction: mouseEntered(MouseEvent)
        public void mouseEntered(MouseEvent e)
            //positionSouris(e);
        //Fin Fonction mouseEntered(MouseEvent)
        //  Fonction: mouseExited(MouseEvent)
        public void mouseExited(MouseEvent e)
            //Met les coords de la souris a 0
            xCoord.setText("X Coord.: 0");
            yCoord.setText("Y Coord.: 0");
        //Fin Fonction mouseExited(MouseEvent)
        //  Fonction: mouseMoved(MouseEvent)
        public void mouseMoved(MouseEvent e)
            positionSouris(e);
        //Fin Fonction mouseMoved(MouseEvent)
        //  Fonction: mousePressed(MouseEvent)
        public void mousePressed(MouseEvent e)
        //Fin Fonction mousePressed(MouseEvent)
        //  Fonction: mouseReleased(MouseEvent)
        public void mouseReleased(MouseEvent e)
        //Fin Fonction mouseReleased(MouseEvent)
        //  Fonction: paint(Graphics)
        public void paint(Graphics g)
            super.paint(g);
            g = dessin.getGraphics();
            //Verifie si rien n'a encore ete dragger
            if(x != -1)
                //Sauvegarde les infos
                sauvOvalXY.add(new Point(x,y));
                sauvOvalWH.add(new Point(ovalWidth,ovalHeight));
                //Dessine les sauvegarde
                int size = sauvOvalXY.size();
                for(int i=0;i<size;i++)
                    Point tmpXY = (Point)sauvOvalXY.get(i);
                    Point tmpWH = (Point)sauvOvalWH.get(i);
                    g.fillOval(tmpXY.x,tmpXY.y,tmpWH.x,tmpWH.y);
                g.fillOval(x,y,this.ovalWidth,this.ovalHeight);
    /*        //Si dessine pour panel config
            if(dessinConfig)
                g = config.getGraphics();
                g.drawImage(img,0,0,100,100,this);
               // dessinConfig = false;
        //Fin Fonction paint(Graphics)
        //  Fonction: positionSouris(MouseEvent)
        public void positionSouris(MouseEvent e)
            int tmpX = e.getX();
            int tmpY = e.getY();
            xCoord.setText("X Coord.: " + Integer.toString(tmpX));
            yCoord.setText("Y Coord.: " + Integer.toString(tmpY));
        //Fin Fonction positionSouris(MouseEvent)
        //  Fonction: stateChanged(ChangeEvent)
        public void stateChanged(ChangeEvent e)
            //Verifie lobject actuel
            Object obj = e.getSource();
            //Voltage
            if(obj == voltage)
                int tmpVoltage = voltage.getValue();
                lVoltage.setText("Voltage  " + Integer.toString(tmpVoltage) + " :");
            //Fin voltage
            else
                //Voltage
                if(obj == amperage)
                    int tmpAmperage = amperage.getValue();
                    lAmperage.setText("Amperage  " + Integer.toString(tmpAmperage) + " :");
                //Fin voltage       
        //Fin Fonction stateChanged(ChangeEvent)
    }

    Hi,
    For Swing components you need to override the paintComponent method instead of paint. In your case you can't do that with the approach you have taken. Here is how you can do it:
    1. Remove your paint method
    2. Change your creation of the dessin JPanel and override its' paintComponent method using an anonymous class.
        dessin = new JPanel()
                    public void paintComponent( Graphics g )   
                      super.paintComponent(g);      
                      //Verifie si rien n'a encore ete dragger 
                      if(x != -1)       
                        //Sauvegarde les infos
                        sauvOvalXY.add(new Point(x,y));
                        sauvOvalWH.add(new Point(ovalWidth,ovalHeight));
                        //Dessine les sauvegarde          
                        int size = sauvOvalXY.size(); 
                        for(int i=0;i<size;i++)         
                          Point tmpXY = (Point)sauvOvalXY.get(i);
                          Point tmpWH = (Point)sauvOvalWH.get(i);
                          g.fillOval(tmpXY.x,tmpXY.y,tmpWH.x,tmpWH.y);
                        g.fillOval(x,y,ovalWidth,ovalHeight);
                 };This will allow you to override the correct method and still use all of your applet class variables. Notice that I have removed the line getting the graphics of dessin because it is now being passed into the paintComponent method.
    The two steps above should remove any flashing that you may have had.
    Regards,
    Manfred.

  • Help with treemap and other stuff

    hi guys..
    i m new to this forum..
    and this is my first post....so if i act a little naive .....please bare with me.
    and if this is not the correct place to post ..i m sorry for that.
    i have an assignment to submit....i m getting the whole picture ....but not sure how to go about implementing it.
    here it is...
    Write an Object Oriented solution to the problem in Java. The solution is to consist of:
    A TableIndex class
    A TableNavigator Interface
    A data row class ....class that i have to create.
    An application class to use and test your TableIndex class
    The following UML class diagrams show the public methods of the classes. Other methods may be specified. Specify data members, inner classes and interfaces as appropriate.
    TableIndex Class
    The TableIndex class is an index to a collection of objects. The class is to approximate an index to a data table in memory that consists of a number of rows. To control access to the index a current row is defined that specifies the row that can be accessed. To retrieve a row from the index it must be the current row. The get() method is the only method in TableIndex class that retrieves a row from the index. The current row can be changed explicitly using the methods: previous(), next(), first(), last(), gotoBookmark and find(K); and implicitly using insert(K, V), modify(K, V) and remove().
    The TableIndex class is to be implemented using the java API's TreeMap class and must use Generics. The data types K and V below are generic types for the Key and Value (row) respectively. An important aspect of the assignment is using the Java API documentation to understand the TreeMap class.
    guys ....can u plz help with the starting bit ..
    what should be the opening statement of the class...
    public class TableIndex<K , V> .....????
    and what should be the treemap declaration..??
    TreeMap<K , V> indexTable = new TreeMap<K , V>();...???
    i m confused....
    can u plz explain to me..

    hi mate.....didnt quite get you..
    can u plz be a bit more simple in explanation..!!!
    i will post the whole question ..so that anyone reading will understand better....
    Problem Description
    You are to develop an index class and associated classes.
    Requirements
    Write an Object Oriented solution to the problem in Java. The solution is to consist of:
    A TableIndex class
    A TableNavigator Interface
    A data row class
    An application class to use and test your TableIndex class
    The following UML class diagrams show the public methods of the classes. Other methods may be specified. Specify data members, inner classes and interfaces as appropriate.
    TableIndex Class
    The TableIndex class is an index to a collection of objects. The class is to approximate an index to a data table in memory that consists of a number of rows. To control access to the index a current row is defined that specifies the row that can be accessed. To retrieve a row from the index it must be the current row. The get() method is the only method in TableIndex class that retrieves a row from the index. The current row can be changed explicitly using the methods: previous(), next(), first(), last(), gotoBookmark and find(K); and implicitly using insert(K, V), modify(K, V) and remove().
    The TableIndex class is to be implemented using the java API's TreeMap class and must use Generics. The data types K and V below are generic types for the Key and Value (row) respectively. An important aspect of the assignment is using the Java API documentation to understand the TreeMap class.
    TableIndex
    +TableIndex()
    +TableIndex(name: String, comp: Comparator)
    +getName(): String
    +isEmpty(): Boolean
    +size(): Integer
    +hasPrevious(): Boolean
    +hasNext(): Boolean
    +previous()
    +next()
    +first()
    +last()
    +setBookmark(): Boolean
    +clearBookmark()
    +gotoBookmark(): Boolean
    +contains(key: K): Boolean
    +find(key: K): Boolean
    +get(): V
    +insert(key:K, value: V): Boolean
    +modify(value: V): Boolean
    +modify(key: K, value: V): Boolean
    +remove(): V
    +iterator(): Iterator
    +equals(obj2: Object): Boolean
    +toString(): String
    Additional Notes:
    The table index has an order defined by the compareTo method of the key's class or by the compare method specified in the class that implements the Comparator interface.
    getName(): the name of the index, blank by default.
    isEmpty(): returns true if there aren't any rows in the table index
    size(): returns the number of rows in the table index
    hasPrevious(): returns true if there is a row before the current row.
    hasNext(): returns true if there is a row after the current row in sequence.
    previous(): if there is a row before the current row, move to the row and make it the new current row.
    next() if there is a row after the current row, move to the row and make it the new current row.
    first(): if the table isn't empty, move to the first row and make it the new current row.
    last(): if the table isn't empty, move to the last row and make it the new current row.
    setBookmark(): sets a bookmark at the current row. If the bookmark is successfully set the method returns true. The bookmark is cleared if the TableIndex is empty or the row the bookmark was set on is deleted..
    clearBookmark(): sets the bookmark to null, indicating there isn't a bookmark.
    gotoBookmark(): if a bookmark has been set, go to the bookmarked row. If successful the book marked row becomes the current row and the method returns true.
    contains(K): return true if a row with the key specified exists.
    find(K): if a row is found with the specified key, the current row is set to the row found.
    get(): returns the current row. Null is returned if there isn't a current row.
    insert(K, V): inserts a row (value) with the key specified. The key must not be null and must be unique (not already in the TableIndex). The row (value) must not be null. If the row is successfully inserted true is returned, and the row becomes the current row..
    modify(V): change the current row's data to the row (value) specified. The key and the current row key are to remain the same. If successful true is returned.
    modify(K, V): change the current row's key and data to the key and row (value) specified. If successful the changed row becomes the new current row. If successful true is returned. Note: this is more difficult than modify(V).
    remove(): remove the current row. When a row is deleted the next row (if available) becomes the current row, otherwise if there isn't a next row the previous row becomes the current row, otherwise the table is empty therefore the current row is null.
    iterator(): returns an iterator to the rows (values) in the index. The rows are to be retrieved in order. The remove method does not need to be implemented (its method body can be empty)..
    the equals method uses the name, and the rows (values) in order when testing for equality.
    the toString method should return appropriately formatted data members and the rows (values/data) in the index.
    TableNavigator Interface
    «interface»
    TableNavigator
    +isEmpty(): Boolean
    +hasPrevious(): Boolean
    +hasNext(): Boolean
    +previous()
    +next()
    +first()
    +last()
    +contains(key: K): Boolean
    +find(key: K): Boolean
    Additional Notes:
    The TableIndex class implements the TableNavigator Interface.
    The purpose of the above methods is outlined in the TableIndex class.
    Your Data Row Class
    You are to include a class of your own to represent a row of data in the TableIndex. This is not to be a class that was covered in other programming subjects. It does not need to be complex but must include a range of data types. This class will be used to test your TableIndex class. The class should have an appropriate name and deal with something of interest to you.
    Your Application Class
    The application class is to make use of the TableIndex class and your data row class. It is to clearly show how the TableIndex class is used, and in doing so, test it. The class should have an appropriate name. The application class should create two indexes of different key data types. One of the indexes must make use of the Comparator interface to have a key that is in descending order.
    Output
    Output in the test classes/programs is to go to standard out or a text file. There should be no output from the TableIndex class or your data row class. A GUI interface is NOT required. There is no need to input data from the keyboard or file. Use the Unix script command or write output to a text file (etc) to provide example runs of your test programs.

Maybe you are looking for