Click here to Skip to main content
13,352,157 members (77,632 online)
Rate this:
Please Sign up or sign in to vote.
See more:
Each time the button is pressed, the result is saved as an arrayList to another arrayList. Problem is it's appending it to the previous element. I need to be able to add the results of each press as a separate element. For example: first press: [5, 3, 5, 2, 6, 5] second press would display: [5, 3, 5, 2, 6, 5][2, 1, 4, 1, 4, 1] This way I can loop through and get each array result separately. How do I do this?

public class mainClass{
        public static void main(String[] args){
JFrame frame1 = new JFrame("testButton");
frame1.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE);
buttonExample b1 = new buttonExample();


    public class Example {
            private int rand1;
            private ArrayList<ArrayList> count;
            private ArrayList<Integer> count2;
            private Random rnd;
            private int counter1;
            private ArrayList<ArrayList>count3;
        public Example(){
            count = new ArrayList<ArrayList>();
            count2 = new ArrayList<Integer>();
            rnd = new Random();
            count3 = new ArrayList<ArrayList>();
        private void addCount2(){
            for(int x = 0; x<6;x++){
            rand1 = rnd.nextInt(6)+1;
            count2.add(rand1);// count2 == Integers

        public void addCount(){
            count.add(count2);// count == count3
        public ArrayList<ArrayList> displayCount(){
        return count;


public class buttonExample extends JPanel {
private JButton button1;
private Example example1;
public buttonExample(){
button1 = new JButton("Submit");
button1.addActionListener(new ButtonListener());
example1 = new Example();
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
Posted 9-Dec-12 7:07am
Updated 9-Dec-12 20:48pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Problem is in function addCount2(). You are extending the List of count2, instead you should init it new to delete the "old values":

 private void addCount2(){
      count2 = new ArrayList<integer>(); // set up count2 clean and new and EMPTY!
      for(int x = 0; x<6;x++){
      int rand1 = rnd.nextInt(6)+1;
      count2.add(rand1);// count2 == Integers

You should also limit the scope of some variables some are only used in single functions and should therefor only exist in there.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web04 | 2.8.180111.1 | Last Updated 10 Dec 2012
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100