Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: ArrayList object's elements confusing??? doesnt replace the elements? set() method?

  1. #1
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default ArrayList object's elements confusing??? doesnt replace the elements? set() method?

    now im gonna post the code that makes me going back to 0,
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.Timer;
    /**
     *
     * @author 
     */
     
    public final class ScoreWindow extends JFrame {
     
        private Timer timer;
     
        public ScoreWindow(int finalScore) {
     
            initWindowComponents(finalScore);
        }
     
        private class ScoreWindowAnimationPanel extends JPanel implements ActionListener {
     
            private ArrayList fScoreNumberList;
            private AnimatedNumbers fScoreNumber;
            private int numImgIdx;
     
            public ScoreWindowAnimationPanel(int finalScore) {
     
                setFocusable(true);
                setDoubleBuffered(true);
                timer = new Timer(1, this);
                timer.start();
                numImgIdx = 0;
                fScoreNumberList = new ArrayList();
                createAnimatedNumberObjects(finalScore);
            }
     
            private void createAnimatedNumberObjects(Integer finalScore) {
     
                // creates a specific size for this array list object (fScoreNumberList)
                for (int x = 0; x < finalScore.toString().length() + 1; x++) {
     
                    fScoreNumberList.add(new Object());
                    //fScoreNumberList.add(null);
                }
     
                // replace the elements on the indexes on this array list object
                for (int x = 0; x < finalScore.toString().length() + 1; x++) {
     
                    fScoreNumberList.set(x, new AnimatedNumbers(x, x));
                }
     
                // check all the instances on this array list object if they are
                // instance of the class (AnimatedNumbers)
                for (int x = 0; x < fScoreNumberList.size(); x++) {
     
                    // here!, elements of this ArrayList Object are instances of this class!!
                    System.out.println(fScoreNumberList.get(x) instanceof AnimatedNumbers);
                }
            }
     
            @Override
            public void actionPerformed(ActionEvent e) {
     
                if (numImgIdx < fScoreNumberList.size()) {
     
                     // the problem is HERE!, elements are still object of Object.class
                    fScoreNumber = (AnimatedNumbers) fScoreNumberList.get(numImgIdx);
                    fScoreNumber.updateDelay();
                }
            }
        }
     
        public void initWindowComponents(int finalScore) {
     
            add(new ScoreWindowAnimationPanel(finalScore));
            setSize(505, 317);
            setVisible(true);
        }
     
        public static void showWindow(int finalScore) {
     
            new ScoreWindow(finalScore);
        }
     
        public static void main(String[] args) {
     
            ScoreWindow.showWindow(3642);
        }
    }

    this is actually a simple animation that show a user's score on my game, to evaluate the problem,
    i had a post in the same forum that asks whether is there a way to set an initial size of an ArrayList object, because i need to insert a certain instance on an index(i removed the insert-in-the-middle thing), then i was given a clarified answer that its not possible, so i made a way to make an initial size, as you can see on the code above,

    1.) creating a for - loop with a certain loop
    2.) adding elements(new Object()) or a null object to make the arraylist have its definite size

    now i created another loop wherein i will replace the elements on it

    1.) creating a for - loop with the same loop count
    2.) replacing the elements using the set() method

    PROBLEM:
    the program is throwing me that the elements/element cannot be casted into an AnimatedNumbers objects(class will be posted below)
    BUT I INCLUDED a for - loop that checks if the elements in that arraylist is an instance of AnimatedNumbers.class
    it makes me confuse that in a certain part of the program the elements are instance of AnimatedNumbers.class but in another part of the program, the elements are STILL instance of Object.class? what is going on?

    i will include the class that will support the issue here: AnimatedNumbers.class
    public class AnimatedNumbers {
     
        private ArrayList numberImageList;
        private int numberImageIdx;
        private int x;
        private int delay;
     
        public AnimatedNumbers(int numberImageIdx, int x) {
     
            numberImageList = new ArrayList();
            this.numberImageIdx = numberImageIdx;
            this.x = x;
            delay = 0;
        }
     
        public AnimatedNumbers(int x) {
     
            this.x = x;
            delay = 0;
        }
     
    }

    i dont have any problems with this AnimatedNumbers.class, the only concern is , why does the elements on that ArrayList object doesnt change or not REPLACED in a certain part of the program
    Last edited by chronoz13; June 21st, 2011 at 02:05 AM.


  2. #2
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: ArrayList object's elements confusing??? doesnt replace the elements? set() metho

    with a little bit more of analyzing and thinking, i noticed how the errors and output statements are being printed in the console, so i ended up looking at the timer object, what i noticed is that my timer object (when it was initialized) it has a delay of "1", basically , the whole program was executing too fast, and im using an action listener, so it WAS NOT EXECUTING THE WAY i want it to be, i adjusted the delay like putting 100 or 1000(1 second) it works fine, but this is just an assumption that the problem is on the execution of the codes, its not executing the way i want it to, im still hoping to get a brief explanation on how do i get this problem, or any ideas other than what i had to compensate with the problem, any answer will be greatly appreciatedbebecause the code is getting bigger, im gonna encounter more problem with this timer object and more..
    Last edited by chronoz13; June 21st, 2011 at 03:56 AM.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: ArrayList object's elements confusing??? doesnt replace the elements? set() metho

    program is throwing me that the elements/element cannot be casted
    When you get errors please copy and paste the full text here.

    why does the elements on that ArrayList object doesnt change or not REPLACED in a certain part of the program
    Can you explain and show an example of what is happening here?

  4. #4
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: ArrayList object's elements confusing??? doesnt replace the elements? set() metho

    i re-run the program above, ScoreWindow.class, and it doesnt show the errors anymore (no changes had been made), it seems like it really has something to do with the timer object(Thread), but i still get the error from the original codes of those 2 classes, its a bit long .. ill post those 2 to show the error

    the original ScoreWindow.class
    package newpackage;
     
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.Timer;
    import javax.swing.UIManager;
     
    /**
     *
     * @author 
     */
     
    public final class ScoreWindow extends JFrame {
     
        private Timer timer;
     
        public ScoreWindow(int finalScore) {
     
            initWindowComponents(finalScore);
        }
     
        private class ScoreWindowAnimationPanel extends JPanel implements ActionListener {
     
            private ArrayList fScoreNumberList;
            private Image scoreLabel;
            private AnimatedNumbers fScoreNumber;
            private int numImgIdx;
            private int imgPosition;
            private int scoreLabelX;
     
            public ScoreWindowAnimationPanel(int finalScore) {
     
                setFocusable(true);
                setDoubleBuffered(true);
                setBackground(Color.BLACK);
                setBounds(0, 0, 510, 243);
                setLayout(null);
                timer = new Timer(1, this);
                timer.start();
                numImgIdx = 0;
                imgPosition = 180;
                fScoreNumberList = new ArrayList();
                createAnimatedNumberObjects(finalScore);
                checkLevelForLabel();
            }
     
            private void createAnimatedNumberObjects(Integer finalScore) {
     
                Character numChar;
     
                // creates a specific size for this array list object (fScoreNumberList)
                for (int x = 0; x < finalScore.toString().length() + 1; x++) {
     
                    fScoreNumberList.add(new Object());
                }
     
                for (int x = 0; x < finalScore.toString().length() + 1; x++) {
     
                    if (x == 1) {
     
                        fScoreNumberList.set(x, new AnimatedNumbers(imgPosition));
                        imgPosition += 30;
                    }
                    else {
     
                        if (x == 0) {
     
                            numChar = finalScore.toString().charAt(x);
                        }
                        else {
     
                            numChar = finalScore.toString().charAt(x - 1);
                        }
     
                        fScoreNumberList.set(x, new AnimatedNumbers(Integer.parseInt(numChar.toString()), imgPosition));
                        imgPosition += 30;
                    }
                }
     
                for (int x = 0; x < fScoreNumberList.size(); x++) {
     
                    System.out.println(fScoreNumberList.get(x) instanceof AnimatedNumbers);
                }
            }
     
            private void checkLevelForLabel() {
     
                int level = 4;
     
                if (level == 1) {
     
                    scoreLabel = new ImageIcon("C:\\KKKFOLDER\\una.png").getImage();
                    scoreLabelX = 75;
                }
                else if (level == 2) {
     
                    scoreLabel = new ImageIcon("C:\\KKKFOLDER\\ikalawa.png").getImage();
                    scoreLabelX = 50;
                }
                else if (level == 3) {
     
                    scoreLabel = new ImageIcon("C:\\KKKFOLDER\\ikatlo.png").getImage();
                    scoreLabelX = 55;
                }
                else if (level == 4) {
     
                    scoreLabel = new ImageIcon("C:\\KKKFOLDER\\ikaapat.png").getImage();
                    scoreLabelX = 50;
                }
            }
     
            @Override
            public void paint(Graphics g) {
     
                super.paint(g);
                Graphics2D g2d = (Graphics2D) g;
     
                g2d.drawImage(new ImageIcon("C:\\KKKFOLDER\\outputWindowBg.jpg").getImage(), 0, 0, this);
                g2d.drawImage(scoreLabel, scoreLabelX, 30, this);
     
                for (int x = 0; x < numImgIdx; x++) {
     
                    fScoreNumber = (AnimatedNumbers) fScoreNumberList.get(x);
                    g2d.drawImage(fScoreNumber.getNumberImage(), fScoreNumber.getX(), 100, this);
                }
     
                Toolkit.getDefaultToolkit().sync();
            }
     
            @Override
            public void actionPerformed(ActionEvent e) {
     
                if (numImgIdx < fScoreNumberList.size()) {
     
                    fScoreNumber = (AnimatedNumbers) fScoreNumberList.get(numImgIdx);
                    fScoreNumber.updateDelay();
     
                    if (fScoreNumber.getDelayValue() == 1) {
     
     
                        numImgIdx++;
                    }
                }
     
                repaint();
            }
        }
     
        private class ScoreWindowSubPanel extends JPanel {
     
            private JButton proceed;
     
            public ScoreWindowSubPanel() {
     
                setBackground(Color.GRAY);
                setBounds(0, 243, 500, 64);
                setLayout(null);
                initComponents();
            }
     
            public void initComponents() {
     
                proceed = new JButton("Ipagpatuloy");
                proceed.setFont(new Font("Comic Sans MS", Font.BOLD, 15));
                proceed.setBounds(180, 7, 150, 30);
                proceed.addActionListener(new ButtonActionListener());
                add(proceed);
            }
     
            private class ButtonActionListener implements ActionListener {
     
                public void actionPerformed(ActionEvent e) {
     
                    timer.stop();
                    setVisible(false);
                    dispose();
                }
            }
        }
     
        public void initWindowComponents(int finalScore) {
     
            try {
     
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
            }
            catch (Exception e) {}
     
     
            JPanel mainPanel = new JPanel(null);
            mainPanel.add(new ScoreWindowAnimationPanel(finalScore));
            mainPanel.add(new ScoreWindowSubPanel());
     
            JFrame f = new JFrame();
            getContentPane().add(mainPanel);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(505, 317);
            setLocationRelativeTo(null);
            setResizable(false);
            setVisible(true);
        }
     
        public static void showWindow(int finalScore) {
     
            new ScoreWindow(finalScore);
        }
     
        public static void main(String[] args) {
     
            ScoreWindow.showWindow(3642);
        }
    }

    the orignal AnimatedNumber.class
    package newpackage;
     
    import java.awt.Image;
    import java.util.ArrayList;
    import javax.swing.ImageIcon;
     
    /**
     *
     * @author 
     */
     
    public class AnimatedNumbers {
     
        private ArrayList numberImageList;
        private int numberImageIdx;
        private int x;
        private int delay;
     
        public AnimatedNumbers(int numberImageIdx, int x) {
     
            numberImageList = new ArrayList();
            this.numberImageIdx = numberImageIdx;
            setNumberImages();
            this.x = x;
            delay = 0;
        }
     
        public AnimatedNumbers(int x) {
     
     
            numberImageList = new ArrayList();
            setNumberImages();
            this.x = x;
            delay = 0;
        }
     
        private void setNumberImages() {
     
            for (int i = 0; i < 10; i++) {
     
                numberImageList.add(new ImageIcon("C:\\KKKFOLDER\\numbers\\" + i + ".png").getImage());
            }
        }
     
        public Image getCommaImage() {
     
            return new ImageIcon("C:\\KKKFOLDER\\numbers\\comma.png").getImage();
        }
     
        public Image getNumberImage() {
     
            return (Image) numberImageList.get(numberImageIdx);
        }
     
        public void move() {
     
            x--;
        }
     
        public int getX() {
     
            return x;
        }
     
        public void updateDelay() {
     
            delay++;
        }
     
        public int getDelayValue() {
     
            return delay;
        }
    }

    Errors being thrown (1st run/execution)
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Object cannot be cast to newpackage.AnimatedNumbers
    true
    	at newpackage.ScoreWindow$ScoreWindowAnimationPanel.actionPerformed(ScoreWindow.java:146)
    true
    true
    true
    true
    	at javax.swing.Timer.fireActionPerformed(Timer.java:291)
    	at javax.swing.Timer$DoPostEvent.run(Timer.java:221)
    	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
    	at java.awt.EventQueue.access$000(EventQueue.java:84)
    	at java.awt.EventQueue$1.run(EventQueue.java:602)
    	at java.awt.EventQueue$1.run(EventQueue.java:600)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

    2nd run/ execution
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Object cannot be cast to newpackage.AnimatedNumbers
    	at newpackage.ScoreWindow$ScoreWindowAnimationPanel.actionPerformed(ScoreWindow.java:146)
    	at javax.swing.Timer.fireActionPerformed(Timer.java:291)
    	at javax.swing.Timer$DoPostEvent.run(Timer.java:221)
    	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
    	at java.awt.EventQueue.access$000(EventQueue.java:84)
    	at java.awt.EventQueue$1.run(EventQueue.java:602)
    	at java.awt.EventQueue$1.run(EventQueue.java:600)
    true
    true
    true
    true
    true
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

    the way it throws me an error seems a little bit different on every run i make
    Last edited by chronoz13; June 21st, 2011 at 09:18 AM.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: ArrayList object's elements confusing??? doesnt replace the elements? set() metho

    Is it possible for the code looking in the arraylist to be executed before the arraylist contents have been changed from Object objects to AnimatedNumber objects?

    Don't start the timer until AFTER the contents of the arraylist is correct.

    Why do you add Object then immediately replace them with AnimatedNumber???

  6. The Following User Says Thank You to Norm For This Useful Post:

    chronoz13 (June 21st, 2011)

  7. #6
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: ArrayList object's elements confusing??? doesnt replace the elements? set() metho

    Don't start the timer until AFTER the contents of the arraylist is correct
    oh yeah! how stupid i am never thinking that i should have let the program finished all the initialization before starting the timer. thanks !! its solved it

    Why do you add Object then immediately replace them with AnimatedNumber???
    well it has something to do with my recent post about how to set an array list with a fixed size, it said there its not possible so what i did is this,
    because I need to insert something in the middle of the array, and i need an arraylist object so in case i want to add more, it will be an easy task to do withjust the .add() method

    Don't start the timer until AFTER the contents of the arraylist is correct.
    thanks for reminding me this one :p

  8. #7
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: ArrayList object's elements confusing??? doesnt replace the elements? set() metho

    Quote Originally Posted by chronoz13 View Post
    .. how to set an array list with a fixed size, it said there its not possible ... and i need an arraylist object so in case i want to add more, it will be an easy task...
    ??? If you could set an ArrayList to be fixed size, you wouldn't be able to add more... You can add more because it isn't fixed size. If you want fixed size use an array; if you don't want fixed size, use an ArrayList. That's it.

  9. #8
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: ArrayList object's elements confusing??? doesnt replace the elements? set() metho

    ??? If you could set an ArrayList to be fixed size, you wouldn't be able to add more... You can add more because it isn't fixed size. If you want fixed size use an array; if you don't want fixed size, use an ArrayList. That's it.
    well yeah it totally make sense, maybe im wrong with my own statement, i was brought down with the idea of the "fixed sized" thing, because the main concern with the program is that i just want to insert something on the middle of the same arraylist object :p, first thing came up to my mind is to have a fixed size
    :p

  10. #9
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: ArrayList object's elements confusing??? doesnt replace the elements? set() metho

    Quote Originally Posted by chronoz13 View Post
    ... i just want to insert something on the middle of the same arraylist object :p, first thing came up to my mind is to have a fixed size
    'Fixed size' means no adding or inserting when full; but you can replace items.

  11. #10
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: ArrayList object's elements confusing??? doesnt replace the elements? set() metho

    maybe i should be careful more with my statements on the future, i should have said Initial size not a fixed size
    << im sloppy

  12. #11
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: ArrayList object's elements confusing??? doesnt replace the elements? set() metho

    No problem - recognizing a mistake is half the battle; it pays to be precise - and it's good practice for writing code

    I think your original information was mistaken - you can set the initial size for an ArrayList. Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. You can pass this initial capacity to the constructor:

    ArrayList al = new ArrayList(10);  // create with initial size of 10.

Similar Threads

  1. Comparing elements of an arrayList with an array?
    By DudeJericho in forum Collections and Generics
    Replies: 2
    Last Post: April 21st, 2011, 12:39 PM
  2. Duplicate elements in 2 Arraylist
    By tcstcs in forum Collections and Generics
    Replies: 3
    Last Post: April 18th, 2011, 12:56 AM
  3. [SOLVED] Gap between GUI elements
    By petemyster in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 15th, 2011, 11:44 AM
  4. accessing elements in a 2d ArrayList
    By Flamespewer in forum Collections and Generics
    Replies: 2
    Last Post: March 8th, 2010, 06:11 PM
  5. Method Adding elements to an array with certain restrictions
    By Newoor in forum Collections and Generics
    Replies: 1
    Last Post: December 13th, 2009, 11:13 AM