有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带螺纹的java模具

我想做一个模具图形用户界面,每次显示不同的数字时,它都会改变模具的表面。我有一个RollDie类,它扩展了gui类Die:

public class RollDie2 extends Die implements Runnable {

public static void main(String[] args) {

    long sleeptime = 500;
    int times;
    Random rd = new Random();
    int face;
    int facebefore;

    times = rd.nextInt(20)+1;
    face = rd.nextInt(6) + 1;

    // Graphics
    SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            Die die = new RollDie2();

            die.setVisible(true);
          }
        });



    for (int i=0; i<times; i++) {
        (new Thread(new RollDie2(face))).start();
        try {
            Thread.sleep(sleeptime);
        } catch (InterruptedException e) {e.printStackTrace();}
        sleeptime += 100;

        facebefore = face;
        face = rd.nextInt(6) + 1;

        while (facebefore == face) //so it is different every time
            face = rd.nextInt(6) + 1;
    }
    System.out.println("The die was rolled " + times + " times.");



}

int face;

public RollDie2(int face) {
    this.face = face;
    super.changeFace(face);

}
public RollDie2() {

}
@Override
public void run() {

    System.out.println("The face is now showing: " + face);
}

}

GUI类:

public class Die extends JFrame {
int face;

public Die() {
    init();

}


private void init() {
    //final 
    DiePanel surface = new DiePanel();
    add(surface);
   // surface.updateVal(face);
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            Timer timer = surface.getTimer();
            timer.stop();
        }
    });

    setTitle("Dice");
    setSize(500, 300);
    //setLocationRelativeTo(null);
    setLayout(new GridLayout(1,3));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void changeFace(int value) {
    face = value;

}
public int getFace() {
    return face;
}
}

问题是每次我在panel类中调用getFace()时,它都不会返回任何结果,而且我无法更新Die的值。我认为这与线程有关,但不知道是什么


共 (1) 个答案

  1. # 1 楼答案

    我看到你缺少一套方法。 而且你的代码到处都是。线程很棘手。下面的代码帮助我一次运行多个线程。这可能有助于解决你的线程问题

    public class RollDie implements Runnable
    {
    //variables go here
    
    public RollDie()
    {
      start();
    }
    
    public void start()
    {
     Thread thread = new thread(this);
     thread.start();
    }
    
    public void run()
    {
    //code for RollDie goes here
    }
    
    } 
    

    然后从骰子类中调用RollDie构造函数。 希望这能有所帮助