Results 1 to 18 of 18
  1. #1
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default Cellular Automata Update Problem

    Hi, I am writing a program that is basically a generic cellular automaton program, where I save cell states in the form of numbers in an array.
    Now, I ask the user to input the number of steps he wants to run, and then i call an update function using the following code:
    Java Code:
    else if( ev.getSource() == startButton5 ){  // start  running
       running = true; int c=0; 
       do {
                da5.repaint();
                exchanges.update(running); da5.repaint(); c++; 
            }while(c<steps);}
    As you can see, I tried calling the repaint() method before and after updation. But somehow the paintComponent only gets called at the very last run of the loop, ie when c=steps-1.
    I can't seem to find out why this is happening.
    My updation code is:
    Java Code:
    public void update(boolean sweep)
        {  
          System.out.println("Enter the matrix!");
            int maxValue = set[0][0];  
      for(int i=1;i < set.length;i++){  
        if(set[i][0] > maxValue){  
          maxValue = set[i][0];  
        }  
      }  
      int minValue = set[0][0];  
      for(int i=1;i<set.length;i++){  
        if(set[i][0] < minValue){  
          minValue = set[i][0];  
        }  
      }  
      System.out.println(set.length);
            for(int col=0; col<width; col++)
            {
                for( int row=0; row<height; row++)
                {
                    int count = 0; 
                    if(  ( (col-13+set[0][1]) >= 0 ) && ((row-10+minValue) >= 0) && ( (col-13+set[set.length-1][1]) < width) && (row-10+maxValue)<height ) 
                    {
                          //working till here
                        for( int r=0; r<rules.length; r++)        //no of rules and no of states will be required
                        {
                            if (cells1[col][row] == child [r][0][0])
                        {  
                            
                            for( int i=0; i<set.length; i++)
                            {
                                
                       if(rules[r][set[i][1]][set[i][0]] == cells1[col-13+set[i][1]][row-10+set[i][0]])                      
                                count++;                        
                            
                        }
                        if(count == set.length) {buffer1[col][row] = child[r][1][0];}
                        count = 0;
                       }
                }
            }
        }}   
        for (int i=0; i<width; i++)
        {
            for(int j=0; j<height; j++)
            {    
            cells1 [i][j] = buffer1 [i][j];  // new = old
        }      
        }
    }
    Number 2: I have installed a Stop Button on the menu to stop the iteration if the user wishes, but I don't know how to apply it to this particular problem.
    So, if you can help me with any of these two problems, please try.
    Cheers.

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,727
    Blog Entries
    7
    Rep Power
    21

    Default

    You're calling this all from your ActionListener; the actionPerformed( ... ) method is called in the EDT (Event Dispatch Thread) which also has to take care of repainting components; it can't do that because it's busy running your code (in the actionPerformed( ... ) method). All your repaint() calls have to wait until the EDT can handle them, hence you see only the last repaint() in its queue. You have to start another thread from your actionPerformed( ... ) method that does the update of your CA and calls repaint() so the EDT can handle it asap.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default

    That makes sense. But I don't know how to start another thread. How do I do that? What modifications do I make? You can tell me verbally, or send me a link. No spoon feeding.

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,453
    Rep Power
    20

    Default

    Lesson: Concurrency in Swing (The Java™ Tutorials > Creating a GUI With JFC/Swing)

    Particularly the section dealing with SwingWorker, and its process(...) and publish(...) methods.

    db

  5. #5
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,727
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by DarrylBurke View Post
    Lesson: Concurrency in Swing (The Java™ Tutorials > Creating a GUI With JFC/Swing)

    Particularly the section dealing with SwingWorker, and its process(...) and publish(...) methods.
    What Darryl said; also it doesn't hurt to read the API documentation of the Thread and Timer classes.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  6. #6
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default

    I still don't get what I'm supposed to do.
    Will this work?
    Java Code:
     protected void done() {
               try {
                   da5.repaint();
               } catch (Exception ignore) {
               }
           }
    Do I remove implements ActionListener from the class definition, and just add it to the jButton? Or simple write extends SwingWorker in front?

  7. #7
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default

    Will I write it like this?

    Java Code:
    public void doInBackground() {
               exchanges.update();
           }
     protected void done() {
               try {
                   da5.repaint();
               } catch (Exception ignore) {
               }
    }
    But again, how do I call the method?

  8. #8
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default

    I did some jiggling and ended up with this classic error. :D
    I am close to throwing my hands up in the air and screaming!

    Exception in thread "AWT-EventQueue-0" java.lang.IllegalThreadStateException
    at java.lang.Thread.start(Thread.java:638)
    at Iteration1.actionPerformed(Iteration1.java:277)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel

  9. #9
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,727
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by samanyu View Post
    I did some jiggling and ended up with this classic error. :D
    I am close to throwing my hands up in the air and screaming!
    That stack trace tells us that you're calling Thread.start() in your actionPerformed( ... ) method; you haven't show us your code yet so there's nothing we can do.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  10. #10
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default

    It's pretty big.

    Java Code:
    import javax.swing.*;    // the Java eXtensions "Swing" graphics kit
    import java.awt.*;       // the Java  Abstract Windowing Toolkit
    import java.awt.image.*; // the AWT image  package
    import java.awt.geom.*;  // AWT geometry 
    import java.awt.event.*; // AWT Event Management  package
    import java.io.*;        // I/O package
    
    // Iterated brahma  with some simplified  con5trols and cell editing capabilities
    import javax.swing.*;    // the Java eXtensions "Swing" graphics kit
    import java.awt.*;       // the Java  Abstract Windowing Toolkit
    import java.awt.image.*; // the AWT image  package
    import java.awt.geom.*;  // AWT geometry
    import java.awt.event.*; // AWT Event Management  package
    import java.io.*;        // I/O package
    
    // Iterated brahma  with some simplified  con5trols and cell editing capabilities
    public class Iteration1 extends JFrame implements ActionListener,Runnable{
    
        Thread t;
        private static final int DISP_WIDTH  = 600;  // constants
        private static final int DISP_HEIGHT = 600;
        private static final int MNU_HEIGHT    = 44;
        public static int CELL_PXL    = 20;
        private static final int FPS = 5;
    
    
    
        public Container con5 = null;
        public DisplayArea5 da5 = null;
        public Iteration2 exchanges = null;
    
        public static Iteration1 obj1;
        public boolean running = false;
        public static int steps =100;
    
        public static void main (String args[]) throws IOException
        {
            obj1=new Iteration1();
        }
    
    
    
    
    
        public Iteration1(){  // con5structor set up thread loops
        super("Brahma-II");
        JFrame frame5 = new JFrame("Brahma-II");
            frame5.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(true);
        con5 = getContentPane();
        con5.setLayout(null);
        System.out.println("1");
        exchanges = new Iteration2( DISP_WIDTH/CELL_PXL, DISP_HEIGHT/CELL_PXL);
    
        setupMenus5();
    
    
        System.out.println("2");
    
        da5 = new DisplayArea5( new Rectangle( 0, 0, DISP_WIDTH+5, DISP_HEIGHT+5 ) );
        con5.add( da5 );
        System.out.println("3");
        con5.addMouseListener( da5 );
        repaint();
        setVisible(true);
    
        resizeToInternalSize5( DISP_WIDTH, DISP_HEIGHT + MNU_HEIGHT);
        System.out.println("4");
    
    
        }
        public void resizeToInternalSize5( int internalWidth, int internalHeight ){
        Insets insets = getInsets();
        final int newWidth  = internalWidth  + insets.left + insets.right;
        final int newHeight = internalHeight + insets.top  + insets.bottom;
        Runnable resize = new Runnable(){ // an anonymous inner class
            public void run(){
                setSize( newWidth, newHeight);
            }
        };
        if(!SwingUtilities.isEventDispatchThread() ){
            try{
            SwingUtilities.invokeAndWait( resize );
            }catch( Exception e ) { }
        }
        else{
            resize.run();
        }
        validate(); System.out.println("11");
        }
    
    
        public JMenuBar menuBar5;
    
        public JMenu fileMenu5;
        public JMenuItem saveItem5;
        public JMenuItem openItem5;
        public JMenuItem clearItem5;
        public JMenuItem exitItem5;
    
        public JMenu gridMenu5;
        public JMenuItem openRulItem5;
        public JMenuItem gridSizeItem5;
        public JMenuItem thirty;
        public JMenuItem fifty;
        public JMenuItem hundred;
    
        public JButton startButton5;
        public JButton stopButton5;
        public JButton stepButton5;
    
        public JTextField stepParameter;
    
        public JLabel cellCount;
    
        public void setupMenus5(){
    
        menuBar5 = new JMenuBar();
        this.setJMenuBar(menuBar5 );
    
        fileMenu5 = new JMenu("File");
        menuBar5.add( fileMenu5 );
    
        saveItem5 = new JMenuItem("Save Grid");
        saveItem5.addActionListener( this );
        fileMenu5.add(saveItem5);
    
        openItem5 = new JMenuItem("Open Grid");
        openItem5.addActionListener( this );
        fileMenu5.add(openItem5);
    
        clearItem5 = new JMenuItem("Clear Grid");
        clearItem5.addActionListener( this );
        fileMenu5.add(clearItem5);
    
        fileMenu5.add( new JSeparator() );
    
        exitItem5 = new JMenuItem("Exit");
        exitItem5.addActionListener( this );
        fileMenu5.add(exitItem5);
    
    
        fileMenu5 = new JMenu("Grid");
        menuBar5.add( fileMenu5 );
    
        gridSizeItem5 = new JMenu("Grid Size");
        gridSizeItem5.addActionListener( this );
    
        thirty = new JMenuItem("30x30");
        thirty.addActionListener( this );
        gridSizeItem5.add(thirty);
    
    
        fifty = new JMenuItem("50x50");
        fifty.addActionListener( this );
        gridSizeItem5.add(fifty);
        hundred = new JMenuItem("100x100");
        hundred.addActionListener( this );
        gridSizeItem5.add(hundred);
    
        fileMenu5.add(gridSizeItem5);
    
        openRulItem5 = new JMenuItem("Load Rules");
        openRulItem5.addActionListener( this );
        fileMenu5.add(openRulItem5);
    
        fileMenu5.add( new JSeparator() );
    
    
        startButton5 = new JButton("Start");
        startButton5.addActionListener( this );
        menuBar5.add(startButton5);
        System.out.println("6");
    
        stopButton5 = new JButton("Stop");
        stopButton5.addActionListener( this );
        menuBar5.add(stopButton5);
    
        stepButton5 = new JButton("1-Step");
        stepButton5.addActionListener( this );
        menuBar5.add(stepButton5);
    
        menuBar5.add( new JLabel("Steps: " ) );
        stepParameter = new JTextField("Enter no of steps" );
        stepParameter.setEditable(true );
        stepParameter.addActionListener( this );
        menuBar5.add( stepParameter );
    
        menuBar5.validate();
    
        }
     public void run() {
                        da5.repaint();
            }
        public void actionPerformed( ActionEvent ev ){
    
            if( ev.getSource() == exitItem5 ){  // handle  EXIT
            System.exit(5);
        }
        else if( ev.getSource() == saveItem5 ){  // handle  saving  to  file
            JFileChooser chooser = new JFileChooser( new File( System.getProperty("user.dir", "." ) ) );
            int returnVal = chooser.showSaveDialog(this);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                File myFile = chooser.getSelectedFile();
            try{
                FileOutputStream fin = new FileOutputStream( myFile );
                ObjectOutputStream oin = new ObjectOutputStream( fin );
                oin.writeObject(exchanges.cells1);
                oin.writeObject(exchanges.buffer1);
                fin.close();
            }catch( Exception e ){
                System.out.println("Error Saving file: " +  myFile.getName() );
                e.printStackTrace();
            }
            }
        }
        else if( ev.getSource() == openItem5 ){  // handle  reloading from file
            JFileChooser chooser = new JFileChooser( new File( System.getProperty("user.dir", "." ) ) );
            //      JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(this);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
            File inputFile = chooser.getSelectedFile();
            try{
                FileInputStream fot = new FileInputStream( inputFile );
                ObjectInputStream oot = new ObjectInputStream( fot );
                exchanges.cells1 = (int[][])oot.readObject();
                exchanges.buffer1 = (int[][])oot.readObject();
                fot.close();
            }catch( Exception e ){
                System.out.println("Error Opening file: " +  inputFile.getName() );
                e.printStackTrace();
            }
            } da5.repaint();
        }
    
    
        else   if( ev.getSource() == openRulItem5 ){  // handle  reloading from file
            JFileChooser chooser = new JFileChooser( new File( System.getProperty("user.dir", "." ) ) );
            //      JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(this);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
            File inputFile = chooser.getSelectedFile();
            try{
                FileInputStream fis = new FileInputStream( inputFile );
                ObjectInputStream ois = new ObjectInputStream( fis );
                exchanges.set=(int[][])ois.readObject();
                exchanges.rules = (int[][][])ois.readObject();
                exchanges.child = (int[][][])ois.readObject();
                fis.close();
            }catch( Exception e ){
                System.out.println("Error Opening file: " +  inputFile.getName() );
                e.printStackTrace();
            }
            } for ( int r=0; r<exchanges.rules.length; r++)
            {
                for(int i=exchanges.set[0][1]; i< 15; i++)
                {   int j=10;
                    System.out.println(r+", "+i+", "+j+" = " + exchanges.rules[r][i][j] );}}
    
                    for(int i=0; i<exchanges.set.length; i++)
                    System.out.println(exchanges.set[i][1] + " " +exchanges.set[i][0]);
        }
        else if( ev.getSource() == stepParameter ){  // handle user entering a new p value
            try{
            steps=Integer.parseInt( stepParameter.getText() ); System.out.println(steps);
            }catch( Exception e ){}
           }
        else if ( ev.getSource() == clearItem5)
        {
            exchanges.blank(0); da5.repaint(); da5.repaint();
        }// process the con5trol events
        else if( ev.getSource() == startButton5 ){  // start  running
                int c=0;
            
            do {
                da5.repaint();
                 exchanges.update(running); t=new Thread(obj1); t.start(); c++; System.out.print(" this is step no:" +(c+1)); t.stop();
            }while(c<steps);
            
        }
        else if( ev.getSource() == stopButton5 ){  // stop background thread
            running = false; exchanges.update(running); da5.repaint();
        }
        else if( ev.getSource() == stepButton5 ){  // do exactly ONE step
            running = true; exchanges.update(running); running= false;
            da5.repaint();
        }
        else if( ev.getSource() == thirty ) {
            CELL_PXL=20; exchanges = new Iteration2( DISP_WIDTH/CELL_PXL, DISP_HEIGHT/CELL_PXL);
            da5 = new DisplayArea5( new Rectangle( 0, 0, DISP_WIDTH+5, DISP_HEIGHT+5 ) );
            da5.repaint(); da5.repaint();
        }
            else if( ev.getSource() == fifty){
                CELL_PXL=12; exchanges = new Iteration2( DISP_WIDTH/CELL_PXL, DISP_HEIGHT/CELL_PXL);
            da5 = new DisplayArea5( new Rectangle( 0, 0, DISP_WIDTH+5, DISP_HEIGHT+5 ) );
            da5.repaint(); da5.repaint();
        }
    
            else if(  ev.getSource() == hundred) {
                CELL_PXL=6;
            exchanges = new Iteration2( DISP_WIDTH/CELL_PXL, DISP_HEIGHT/CELL_PXL);
            da5 = new DisplayArea5( new Rectangle( 0, 0, DISP_WIDTH+5, DISP_HEIGHT+5 ) );
            da5.repaint(); da5.repaint();
        }
    }
    
    
    }
    
    
    
        class DisplayArea5 extends JPanel implements MouseListener{
            
            public Iteration2 exp = null;
    
        public DisplayArea5( Rectangle bounds ){  // default con5structor
            setLayout(null);
            setBounds( bounds);
            setOpaque(false);
            setPreferredSize( new Dimension (bounds.width, bounds.height )  );
            exp = new Iteration2( 600/Iteration1.CELL_PXL, 600/Iteration1.CELL_PXL);
            repaint();
            System.out.println( "this is pixel size : " + Iteration1.CELL_PXL);
        }
    
        public void paintComponent( Graphics g ){  // main rendering  recipe
            Graphics2D g5 = (Graphics2D)g;
            System.out.println("a");
            g5.setColor( Color.black );
            g5.fillRect( 0, 0, getWidth()-1, getHeight()-1 );
            System.out.println("b");
            int w = Iteration1.CELL_PXL; int wid= 0; int hgt= 0;
            int h = Iteration1.CELL_PXL;
            if( Iteration1.CELL_PXL==20) {wid=30; hgt=30;} else if( Iteration1.CELL_PXL==12) {wid=50; hgt=50;} else if( Iteration1.CELL_PXL==6) {wid=100; hgt=100;}
            for(int col=0;col<wid;col++){
                for(int row=0;row<hgt;row++){
                    for(int k=0; k<11; k++){  //replaced with works1.l                    
                if( exp.cells1[col][row] == k ){
                if( exp.buffer1[col][row] == exp.cells1[col][row] ) 
                    g5.setColor( exp.colarray[k] ); // is and was a cooperator
                }
                
                }
                
                
                g5.fillRect( col * w +1, row * h +1, w-2, h-2 );
            }
            
    
        }
        System.out.println("9");}
    
        public void mousePressed(  MouseEvent mev ){}
        public void mouseReleased( MouseEvent mev ){}
        public void mouseEntered(  MouseEvent mev ){}
        public void mouseExited(   MouseEvent mev ){}
    
        public void mouseClicked(  MouseEvent mev ){
            int i = mev.getX() / Iteration1.CELL_PXL;
            int j = mev.getY() / Iteration1.CELL_PXL;
            if( i < exp.width && j < exp.height ){
            for (int k=0; k<11; k++){
            if( exp.cells1[i][j] == k ){ // toggle the value
                exp.cells1[i][j] = k+1;
                exp.buffer1[i][j] = k+1;
                break;
            }}
            if (exp.cells1[i][j] == (11)){
                exp.cells1[i][j] = 0;
                exp.buffer1[i][j] = 0;  // toggles the old behaviour too for clarity
            }
           
            repaint();
            }System.out.println("10");
        }
    }
    
     class Iteration2 {  // Iterated Prisoner's Dilemma on x,y grid
    
        public static int cells1[][];       // our 2D array of prisoner cells1
        public static int buffer1[][];      // use this for an intermediate update buffer1
        public static int tmp[][];         // use as a reference (uninstantiated) to do the swapover
        int width;                  // number of player cells1 horizontally
        int height;                 // number of player cells1 vertically
        public boolean sweeping = false;
        public int set[][];
        public int rules[][][];
        public int child[][][];// controls the update algorithm used
        Color[] colarray = {Color.blue, Color.green, Color.yellow, Color.red, Color.orange, Color.cyan, Color.magenta, Color.pink, Color.lightGray, Color.darkGray, Color.white};
        private DisplayArea5 da6= null;
            
        public int count(int val){  // count number of cells1 equal to val
        int n = 0;
        for(int col=0;col<width;col++){
            for(int row=0;row<height;row++){
            if( cells1[col][row] == val ) n++;
            }
        }
        return n;
        }
        
        public void blank(int  val){   // clear all the cells1 to val (either DEFECTOR or COOPERATOR)
        
            for(int col=0;col<width;col++){
            for(int row=0;row<height;row++){
                cells1[col][row] = val;
                buffer1[col][row] = cells1[col][row];
            }
            }
        
        }
        
        public void update(boolean sweep)
        {  
          System.out.println("Enter the matrix!");
            int maxValue = set[0][0];  
      for(int i=1;i < set.length;i++){  
        if(set[i][0] > maxValue){  
          maxValue = set[i][0];  
        }  
      }  
      int minValue = set[0][0];  
      for(int i=1;i<set.length;i++){  
        if(set[i][0] < minValue){  
          minValue = set[i][0];  
        }  
      }  
      System.out.println(set.length);
            for(int col=0; col<width; col++)
            {
                for( int row=0; row<height; row++)
                {
                    int count = 0; 
                    if(  ( (col-13+set[0][1]) >= 0 ) && ((row-10+minValue) >= 0) && ( (col-13+set[set.length-1][1]) < width) && (row-10+maxValue)<height ) 
                    {
                          //working till here
                        for( int r=0; r<rules.length; r++)        //no of rules and no of states will be required
                        {
                            if (cells1[col][row] == child [r][0][0])
                        {  
                            
                            for( int i=0; i<set.length; i++)
                            {
                                
                            if( rules[r][set[i][1]][set[i][0]] == cells1 [col-13+set[i][1]][row-10+set[i][0]] )                      
                                { count++; }                       
                            
                        }
                        if(count == set.length) {buffer1[col][row] = child[r][1][0];}
                        count = 0;
                       }
                }
            }
        }}
        
        
        for (int i=0; i<width; i++)
        {
            for(int j=0; j<height; j++)
            {  
        
            cells1 [i][j] = buffer1 [i][j];  // new = old
        }      
        }
         
    
    }
      
        // initialise the system with fraction pInit defectors
        Iteration2( int w, int h){
        width = w;
        height = h;
        cells1  = new int[w][h];
        buffer1 = new int[w][h];
        
        }   
    }

  11. #11
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,727
    Blog Entries
    7
    Rep Power
    21

    Default

    I don´t see a Timer nor a SwingWorker anywhere ... please show us a small example program that shows your problem and we can run, we are not going to wade through all that irrelevant code.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  12. #12
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    Good grief - that can't all be relevant, surely?

    Some tips:
    Try to use meaningful variable names that say what an object is or does - 't' is not a useful name for a Thread.
    Always read the API docs before using classes or methods you are unfamiliar with. Thread.stop() is not a method you should be using - and anyhow, it's pointless to call it 2 lines after Thread.start()...
    Don't just blindly hack code into your application in the hope that it will fix the problem - you must understand what the problem is, why you're getting it, and how to fix it before you write any code - otherwise, you'll probably just make things worse.

    For example, every time round a 100 iteration loop, you're creating a new thread, starting it, and immediately stopping it, and all each thread does is a single repaint call. This is not how threads are used. Also, if a background process needs to interact with the GUI (such as requesting a repaint), it should be run as a SwingWorker, not an ordinary thread. If you'd read and understood the tutorial linked by DarrylBurke, you'd be aware of this, and you'd know why it is necessary. Sure, it takes time to read and understand the docs and tutorials, but if you don't, you'll waste 10x as much time being annoyed and frustrated because you don't know what you're doing - and what's far worse, you'll also waste our time too

  13. #13
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default

    Okay, I will put some more time understanding it. Just by the way, does a 64bit system execute code differently from a 32bit system?

  14. #14
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default

    I read all the documentation and examples in the tutorial, and I understand what I'm supposed to do. But I don't know how to apply it to my program. The classes are already defined in my program, and the array used for repainting the cells in the DisplayArea class is stored in a class called Iteration2.

    If i extend the SwingWorker class to the class which contains the main() method, Iteration1, then what do I write in place of the second parameter? Iteration2? I need to avoid creating any more classes, as I am afraid the bugs will just keep on increasing.

    Secondly, each array needs to be updated immediately after its values change. So, the repaint() method will need to be called after every update. Is there some way I can modify the program so I can simply press start and get real time calls to repaint() immediately after the update() method is called?

    I saw an example program online, but it doesn't execute on my laptop when I press the start button, however it is executing on another laptop. I checked and re-checked my Environment variables, they seem all right, but when I use c-prompt to compile the program, it throws errors, and if I force the program to still run, it throws a no class found exception. I am confused and need help.

  15. #15
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    Quote Originally Posted by samanyu View Post
    ... does a 64bit system execute code differently from a 32bit system?
    As far as Java is concerned, no.

  16. #16
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,453
    Rep Power
    20

    Default

    Java Code:
    do {
                da5.repaint();
                 exchanges.update(running); t=new Thread(obj1); t.start(); c++; System.out.print(" this is step no:" +(c+1)); t.stop();
            }while(c<steps);
    A Thread can be started only once. Didn't you read the documentation to see when start() throws that exception?

    db

    edit Also read this

  17. #17
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    Quote Originally Posted by samanyu View Post
    I read all the documentation and examples in the tutorial, and I understand what I'm supposed to do.
    Really?

    If i extend the SwingWorker class to the class which contains the main() method, Iteration1
    I don't know what you mean by that. You don't need to extend SwingWorker.

    then what do I write in place of the second parameter? Iteration2?
    What second parameter? You need to explain exactly what classes and methods you're talking about, and why you're considering whatever it is you're thinking of - I'm not a mind reader.


    I need to avoid creating any more classes, as I am afraid the bugs will just keep on increasing.
    Each class should have a single, clearly defined role or task, so you should have as many classes as are necessary to achieve the required goal. You're more likely to get more bugs if you try to do too many things in a class than if you split it into simple easy to understand classes that can work together.

    I would also recommend moving each of the button handlers in the actionPerformed method, and some of the code in those deeply nested loops, into separate methods, so you can follow what's going on more easily. I find the code almost unreadable as it is - with those huge great chunks of code, I certainly can't see how it's supposed to work.

    Secondly, each array needs to be updated immediately after its values change.
    I don't understand - if the array values change, the array has been updated, surely?

    Is there some way I can modify the program so I can simply press start and get real time calls to repaint() immediately after the update() method is called?
    If you want to get repaints done from a SwingWorker, override the 'process' method to do the update and repaint, and call the 'publish' method from 'doInBackground' - this will call 'process' in the Swing EDT (Event Dispatch Thread) [I thought you said you'd read and understood the SwingWorker tutorial?]. If you want to repaint from the Swing EDT as normal, that is, not from another thread, just call repaint after whatever updates you make.

    I saw an example program online, but it doesn't execute on my laptop when I press the start button, however it is executing on another laptop. I checked and re-checked my Environment variables, they seem all right, but when I use c-prompt to compile the program, it throws errors, and if I force the program to still run, it throws a no class found exception. I am confused and need help.
    If you want help with another application, it's probably better to start a new thread, but if you think it is directly relevant to this thread, post up the full text of the error messages and stack trace if present, and explain what it is you are confused about.

  18. #18
    samanyu is offline Member
    Join Date
    Jun 2011
    Location
    Tsukuba, Japan
    Posts
    63
    Rep Power
    0

    Default

    I modified the code so that it works without using the SwingWorker class, now the problem is that sometimes, a part of the update hasn't finished by the time the repaint method is called, so while the program works fine for the second half of my grid, it sometimes stays blank on the first half.

    Is there a simple statement that ensures that the update is complete before moving to repaint? Such as can I use Thread.wait() and Thread.notify? The methods are being called from the Iteration1 class, whereas the update method is in the Iteration2 class, does this mean I have to use objects to call the wait() and notify() methods?

    Also, is it faster to access an array row by row, as in left to right then next row and so on, rather than column wise, ie. top to bottom and then next column and so on?

Similar Threads

  1. 1-D Cellular Automata
    By cest.lavie16 in forum New To Java
    Replies: 1
    Last Post: 04-25-2011, 08:40 PM
  2. Replies: 6
    Last Post: 02-05-2010, 05:53 PM
  3. Problem in update
    By Shivraj in forum NetBeans
    Replies: 0
    Last Post: 03-24-2009, 01:11 PM
  4. Some help needed: 2D Cellular Automata
    By markus-sukram in forum AWT / Swing
    Replies: 1
    Last Post: 04-27-2008, 09:02 PM
  5. Replies: 1
    Last Post: 03-17-2008, 01:59 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •