java - 如何使对象从左向右缓慢移动
问题描述
我正在尝试使用 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
}
解决方案
更改您的movement
方法以简单地更新增量
public void movement(){
x_position = x_position +10;
}
movement
从您的paintComponent
方法中删除调用
更新您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();
}
}
}
推荐阅读
- node.js - 从一个接口映射到另一个接口
- sql - 如何在 Grafana 中创建因变量来检查 SQL 代理作业
- java - 仅在一个 JSONPath 表达式中过滤多个字段
- flutter - 渲染库问题捕获的异常
- huggingface-transformers - 如何在 Huggingfaces 中从 CSV 加载自定义数据集
- sql - 使用条件合并过期和更新记录
- python - Css 选择器下拉语言选择器 python
- powerbi - Power BI 和 Snowflake 之间的奇怪行为
- python - 如何在 Snapcraft PyQt5 应用程序中的 Ubuntu Budgie 中显示托盘图标?
- batch-file - 使用 & 批量创建文件