Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使对象从左到右缓慢移动_Java_Swing - Fatal编程技术网

Java 如何使对象从左到右缓慢移动

Java 如何使对象从左到右缓慢移动,java,swing,Java,Swing,我试着让一个物体,地面,从屏幕的左边慢慢地移动到右边,使用for循环和定时器。我所取得的成功的唯一衡量标准是让地面移动,但它会在应用程序启动后立即远程传送。我已经查看了threads和thread.sleep以减慢速度,但现在我面对的是一个白色屏幕,根本看不到我的视觉效果。我是否错误地使用了线程,或者for循环没有正确使用?请帮忙。谢谢,这是代码,任何提示都将不胜感激 import java.awt.BorderLayout; import java.awt.Color; import java

我试着让一个物体,地面,从屏幕的左边慢慢地移动到右边,使用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                   
}
导入java.awt.BorderLayout;
导入java.awt.Color;
导入java.awt.Graphics;
导入java.awt.Graphics2D;
导入java.awt.RenderingHints;
导入java.awt.event.WindowAdapter;
导入java.awt.event.WindowEvent;
导入java.awt.geom.Rectangle2D;
导入javax.swing.JComponent;
导入javax.swing.JFrame;
导入javax.swing.SwingUtilities;
导入javax.swing.Timer;
/*
*要更改此许可证标题,请在“项目属性”中选择“许可证标题”。
*要更改此模板文件,请选择工具|模板
*然后在编辑器中打开模板。
*/
/**
*
*@作者山姆·K
*/
公共类游戏扩展了javax.swing.JFrame{
私人漆面帆布;
int x_位置=0;
int y_位置=580;
int x_速度=7;
int velX=20;
/**
*创造新形式的游戏
*/
公共游戏(){
这是setTitle(“弹跳球”);
这个。设置大小(1200650);
//超级。挫折背景(颜色。黄色);
此.setDefaultCloseOperation(此.EXIT在关闭时退出);
添加(新的PaintSurface(),BorderLayout.CENTER);
此.setVisible(true);
canvas=新的PaintSurface();
添加(画布、边框布局、中心);
//窗体的设置,处理退出和大小等事项
定时器=新定时器(50,e->{
canvas.repaint();
});
timer.start();
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//                           
私有组件(){
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0,400,短。最大值)
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0,300,短。最大值)
);
包装();
}//                         
类PaintSurface扩展了JComponent{
公共组件(图形g){
超级组件(g);
图形2d g2=(图形2d)g;
矩形2D背景=新矩形2D.Float(0,01200650);
g2.setColor(颜色为青色);
g2.填充(背景);
矩形2D地面=新矩形2D浮动(x\U位置,y\U位置,1200,30);
g2.设置颜色(颜色为绿色);
g2.填土(地面);
运动();
g2.setRenderingHint(renderingHits.KEY\u ANTIALIASING,renderingHits.VALUE\u ANTIALIAS\u ON);
/**
*@param指定命令行参数
*/
}
公众空虚运动{
对于(int i=0;i<100;i=i+1){
x_位置=x_位置+10;
重新油漆();
系统输出打印项次(“X-POS=“+i”);
尝试{Thread.sleep(50);}/*这将暂停50毫秒*/
catch(InterruptedException e){System.err.println(“睡眠异常”);}
}
}
}
公共静态void main(字符串参数[]){
/*设置Nimbus的外观和感觉*/
//
/*如果Nimbus(在JavaSE6中引入)不可用,请使用默认的外观。
*详情请参阅http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
*/
试一试{
for(javax.swing.UIManager.LookAndFeelInfo:javax.swing.UIManager.getInstalledLookAndFeels()){
if(“Nimbus”.equals(info.getName())){
setLookAndFeel(info.getClassName());
打破
}
}
}捕获(ClassNotFoundException ex){
getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(实例化异常){
getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}捕获(非法访问例外){
getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(javax.swing.UnsupportedLookAndFeelException ex){
getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}
//
/*创建并显示表单*/
invokeLater(new Runnable()){
公开募捐{
新游戏().setVisible(true);
}
});
}
//变量声明-不修改
//变量结束声明
}

更改
移动
方法,只需更新增量即可

public void movement(){
            x_position = x_position +10;
}
paintComponent
方法中删除对
movement
的调用

Timer timer = new Timer(50, e -> {
        canvas.movement();
        canvas.repaint();
 });
更新您的
计时器
以调用
移动
方法

Timer timer = new Timer(50, e -> {
        canvas.movement();
        canvas.repaint();
 });

那么if语句呢?如果版本离开屏幕,它会返回到开始?我需要单独做一个m吗