如何在垂直线内移动JApplet内的图像?

时间:2011-09-16 11:16:38

标签: java image swing graphics2d paintcomponent

我在JApplet中显示了一个图像(球),现在我希望图像以垂直方式(向上和向下)移动。问题是我不知道该怎么做。

有人可以对此事有所了解吗?

4 个答案:

答案 0 :(得分:3)

您需要将该图像的位置设置为某个计算值(表示您使用时间,速度和其他限制来计算垂直位置)。

如何设置该位置取决于您绘制图像的方式。

示例,基于applet(或嵌套组件)paint(Graphics g)方法中的绘图:

//first calculate the y-position
int yPos += timeSinceLastPaint * speed; //increment the position
if( (speed > 0 && yPos > someMaxY) || (speed < 0 && yPos <0 ) ) {
  speed *= -1; //if the position has reached the bottom (max y) or the top invert the direction  
}


//in your paint(Graphics g) method:
g.drawImage(image, yPos, x, null);

然后你必须不断重新绘制小程序。

有关applet中动画的更多信息,请访问:http://download.oracle.com/javase/tutorial/uiswing/components/applet.html

答案 1 :(得分:3)

  

如何在JApplet中移动图像..?

JFrameJComponentJPanel或...... {/ p>完全相同的方式完全相同

或者用另一种方式,没有来处理applet和所有来处理Graphics2D。有关更多详细信息,请参阅Java Tutorial的2D Graphics Trail

当您想出如何移动图片并将其绘制为Graphics2D时,请使用JComponentJPanel的{​​{1}}方法实现该逻辑并删除将动态图像转换为paintComponent(Graphics)JApplet(或JFrame等)的组件。


对于动画方面,请使用JPanel,如本例所示。此示例不扩展任何组件。相反,它会创建一个javax.swing.Timer并将其添加到显示给用户的BufferedImage。当计时器触发时,代码会抓取图像的JLabel对象,并从那里继续绘制弹跳线。

100 Bouncing Lines

Graphics

更新1

  

我想在JApplet(1)中使用图像(2)来做,是否可能(3)?

  1. mKorbel和我自己的例子展示了import java.awt.image.BufferedImage; import java.awt.event.*; import java.awt.geom.*; import java.awt.*; import javax.swing.*; import java.util.Random; class LineAnimator { public static void main(String[] args) { final int w = 640; final int h = 480; final RenderingHints hints = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); hints.put( RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY ); final BufferedImage bi = new BufferedImage(w,h, BufferedImage.TYPE_INT_ARGB); final JLabel l = new JLabel(new ImageIcon(bi)); final BouncingLine[] lines = new BouncingLine[100]; int factor = 1; for (int ii=0; ii<lines.length; ii++) { lines[ii] = new BouncingLine(w*factor,h*factor); } final Font font = new Font("Arial", Font.BOLD, 30); ActionListener al = new ActionListener() { int count = 0; long lastTime; String fps = ""; private final BasicStroke stroke = new BasicStroke(6); public void actionPerformed(ActionEvent ae) { count++; Graphics2D g = bi.createGraphics(); g.setRenderingHints(hints); g.setColor(new Color(55,12,59)); g.fillRect(0,0,w,h); g.setStroke(stroke); for (int ii=0; ii<lines.length; ii++) { lines[ii].move(); lines[ii].paint(g); } if ( System.currentTimeMillis()-lastTime>1000 ) { lastTime = System.currentTimeMillis(); fps = count + " FPS"; count = 0; } g.setColor(Color.YELLOW); g.setFont(font); g.drawString(fps,5,h-5); l.repaint(); g.dispose(); } }; Timer timer = new Timer(25,al); timer.start(); JOptionPane.showMessageDialog(null, l); //System.exit(0); timer.stop(); } } class BouncingLine { private final Color color; private static final Random random = new Random(); Line2D line; int w; int h; int x1; int y1; int x2; int y2; BouncingLine(int w, int h) { line = new Line2D.Double(random.nextInt(w),random.nextInt(h),random.nextInt(w),random.nextInt(h)); this.w = w; this.h = h; this.color = new Color( random.nextInt(255) ,random.nextInt(255) ,random.nextInt(255) ,64+random.nextInt(128) ); x1 = (random.nextBoolean() ? 1 : -1); y1 = (random.nextBoolean() ? 1 : -1); x2 = -x1; y2 = -y1; } public void move() { int tx1 = 0; if (line.getX1()+x1>0 && line.getX1()+x1<w) { tx1 = (int)line.getX1()+x1; } else { x1 = -x1; tx1 = (int)line.getX1()+x1; } int ty1 = 0; if (line.getY1()+y1>0 && line.getY1()+y1<h) { ty1 = (int)line.getY1()+y1; } else { y1 = -y1; ty1 = (int)line.getY1()+y1; } int tx2 = 0; if (line.getX2()+x2>0 && line.getX2()+x2<w) { tx2 = (int)line.getX2()+x2; } else { x2 = -x2; tx2 = (int)line.getX2()+x2; } int ty2 = 0; if (line.getY2()+y2>0 && line.getY2()+y2<h) { ty2 = (int)line.getY2()+y2; } else { y2 = -y2; ty2 = (int)line.getY2()+y2; } line.setLine(tx1,ty1,tx2,ty2); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; g2.setColor(color); //line.set g2.draw(line); } } 中的图片或JLabel中的自定义渲染。在我们的例子中,我们将组件添加到JPanel&amp;一个JOptionPane。这两个示例都可以轻松添加到JFrameJApplet,或作为其他面板的一部分,或者..请参阅Laying Out Components Within a Container课程&amp;有关详细信息,请参阅Java教程中的Using Top-Level Containers
  2. 而不是我们示例中的星星或线条,...显示您的图像。我的例子甚至展示了如何让位置在容器的范围内反弹。
  3. 当然有可能,但“不包括电池”。我们的目的是为您提供一些想法,然后您可以适应您的弹跳球小程序。我怀疑有人会在applet中为你创建一个使用球的例子。虽然如果你发布一个显示你的意图和你尝试过的SSCCE,我(和其他人)会经常使用该来源。如果您想要更具体的答案,请询问更具体的SSCCE。 ;)

答案 2 :(得分:3)

paintComponent(Graphics g)创建移动对象的javax.swing.Timer的另一个示例,我有很多Start,而不是一些模糊的Mikado: - )

