我正在尝试编写使此框逐渐向上移动的代码,但我无法使其运行:

时间:2018-12-10 13:15:01

标签: java

主类: 如果有人可以帮助我解决此问题,我将很感激

package com.company;
import javax.swing.JComponent;
import javax.swing.*;

public class Main {

    public static void main(String[] args) {
        int on = 1;
        JFrame frame = new JFrame();
        frame.setSize(600,600);
        frame.setTitle("My Program");
        Box b = new Box();
        frame.add(b);
        frame.setVisible(true);
    }
}

名为Box.java的类 我希望它暂停约半秒钟,然后循环才能再次开始。 我希望它的工作方式是循环不断进行,并且像动画那样每次将其向上移动一个像素。 我只是不知道为什么它起作用。该框仅在我摆脱循环时才会显示

package com.company;
import java.awt.*;
import javax.swing.*;
import java.util.concurrent.TimeUnit;

         public class Box extends JComponent {
             int x = 300;
             int y = 300;
             int width = 100;
             int height = 100;

             public void paintComponent(Graphics g)
             {
                 int on = 1;
                 while (on == 1){
                 Color Black = new Color(0, 0, 0);
                 g.setColor(Black);
                 g.fillRect(x,y,width,height);
                 x++;
                 y++;
                 //I want it to pause for like half a second here but these next 4 lines dont work
                 long start1 = System.currentTimeMillis();
                 try {
                 Thread.sleep(500);
                 }
                 catch (Exception ex) {}
                 }
             }
         }

0 个答案:

没有答案