【发布时间】:2019-01-18 21:44:25
【问题描述】:
我正在尝试使用 for 循环和计时器制作一个对象,即地面,从屏幕左侧缓慢移动到右侧。我取得成功的唯一衡量标准是让地面移动,但它会在应用程序启动后立即传送出去。我查看了线程和 thread.sleep 以减慢速度,但现在我面临白屏,根本看不到我的视觉效果。是我错误地使用了线程,还是没有正确使用 for 循环?请帮忙。谢谢,这是代码,任何指针将不胜感激。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Sam.K
*/
public class game extends javax.swing.JFrame {
private PaintSurface canvas;
int x_position = 0;
int y_position = 580;
int x_speed = 7;
int velX= 20;
/**
* Creates new form game
*/
public game() {
this.setTitle("Bouncing Ball");
this.setSize(1200, 650);
// super.setBackground(Color.YELLOW);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.add(new PaintSurface(), BorderLayout.CENTER);
this.setVisible(true);
canvas = new PaintSurface();
this.add(canvas, BorderLayout.CENTER);
//settings for the form, hyandling things such as exiting and size
Timer timer = new Timer(50, e -> {
canvas.repaint();
});
timer.start();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
class PaintSurface extends JComponent {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle2D background = new Rectangle2D.Float(0,0,1200,650);
g2.setColor(Color.CYAN);
g2.fill(background);
Rectangle2D ground = new Rectangle2D.Float(x_position,y_position,1200,30);
g2.setColor(Color.GREEN);
g2.fill(ground);
movement();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
/**
* @param args the command line arguments
*/
}
public void movement(){
for (int i = 0; i < 100; i = i + 1) {
x_position = x_position +10;
repaint();
System.out.println("X-POS = " + i);
try { Thread.sleep(50); } /* this will pause for 50 milliseconds */
catch (InterruptedException e) { System.err.println("sleep exception"); }
}
}
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new game().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
}
【问题讨论】:
-
计时器充当伪循环,每次触发时,您都会更新状态(更改增量)并安排重绘。我会删除循环并使用移动方法来更新 x_position,从 Timer 调用它,并丢失 Thread.sleep