【发布时间】:2016-11-12 23:34:04
【问题描述】:
我一直在编写有关 Java 8 中 2D 图形的教程,当时 NetBeans 提示我执行 Thread.Sleep 会影响性能。然而,虽然我已经找到了几种更好的方法,但我一直无法找到一种方法来包含它们而不弄乱你的代码。
package platformer;
import java.awt.*;
import javax.swing.*;
import java.util.Scanner;
@SuppressWarnings("serial")
public class Platformer extends JPanel {
int x = 0;//Sets the starting coords. of the ball
int y = 0;
private void moveBall() {//How much the ball moves by
x = x+1;
y = y+1;
}
@Override
public void paint(Graphics g) {//Essentially al the graphics functions
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, 30, 30);
}
public static void main(String[] args) throws InterruptedException {
Scanner reader = new Scanner(System.in);
Scanner reader1 = new Scanner(System.in);
System.out.print("Enter an x-value for the window (whole numbers only): ");
int setx = reader.nextInt();
System.out.print("Enter a y-value for the window (whole numbers only): ");
int sety = reader.nextInt();
JFrame gameFrame = new JFrame("Sample Frame");//Makes the window variable w/ the name in quotations.
Platformer game = new Platformer();//'Copies' the graphics functions above into a variable
gameFrame.add(game);//Adds the above variable into th window
gameFrame.setSize(setx,sety);//Sets the resolution/size of the window(x,y)
gameFrame.setVisible(true);//Makse the window visible
gameFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//Makes the window close when the close button is hit
while (true){
game.moveBall();
game.repaint();
Thread.sleep(10);
}
}
}
我想知道如何包含更好的方法让线程在循环中休眠,或者让 NetBeans 只执行循环。
【问题讨论】:
-
Netbeans 可能不明白你为什么使用
Thread.sleep()并给你一个错误的提示。 -
我自己也在想——非常合理的解释。
标签: java multithreading swing netbeans thread-sleep