Results 1 to 9 of 9
  1. #1
    ki_ha1984 is offline Member
    Join Date
    Aug 2011
    Posts
    74
    Rep Power
    0

    Default Start a Method from other Class in background

    Hello,

    I am new to Java and i have a problem.
    I try to create a monitoring window of a game with some components.
    In the method sample2() from class sample my games starts with thousands repetition.

    I want to start the game by pressing the Start button, but when i press the button all the Jpanel stuck until the end of the game. I think that i need to run in background the method and continue monitoring with JfreeChart.

    Also i need to pause the running of the sample2() method fromsample class in order to change some attributions. How to pause it by pressing the Pause button ??
    I have here the classes.


    testvre.java
    Java Code:
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    
    public class testvre extends JFrame implements ActionListener{
        JPanel Firstpanel = new JPanel();
        GridLayout  layout2 = new GridLayout(1,3);
        JButton Start, Pause, Stop;
        public testvre(){
        
            Firstpanel.setLayout(layout2);
            Firstpanel.add(Start = new JButton("Start"));
            Start.addActionListener(this);
            Firstpanel.add(Pause = new JButton("Pause"));
            Pause.addActionListener(this);
            Firstpanel.add(Stop = new JButton("Stop"));
            Stop.addActionListener(this);
        add(Firstpanel);
        
        }
        
        public void actionPerformed( ActionEvent event )
    	{       System.out.println( event );
                if(event.getSource() == Start){
                  System.out.println("start");            
                        
                  sample.sample2();
    
                    }
                else if(event.getSource() == Pause){
                    System.out.println("Pause");  
                    }
                else if(event.getSource() == Stop){
                    System.out.println("Stop");  
                    }else { 
                    }    
            }   
     
    }

    sample.java
    Java Code:
    public class sample {
      
        public static void sample2(){  
            for (int i = 0; i < 1000000; i++) {
                System.out.println(i);
                
                //here starts my game
            }
        }
        public static void main( String args[] )
    	{
    		testvre mainFrame = new testvre();
    		mainFrame.setVisible( true );
                    mainFrame.setSize(700, 500);
                    mainFrame.setResizable(false);
    	}
    }

    Thank you in Advanced

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Start a Method from other Class in background

    Yes, you need to use a background thread for this such as that which is available with a SwingWorker object. Google for "Concurrency in Swing" and check out the first link. What are you doing inside that huge for loop anyway?

  3. #3
    ki_ha1984 is offline Member
    Join Date
    Aug 2011
    Posts
    74
    Rep Power
    0

    Default Re: Start a Method from other Class in background

    Thank you for your answer, i will about the Concurrency in swing and i will inform you.
    In the for loop is running an AI strategy board game. I need to control and monitor the game from my panel. The game is running many time because is a tournament style and i try to monitoring the knowledge growth for each player.

    Thank you

    I will inform you about my results.

  4. #4
    ki_ha1984 is offline Member
    Join Date
    Aug 2011
    Posts
    74
    Rep Power
    0

    Default Re: Start a Method from other Class in background

    Thank You very Much Fubarable.

    I tried the "Concurrency in Swing" that you told me and it worked for me.

    I give here the code for someone else who has the same problem and to tell me if is there any wrong in my Code.

    Thank you again.

    sample.java
    Java Code:
    import javax.swing.ImageIcon;
    import javax.swing.SwingWorker;
    
    public class sample {
         
        static Object doWork() {
             try {
                for(int i = 0; i < 100; i++) {                
                    testvre.updateStatus(i);              
                    System.out.println("Start ="+i);
                    if (Thread.interrupted()) {
                        throw new InterruptedException();
                    } 
                    while (testvre.pauseProcessing) {
                        try {
                            Thread.sleep(50);  
                            if (testvre.abortProcessing) {
                                return false;
                            }
                            } catch (InterruptedException e) {}
                    }
                    testvre.Pause.setText("Pause");  
                    Thread.sleep(500);
                }
            }
            catch (InterruptedException e) {
                testvre.updateStatus(0);
                return "Interrupted";  
            }
            return "All Done";         
        }
     
        
        public static void main( String args[] )
    	{
    		testvre mainFrame = new testvre();
    		mainFrame.setVisible( true );
                    mainFrame.setSize(700, 500);
                    mainFrame.setResizable(false);
    	}
    
    }
    testvre.java
    Java Code:
    import SwingWorkerP.SwingWorker;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    
    
    public class testvre extends JFrame implements ActionListener{
        JPanel Firstpanel = new JPanel();
        JPanel p2= new JPanel();
        static JProgressBar progressBar = new JProgressBar();    
        
        GridLayout  layout2 = new GridLayout(3,3);
        JButton Start, Stop;
        public static JToggleButton Pause;
        JLabel statusField;
        static boolean abortProcessing = false, pauseProcessing = false;
        
        SwingWorker worker;
        
        public testvre(){
            Firstpanel.setLayout(layout2);
            Firstpanel.add(Start = new JButton("Start"));
            Start.addActionListener(this);
            Start.setEnabled(true);
            Firstpanel.add(Pause = new JToggleButton("Pause"));
            Pause.addActionListener(this);
            Pause.setEnabled(false);
            Firstpanel.add(Stop = new JButton("Stop"));
            Stop.addActionListener(this);
            Stop.setEnabled(false);
            p2.setLayout(new FlowLayout());
            p2.add(statusField = new JLabel());
            p2.add(progressBar);
            
            Firstpanel.add(p2);
            
        add(Firstpanel);
        }
        
        public void actionPerformed( ActionEvent event )
    	{       
                System.out.println( event );
                if(event.getSource() == Start){
                    System.out.println("start");                        
                    worker = new SwingWorker() {
                        public Object construct() {
                                sample.doWork();
                                return "ok Start";
                        }
                        public void finished() {
                            Start.setEnabled(true);
                            Stop.setEnabled(false);
                            statusField.setText(get().toString());
                        }
                    };
                    worker.start(); 
                    Start.setEnabled(false);
                    Pause.setEnabled(true);
                    Stop.setEnabled(true);
                }
                else if(event.getSource() == Pause){
                    System.out.println("Pause"); 
                    pauseProcessing = Pause.isSelected();
                    Pause.setText("Continue");
                    }            
                else if(event.getSource() == Stop){
                    System.out.println("Stop"); 
                    abortProcessing = true;
                    worker.interrupt();
                    }else { 
                    }    
            }   
       
      public static void updateStatus(final int i) {
            Runnable doSetProgressBarValue = new Runnable() {
                public void run() {
                    progressBar.setValue(i);
                }
            };
            SwingUtilities.invokeLater(doSetProgressBarValue);
        }
    
    }

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Start a Method from other Class in background

    Quote Originally Posted by ki_ha1984 View Post
    Thank You very Much Fubarable.

    I tried the "Concurrency in Swing" that you told me and it worked for me.

    I give here the code for someone else who has the same problem and to tell me if is there any wrong in my Code.
    Is the code not working? I don't recognize the SwingWorker that you're using as there is no doInBackground(...) method, no call to execute. I suggest that you ignore other code that you might find online and instead re-read the tutorial and use the code and recommendations found in the tutorial that I recommended above.

  6. #6
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,193
    Rep Power
    19

    Default Re: Start a Method from other Class in background

    Also, learn to follow the Java coding conventions. Variable names should start with a lowercase letter.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  7. #7
    ki_ha1984 is offline Member
    Join Date
    Aug 2011
    Posts
    74
    Rep Power
    0

    Default Re: Start a Method from other Class in background

    Quote Originally Posted by Fubarable View Post
    Is the code not working? I don't recognize the SwingWorker that you're using as there is no doInBackground(...) method, no call to execute. I suggest that you ignore other code that you might find online and instead re-read the tutorial and use the code and recommendations found in the tutorial that I recommended above.
    Yes the code is working. I founded here Using a Swing Worker Thread and i used the SwingWorker class.

    you say that i should read again the tutorial and to use doInBackground(...) method ??

    Can you post me any example of the donInBackround ???

    Thank you DarrylBurke about the intervention You're right, ι will fix.

    Thank You

  8. #8
    ki_ha1984 is offline Member
    Join Date
    Aug 2011
    Posts
    74
    Rep Power
    0

    Default Re: Start a Method from other Class in background

    This is the the class swingworker is it ok?

    Java Code:
    
    import javax.swing.SwingUtilities;
    
    /**
     * This is the 3rd version of SwingWorker (also known as
     * SwingWorker 3), an abstract class that you subclass to
     * perform GUI-related work in a dedicated thread.  For
     * instructions on using this class, see:
     * 
     * http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
     *
     * Note that the API changed slightly in the 3rd version:
     * You must now invoke start() on the SwingWorker after
     * creating it.
     */
    public abstract class SwingWorker {
        private Object value;  // see getValue(), setValue()
        private Thread thread;
    
        /** 
         * Class to maintain reference to current worker thread
         * under separate synchronization control.
         */
        private static class ThreadVar {
            private Thread thread;
            ThreadVar(Thread t) { thread = t; }
            synchronized Thread get() { return thread; }
            synchronized void clear() { thread = null; }
        }
    
        private ThreadVar threadVar;
    
        /** 
         * Get the value produced by the worker thread, or null if it 
         * hasn't been constructed yet.
         */
        protected synchronized Object getValue() { 
            return value; 
        }
    
        /** 
         * Set the value produced by worker thread 
         */
        private synchronized void setValue(Object x) { 
            value = x; 
        }
    
        /** 
         * Compute the value to be returned by the <code>get</code> method. 
         */
        public abstract Object construct();
    
        /**
         * Called on the event dispatching thread (not on the worker thread)
         * after the <code>construct</code> method has returned.
         */
        public void finished() {
        }
    
        /**
         * A new method that interrupts the worker thread.  Call this method
         * to force the worker to stop what it's doing.
         */
        public void interrupt() {
            Thread t = threadVar.get();
            if (t != null) {
                t.interrupt();
            }
            threadVar.clear();
        }
    
        /**
         * Return the value created by the <code>construct</code> method.  
         * Returns null if either the constructing thread or the current
         * thread was interrupted before a value was produced.
         * 
         * @return the value created by the <code>construct</code> method
         */
        public Object get() {
            while (true) {  
                Thread t = threadVar.get();
                if (t == null) {
                    return getValue();
                }
                try {
                    t.join();
                }
                catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // propagate
                    return null;
                }
            }
        }
    
    
        /**
         * Start a thread that will call the <code>construct</code> method
         * and then exit.
         */
        public SwingWorker() {
            final Runnable doFinished = new Runnable() {
               public void run() { finished(); }
            };
    
            Runnable doConstruct = new Runnable() { 
                public void run() {
                    try {
                        setValue(construct());
                    }
                    finally {
                        threadVar.clear();
                    }
    
                    SwingUtilities.invokeLater(doFinished);
                }
            };
    
            Thread t = new Thread(doConstruct);
            threadVar = new ThreadVar(t);
        }
    
        /**
         * Start the worker thread.
         */
        public void start() {
            Thread t = threadVar.get();
            if (t != null) {
                t.start();
            }
        }
    }

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Start a Method from other Class in background

    I'm not sure where you got that class, but Java already comes with a SwingWorker class that has generic capabilities as part of its core libraries, and the tutorial describes it and how to use it. But what you use is totally up to you.

Similar Threads

  1. Replies: 1
    Last Post: 10-17-2011, 01:00 AM
  2. Replies: 4
    Last Post: 05-19-2011, 04:05 PM
  3. Using main method to start off app
    By garrym in forum New To Java
    Replies: 3
    Last Post: 04-12-2011, 11:17 PM
  4. How do I re-start a class?
    By Salamander in forum New To Java
    Replies: 5
    Last Post: 08-04-2010, 06:59 AM
  5. Replies: 9
    Last Post: 08-08-2007, 07:16 PM

Posting Permissions

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