0

This project is related to my current question here. I think I've solve the problem but there's another problem coming when I want to cancel a Worker Thread as I click the button . The doInBackground's still runing .( The Printf("Runing" + this.index) is still working ) These're my codes :

import java.awt.Color;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingWorker;

public class Robot extends SwingWorker< Void ,Integer> {
    public int x;
    public static int i = 0;
    public int index;
    public int y;
    public Color color;
    public final int speed = 10;
    Robot(int x , int y , Color color)
    {
        this.x = x;
        this.y = y;
        this.color = color;
        this.index = i;
        i++;
    }
    public void move_90()
    {
        this.y += speed;
    }

    public void move_270()
    {
        this.y -= speed;
    }

    public void move_180()
    {
        this.x -= speed;
    }

    public void move_0()
    {
        this.x += speed;
    }

    public void move_45()
    {
        this.x += speed;
        this.y += speed;
    }

    public void move_135()
    {
        this.x -= speed;
        this.y += speed;
    }

    public void move_225()
    {
        this.x -= speed;
        this.y -= speed;
    }

    public void move_315()
    {
        this.x += speed;
        this.y -= speed;
    }

    public void move()
    {
        Random temp = new Random();
        int rand = temp.nextInt(8);
        switch(rand + 1)
        {
            case 1: move_0();
            break;
            case 2: move_135();
            break;
            case 3: move_180();
            break;
            case 4: move_225();
            break;
            case 5: move_270();
            break;
            case 6: move_315();
            break;
            case 7: move_45();
            break;
            case 8: move_90();
            break;
        }
    }
    @Override
    protected Void doInBackground() throws Exception {
         while(true)
        {
            System.out.println("Runing" + this.index);
            move();
            if(this.x < 40) this.x = 40;
            if(this.x > PlayField.width - 40) this.x = (PlayField.width - 40);
            if(this.y < 40) this.y = 40;
            if(this.y > PlayField.height - 40) this.y = (PlayField.height - 40);
             try {
                 Thread.sleep(200);
             } catch (InterruptedException ex) {
                 Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex);
             }
        }
    }

    @Override
    protected void done() {
        super.done();
        System.out.println("done");//To change body of generated methods, choose Tools | Templates.
    }

}

this's my RobotModel class :

import java.awt.Color;
import java.util.LinkedList;
public class RobotModel {
    public static final int MAX = 8;
    public LinkedList<Robot> model = new LinkedList<Robot>();
    public void add_New_Robot()
    {
        Robot temp = new Robot( 40 , 40 , Color.BLUE);
        temp.execute();
        model.addFirst(temp);
    }
}

This's GameMain class

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GameMain extends JFrame {
    RobotModel a;
    PlayField field;
    public void Game_Start()
    {
        a = new RobotModel();
        field = new PlayField(500 , 500, Color.yellow);
        RobotWorld world = new RobotWorld(a);
        world.setPreferredSize(new Dimension(500 , 500));
        world.robot_Model.add_New_Robot();
        world.robot_Model.add_New_Robot();
        world.robot_Model.add_New_Robot();
        world.robot_Model.add_New_Robot();
        world.robot_Model.add_New_Robot();
        world.robot_Model.add_New_Robot();
        world.robot_Model.add_New_Robot();
        this.setSize(field.width , field.height);
        this.setLayout(new GridLayout());
        this.add(world);
        JButton but = new JButton();
        but.setPreferredSize(new Dimension(50, 20));
        but.setText("STOP");
        but.setVisible(true);
        but.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                world.robot_Model.model.get(0).cancel(true);
                world.robot_Model.model.remove(0);
            }
        });
        this.add(but);
        this.setVisible(true);
        world.repaint();
    }
    public void gameUpdate(){
    Thread gameThread = new Thread(){
        public void run(){
            while(true){
                //refresh screen
                repaint();
                //give other threads time
                try{
                    Thread.sleep(5);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    };

    gameThread.start();
}



    public static void main(String args[])
    {
        GameMain main = new GameMain();
        main.Game_Start();
        main.gameUpdate();

    }
}

This's RobotWorld class

import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class RobotWorld extends JPanel {
    public RobotModel robot_Model;

    public RobotWorld(RobotModel robot_Model) {
        super();
        this.robot_Model = robot_Model;
        this.setSize(PlayField.width , PlayField.height);
        this.setVisible(true);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D graphic = (Graphics2D)g;
        for(Robot x : this.robot_Model.model )
        {
            graphic.setColor(x.color);
            graphic.drawOval(x.x, x.y, 40, 40);
        }
    }

}

this's PlayField class

package com.mycompany.test;

import java.awt.Color;

public class PlayField {
    public static int width;
    public static int height;
    public static Color fill_Color;
    PlayField(int width , int height , Color fill_Color)
    {
        this.width = width;
        this.height = height;
        this.fill_Color = fill_Color;
    }
}

MadProgramer has give me an amazing example here . If this's not about the exercise's request , I will not program with SwingWorker

  • Possible duplicate of [How cancel the execution of a SwingWorker?](https://stackoverflow.com/questions/6113944/how-cancel-the-execution-of-a-swingworker) – Michał Krzywański Oct 16 '19 at 16:08
  • Are you aware of the Swing Timer? This might actually suit what you are doing here better than using a SwingWorker – ControlAltDel Oct 16 '19 at 17:28

1 Answers1

0

You cancel, and indicate you may interrupt.

But looking at your doInBackgroundcode :

@Override
protected Void doInBackground() throws Exception {
     while(true)
    {
        System.out.println("Runing" + this.index);
        move();
        if(this.x < 40) this.x = 40;
        if(this.x > PlayField.width - 40) this.x = (PlayField.width - 40);
        if(this.y < 40) this.y = 40;
        if(this.y > PlayField.height - 40) this.y = (PlayField.height - 40);
         try {
             Thread.sleep(200);
         } catch (InterruptedException ex) {
             Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex);
         }
    }
}

We see that you respond to interruption by logging the InterruptedException in a ctach block (which clears the interrupted state on your thread), and then merrily continue the loop. Of course that won't stop the thread.

Try being responsive to the interrupted state of your thread :

@Override
protected Void doInBackground() throws Exception {
    while(!Thread.currentThread().isInterrupted())   // break out of the loop onc ethe thread is interrupted
    {
        // ... omitted for brevity

         try {
             Thread.sleep(200);
         } catch (InterruptedException ex) {
             Thread.currentThread().interrupt();   // catching the exception clears the interrupted state, so we reset it, to break out of the loop.
         }
    }
}
bowmore
  • 10,842
  • 1
  • 35
  • 43