【问题标题】:How to move the image inside the JApplet in vertical line?如何在垂直线上移动 JApplet 内的图像?
【发布时间】:2011-11-18 14:56:56
【问题描述】:

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

有人对这件事有什么想法吗?

【问题讨论】:

    标签: java image swing graphics2d paintcomponent


    【解决方案1】:

    您需要将该图像的位置设置为某个计算值(意味着您使用时间、速度和可能的其他限制来计算垂直位置)。

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

    示例,基于在小程序的(或嵌套组件的)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);
    

    那么你必须不断地重新绘制小程序。

    更多关于小程序动画的信息可以在这里找到:http://download.oracle.com/javase/tutorial/uiswing/components/applet.html

    【讨论】:

      【解决方案2】:

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

      JFrameJComponentJPanel 或...中的操作方式几乎完全相同。

      或者换一种说法,没有与小程序有关,而一切Graphics2D有关。更多详情,请参阅 Java 教程的2D Graphics Trail

      当您知道如何移动图像并将其绘制到 Graphics2D 时,请在 JComponentJPanelpaintComponent(Graphics) 方法中实现该逻辑,并将带有移动图像的组件放入 @ 987654334@ 或 JFrame(或 JPanel 等)。


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

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

      更新 1

      我想在 JApplet(1) 中使用图像 (2) 进行操作,是否可以 (3)?

      1. mKorbel 和我自己的示例以JLabel 中的图像或JPanel 中的自定义渲染为特色。在我们的例子中,我们将组件添加到 JOptionPaneJFrame。任何一个示例都可以很容易地添加到JAppletJDialog,或者作为另一个面板的一部分,或者..有关更多详细信息,请参阅 Java 教程中的Laying Out Components Within a Container 课程和Using Top-Level Containers。李>
      2. 代替我们示例中的星形或线条,..绘制您的图像。我的示例甚至演示了如何让位置在容器边界内反弹。
      3. 当然可以,但是“不包括电池”。我们的目的是为您提供一些想法,然后您可以适应您的弹跳球小程序。我怀疑有人会在小程序中使用球为您创建一个示例。虽然如果您发布一个 SSCCE 来显示您的意图和您尝试过的内容,我(和其他人)通常会使用该来源运行。如果您想要更具体的答案,请询问更具体的 SSCCE。 ;)

      【讨论】:

      • @mKorbel 谢谢。 :-) 出于好奇,您的机器上是否有该代码的典型帧速率?
      • 是的一半刷新率从 RepaintManager 返回第一个漂亮的错误,现在在所有情况下都没有开玩笑(plus_minus_CitiBus)我试图帮助 WinXp 的最大值???刷新率 33/每秒
      • 我在 Wikipedia 上找不到相关的 blablbbla,但 LCD/LED 显示器的刷新率是每一个像素的最大重绘/除以秒,请不要告诉如何快速、更快或fastes 可以在屏幕上绘制一些来自 PL 绘制对象的代码,我没记错,等离子电视非常靠近 CRT 显示器,刷新频率更快:-),因为我成功地学习了电影和照片技术,在这个时候不是我的一杯咖啡
      • @mKorbel "刷新率 33/每秒.." 感谢您的结果!
      • @Andrew 很棒的台词...但基本上我想在 JApplet 中使用图像来做,有可能吗?
      【解决方案3】:

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

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

      【讨论】:

      • 星星向各个不同的方向移动,有 50 种不同的颜色。 ..这是伟大的酸,伙计! +1
      • @Andrew Thompson 在所有情况下都不是真的,因为有一点点修改,但是由 Darryl 提出的原创想法,你必须直接向他表示 3quaters 的荣誉 :-),我只和他一起玩想法,仅此而已,如果/如果您有全高清显示器,那么您可以将其乘以 4x2 矩阵,然后您会看到真正的酸:-)
      • @mKorbel 就像星星一样。 JApplet 是否可以使用球作为图像?我的意思是这确实是我需要的,问题是我想在 JApplet 中使用图像。
      【解决方案4】:

      我想在JApplet做。

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

      【讨论】:

      • 好点子,尤其是当开发人员第一次看到使用Java Web Start 启动的JFrame 并想知道他们为什么需要这个小程序时。 ;)
      • 这当然是 JWS 设计者的意图。在您的指导下,我终于学会了如何调试小程序,但我从来没有真正喜欢不得不这样做。 :-)
      • hmmm 1) Mac OS X @ 2⅔ GHz 上约 40 fps 对于今天的原生操作系统是正确的,WinXP 有点旧,2) 不好的点,优秀 +1
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      相关资源
      最近更新 更多