enter image description here

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class AnimationBackground {

    private Random random = new Random();
    private JFrame frame = new JFrame("Animation Background");
    private final MyJPanel panel = new MyJPanel();
    private JLabel label = new JLabel("This is a Starry background.", JLabel.CENTER);
    private JPanel stopPanel = new JPanel();
    private JPanel startPanel = new JPanel();

    public AnimationBackground() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        panel.setBackground(Color.BLACK);
        for (int i = 0; i < 50; i++) {
            Star star = new Star(new Point(random.nextInt(490), random.nextInt(490)));
            star.setColor(new Color(100 + random.nextInt(155), 100 + random.nextInt(155), 100 + random.nextInt(155)));
            star.setxIncr(-3 + random.nextInt(7));
            star.setyIncr(-3 + random.nextInt(7));
            panel.add(star);
        }
        panel.setLayout(new GridLayout(10, 1));
        label.setForeground(Color.WHITE);
        panel.add(label);
        stopPanel.setOpaque(false);
        stopPanel.add(new JButton(new AbstractAction("Stop this madness!!") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                panel.stopAnimation();
            }
        }));
        panel.add(stopPanel);
        startPanel.setOpaque(false);
        startPanel.add(new JButton(new AbstractAction("Start moving...") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                panel.startAnimation();
            }
        }));
        panel.add(startPanel);
        frame.add(panel);
        frame.pack();
        frame.setLocation(150, 150);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                AnimationBackground aBg = new AnimationBackground();
            }
        });
    }

    private class Star extends Polygon {

        private static final long serialVersionUID = 1L;
        private Point location = null;
        private Color color = Color.YELLOW;
        private int xIncr, yIncr;
        static final int WIDTH = 500, HEIGHT = 500;

        Star(Point location) {
            int x = location.x;
            int y = location.y;
            this.location = location;
            this.addPoint(x, y + 8);
            this.addPoint(x + 8, y + 8);
            this.addPoint(x + 11, y);
            this.addPoint(x + 14, y + 8);
            this.addPoint(x + 22, y + 8);
            this.addPoint(x + 17, y + 12);
            this.addPoint(x + 21, y + 20);
            this.addPoint(x + 11, y + 14);
            this.addPoint(x + 3, y + 20);
            this.addPoint(x + 6, y + 12);
        }

        public void setColor(Color color) {
            this.color = color;
        }

        public void move() {
            if (location.x < 0 || location.x > WIDTH) {
                xIncr = -xIncr;
            }
            if (location.y < 0 || location.y > WIDTH) {
                yIncr = -yIncr;
            }
            translate(xIncr, yIncr);
            location.setLocation(location.x + xIncr, location.y + yIncr);
        }

        public void setxIncr(int xIncr) {
            this.xIncr = xIncr;
        }

        public void setyIncr(int yIncr) {
            this.yIncr = yIncr;
        }

        public Color getColor() {
            return color;
        }
    }

    private class MyJPanel extends JPanel {

        private static final long serialVersionUID = 1L;
        private ArrayList<Star> stars = new ArrayList<Star>();
        private Timer timer = new Timer(20, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                for (Star star : stars) {
                    star.move();
                }
                repaint();
            }
        });

        public void stopAnimation() {
            if (timer.isRunning()) {
                timer.stop();
            }
        }

        public void startAnimation() {
            if (!timer.isRunning()) {
                timer.start();
            }
        }

        @Override
        public void addNotify() {
            super.addNotify();
            timer.start();
        }

        @Override
        public void removeNotify() {
            super.removeNotify();
            timer.stop();
        }

        MyJPanel() {
            this.setPreferredSize(new Dimension(512, 512));
        }

        public void add(Star star) {
            stars.add(star);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            for (Star star : stars) {
                g.setColor(star.getColor());
                g.fillPolygon(star);
            }
        }
    }
}

答案 3 :(得分:3)

  

我想在JApplet中完成。

为什么不两者兼而有之?您可以拥有一个混合应用程序/ applet,如animation所示。