java选择随机图像

标签 java image swing random paintcomponent

英语不是我的母语,对于任何错误,我们深表歉意。我必须用 Java 制作一个泡泡射击游戏。我想使用气泡图像,并且我希望随机选取图像。我使用了 Random 和 ImageIcon 类。我的程序编译时没有显示任何内容,我不知道问题出在哪里。我是 Java 初学者。

这是我的 Game 类的代码:

import java.awt.Graphics;
import java.awt.Image;
import java.util.Vector;

import javax.swing.JPanel;

public class Game extends JPanel{
  private static final long serialVersionUID = 1L;

  //what the balls are like
  public final static int START_BALLS=40;
  public static Vector<Ball> balls = new Vector<Ball>();
  private Image img;
  private Graphics graphics;

  public Game() {
    for(int i=0; i<START_BALLS; i++) {
      balls.add(new Ball());
    }
  }

  public void paint(Graphics g) {
    img = createImage(null);
    graphics = img.getGraphics();
    paintComponent(graphics);
    g.drawImage(img, 0, 0, null);
    repaint();
  }

  public void paintComponet(Graphics g) {
    for(int i=0; i<balls.size(); i++) {
      Ball b=(Ball)balls.get(i);
      b.draw(g);
    }
  }

  public static void main(String [] args) {
    new Frame();
    Game game = new Game();
    new Game();
    Window.window.add(game);
  }
}

以及气泡的类:

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.Random;

import javax.swing.ImageIcon;

public class Ball {
  Random random = new Random();
  final String[] image_paths = new String[] {"balls/peg_0.png",
            "balls/peg_1.png","balls/peg_2.png","balls/peg_3.png",
            "balls/peg_4.png","balls/peg_5.png"};

  String randomBalls;
  public Image image;

  public Ball(){
    randomBalls = image_paths[random.nextInt(image_paths.length)];
    ImageIcon poza = new ImageIcon(randomBalls);
    image=poza.getImage();
  }

  public void draw(Graphics g){
    g.drawImage(image, 0, 0, null, null);
  }
}

我的程序出了什么问题?

最佳答案

看看我的注释,仔细看看代码中的注释,看看我是如何重新安排类的组织的。

Game demo

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.Random;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.imageio.ImageIO;
import java.net.URL;

public class Game extends JPanel {

    Random random = new Random();
    final String[] image_path = new String[]{
        "/image/gJmeJ.png",
        "/image/IHARa.png",
        "/image/wCF8S.png",
        "/image/T5uTa.png"
    };
    private static final long serialVersionUID = 1L;
    //what the balls are like
    public final static int START_BALLS = 40;
    public static Vector<Ball> balls = new Vector<Ball>();
    private Image img;
    // A Graphics instance is typically transient.
    // There is rarely, if ever, a need to store them
    //private Graphics graphics;

    public Game() {
        for (int i = 0; i < image_path.length; i++) {
            balls.add(new Ball(image_path[i]));
        }
        //I have no idea what you were trying to achieve here, but it fails horribly
        // img = createImage(null);
        img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
        // graphics = img.getGraphics();
        ActionListener al = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                repaint();
            }
        };
        Timer timer = new Timer(400, al);
        timer.start();
    }

    @Override  // very handy!
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // g.drawImage(img, 0, 0, null);  A JPanel IS A ImageObserver
        g.drawImage(img, 0, 0, this);
        Ball b = (Ball) balls.get(random.nextInt(4));
        b.draw(g);
    }

    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                JFrame f = new JFrame("Game");
                f.add(new Game());
                // Ensures JVM closes after frame(s) closed and
                // all non-daemon threads are finished
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                // See https://stackoverflow.com/a/7143398/418556 for demo.
                f.setLocationByPlatform(true);

                // ensures the frame is the minimum size it needs to be
                // in order display the components within it
                f.pack();
                // should be done last, to avoid flickering, moving,
                // resizing artifacts.
                f.setVisible(true);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}

class Ball {

    String randomBalls;
    public Image image;

    public Ball(String url) {
        try {
            image = ImageIO.read(new URL(url));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void draw(Graphics g) {
        g.drawImage(image, 0, 0, null, null);
    }
}

提示

  • 线程“AWT-EventQueue-0”中的异常 java.lang.UnsupportedOperationException: getGraphics() 对于在 img = createImage(null) 处使用 createImage(生产者) 创建的图像无效; 我不知道您认为该代码语句的作用,但是..没有什么好处。
  • JPanel 中进行自定义绘画时,我们应该仅重写 paintComponent(Graphics) 并保留 paint(Graphics) 方法不变。当重写前者时,立即调用 super 方法。
  • paint(Graphics)内添加对repaint()的调用将导致无限循环。如果代码需要循环,请建立一个Swing Timer来调用repaint()
  • paintComponet(Graphics g) 应为 paintComponent(Graphics g) 在适当的时候使用 @Override 表示法。它会警告您拼写错误的方法名称。

更多一般提示

  1. 为了更快地获得更好的帮助,请发布 MCVE .
  2. 获取示例图像的一种方法是热链接到 this answer 中看到的图像。 。
  3. 到部署时,这些镜像可能会变成 。既然如此,它们必须通过 URL 而不是 File 来访问。请参阅info page对于标签,对于形成 URL 的方式。

关于java选择随机图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21025595/

相关文章:

Java/Open CL/Aparapi : What to kind of performance to expect from which device?

image - 如何使用 GIF 获得更好的透明度?

c# - 绑定(bind)列表和 UI 控件,编辑时不更新

java - 链接到动态网页中的图像

java - 在 JPanel 之间传递数据

java - 计算下一个生日日期时日期跳过一年

java - 从 Json 生成 POJO 实例

java - ProcessBuilder 找不到 perl

java - 获取 Swing GridLayout 中特定行和列的小部件

java - 为什么 Jtable 中行高自动调整不起作用