Search code examples
javarunnable

Problems with starting run command


First, I'd like to say that I'm sorry if my question doesn't sound very specific, I don't know very much about programming, Please forgive me.

The problem with this code is that I want it to be moving the square around randomly (Right know it's just says hi repeatedly though) but the run() is not activating.

Code:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.net.*;

public class Square extends JApplet {

    int X = 10;
    int Y = 10;

    public void init() {
        FlowLayout flow = new FlowLayout();
        setLayout(flow);
    }


    public void paint(Graphics screen) {
        // Paint lines
        Graphics2D g2 = (Graphics2D) screen;
        g2.draw(new Line2D.Double(X, Y, (X + 50), Y));
        g2.draw(new Line2D.Double(X, Y, X, (Y + 50)));
        g2.draw(new Line2D.Double(X, (Y + 50), (X + 50), (Y + 50)));
        g2.draw(new Line2D.Double((X + 50), (Y + 50), (X + 50), Y));
    }

    public void run() {
        System.out.println("Hi2");
        while (true) {
            System.out.println("Hi");
            repaint();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // do nothing
            }
        }
        }

    public static void main(String[] args) {
        JFrame f = new JFrame("Square");
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
        });
        JApplet applet = new Square();
        f.getContentPane().add("Center", applet);
        applet.init();
        f.pack();
        f.setSize(new Dimension(550,100));
        f.setVisible(true);

    }
}

(I know I imported a few things I probably didn't need, I copied some of this from another code)


Solution

  • Although you have a run method, your class doesn't implement Runnable so it can't be used in a Thread. To get your Thread running, you would have to implement Runnable and create a new Thread on init:

    new Thread(this).start();
    

    If you intend interacting with UI components, forget about Threads. Swing has its own concurrency mechanisms which allow you to safely interact with UI components. Have a look at using a Swing Timer instead.