[英]How can I make an object move from left to right slowly
我正在嘗試使用 for 循環和計時器使物體(地面)從屏幕左側緩慢移動到右側。 我取得的成功的唯一衡量標准是讓地面移動,但一旦應用程序啟動,它就會立即傳送離開。 我查看了threads和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
}
更改您的movement
方法以簡單地更新增量
public void movement(){
x_position = x_position +10;
}
從您的paintComponent
方法中刪除對movement
的調用
更新您的Timer
以調用movement
方法
Timer timer = new Timer(50, e -> {
canvas.movement();
canvas.repaint();
});
如果版本從屏幕上消失,它又會回到開頭的 if 語句呢? 我是否必須制定單獨的檢查方法? 如果是這樣,我會在圖形中還是在計時器中調用它? 謝謝
你不斷問這個問題,你不斷得到相同的答案,我不確定你希望改變什么。
我會考慮使用這樣的東西,例如,它只是簡單地繪制圖像的“溢出”以填充剩余空間,或者甚至是這個使用BufferedImage#getSubImage
,這可能更有效。
基於前兩個示例,您還可以執行以下操作...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
BufferedImage background = new BufferedImage(800, 200, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = background.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, 800, 200);
g2d.setColor(Color.RED);
g2d.drawLine(0, 0, 800, 200);
g2d.drawLine(0, 200, 800, 0);
JFrame frame = new JFrame();
frame.add(new RenderPane(background));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class RenderPane extends JPanel {
private BufferedImage bgMaster;
private BufferedImage bgImage;
private Timer timer;
private double delta = 1.0;
private double backgroundXPos = 0;
public RenderPane(BufferedImage background) {
this.bgMaster = background;
bgImage = new BufferedImage(getPreferredSize().width, getPreferredSize().height, bgMaster.getType());
renderBackground();
timer = new Timer(5, new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
backgroundXPos -= delta;
if (backgroundXPos + background.getWidth() < 0) {
System.out.println("Reset");
backgroundXPos = 0;
}
renderBackground();
repaint();
}
});
timer.start();
}
protected void renderBackground() {
Graphics2D g2d = bgImage.createGraphics();
g2d.drawImage(bgMaster, (int)backgroundXPos, 0, null);
double overflow = bgMaster.getWidth() - (backgroundXPos * -1) - getWidth();
if (overflow < 0) {
double overflowX = getWidth() + overflow;
g2d.drawImage(bgMaster, (int)overflowX, 0, null);
}
g2d.dispose();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (bgImage != null) {
g2d.drawImage(bgImage, 0, 0, this);
}
g2d.dispose();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.