0

I am making Battleship in Java and I am trying to make a visual effect when a ship is destroyed. I am trying to make copies of a JLabel, then delete them after a short amount of time. I have the code for the method that creates the explosion here:

//"scheduler" is a single-thread ScheduledExecutorService that has already been declared in the class constructor method
//"layer" is a JLayeredPane, "explosion" is the JLabel I am duplicating
 public synchronized void bigExplosion(Ship s) throws InterruptedException {

    Random rand = new Random();


        ArrayList<Coordinate> c = s.getCoordinates();
        int x = rand.nextInt(((c.get(c.size()-1)).getX() - c.get(0).getX()) + 1) + c.get(0).getX();
        int y = rand.nextInt(((c.get(c.size()-1)).getY() - c.get(0).getY()) + 1) + c.get(0).getY();
        JLabel temp = new JLabel(explosion.getIcon());
        temp.setBounds(x, y, 58, 58);
        layer.add(temp,JLayeredPane.MODAL_LAYER);
        playSound("Sounds/Explosion.wav");
        scheduler.schedule(new Thread(() -> layer.remove(temp)), 1400, TimeUnit.MILLISECONDS);




}

The snippet of code that calls the method is here:

//"t" is a variable that has been already declared that is the index of which ship's coordinates the explosions will be at
for(int a = 0; a < 10; a++) {
                        scheduler.schedule(new Thread(()-> {
                            try {
                                bigExplosion(shipList[t]);
                            } catch (InterruptedException e) {

                                e.printStackTrace();
                            }
                        }), 100, TimeUnit.MILLISECONDS);
                        }

I want to duplicate the JLabel ever 100 milliseconds 10 times, then delete it after 1.4 seconds, but the code does not seem to be not doing anything. What am I doing wrong?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    1) `temp.setBounds(x, y, 58, 58);` A Battleship game is well suite to being laid out in a `GridLayout`. 2) A label with no text or icon is invisible. 3) Updates to a swing GUI should be scheduled on the EDT. 4) Special measures have to be taken when adding or removing components from an existing, on-screen GUI. **General tips:** 1) A single blank line of white space in source code is all that is *ever* needed. Blank lines after `{` or before `}` are also typically redundant. 2) For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/)... – Andrew Thompson Feb 28 '20 at 22:44
  • 1
    .. 3) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). E.G. [This answer](https://stackoverflow.com/a/10862262/418556) hot links to an image embedded in [this question](https://stackoverflow.com/q/10861852/418556). – Andrew Thompson Feb 28 '20 at 22:44

0 Answers0