0

Trying to create a maze generator, to get the repaint() to work I had to add the swingUtilities.invokeLater in main, and make the graphics class implement Runnable with new Thread(this).start(); in the constructor.

However, I want the maze to regenerate on a button click, which is in the button class.

Simply calling the method from another class seems to work as println still prints but nothing is repainted onto the panel, resizing the window also doesn't change anything.

I've tried creating a new thread using the below code but the same thing happens?

MazeArea ma = new MazeArea();

Thread t = new Thread(ma);

t.start();

Main Class

public class MainGenerator {

    public static void main(String[] args) 
    {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // executes code
            }
        });
    }
}

Graphics Class

public class MazeArea extends JComponent implements Runnable {
    public MazeArea() {
        new Thread(this).start();
    }

    public void run() {
        generateMaze();
        clear();
    }

    synchronized protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        drawMaze(g);
    }
}

Button Class

public class VariableDetails extends JPanel {
    public VariableDetails() {
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {                   
                MazeArea ma = new MazeArea();

                Thread t = new Thread(ma);

                t.start();
            }
        });
    }

How would I just rerun a thread?

Sebmins
  • 13
  • 6
  • *How would I just rerun a thread?* You would not. – Elliott Frisch Jan 25 '19 at 23:47
  • It doesn't look to me like there's any reason to use threads here, unless generating the maze takes a really long time. If you need a background task sometimes, use [`SwingWorker`](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html), or if you want to do animation, use a [Swing `Timer`](https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html). – Radiodef Jan 26 '19 at 00:11
  • See [Concurrency in Swing](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) – c0der Jan 26 '19 at 05:03
  • @Radiodef it doesn't take a really long time, it's very quick but if I don't have the `Runnable` then the repaint doesn't work. – Sebmins Jan 26 '19 at 12:49
  • What do you mean by "doesn't work"? If you have some kind of an infinite loop that does animation and calls `repaint()`, then you should use a timer (like I already suggested). Possibly see e.g. [this answer](https://stackoverflow.com/a/29837148/2891664) for an explanation. If you want more specific help, [edit your question](https://stackoverflow.com/posts/54374266/edit) to add a [mcve] which reproduces the problem you're having. – Radiodef Jan 26 '19 at 13:01

0 Answers0