如何使物体从左向右缓慢移动

时间:2019-01-18 21:44:25

标签: java swing

我正在尝试使用for循环和计时器使物体(地面)从屏幕的左侧缓慢移至右侧。我获得的成功的唯一衡量标准是取得进展,但是一旦应用程序启动,它会立即转移。我已经研究了thread和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                   
}

1 个答案:

答案 0 :(得分:-1)

更改您的movement方法以仅更新增量

public void movement(){
            x_position = x_position +10;
}

从您的movement方法中删除对paintComponent的调用

更新您的Timer来调用movement方法

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

以及if语句如何处理,如果版本不在屏幕上,它将返回到开始?我需要做一个单独的检查方法吗?如果是这样,我会在图形中还是在计时器中调用它?谢谢

您一直在问这个问题,并且您得到的答案是相同的,我不确定您希望改变什么。

我会考虑使用类似this for example的方法,该方法只是绘制图像的“溢出”以填充剩余空间,或者考虑使用BufferedImage#getSubImage的{​​{3}}甚至是this for example ,这可能会更有效。

根据前两个示例,您还可以执行类似...

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();
        }

    }

}