Java选择随机图像 [英] java pick random images
本文介绍了Java选择随机图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
英语不是我的母语,对于任何错误,我们深表歉意.我必须用Java制作Bubble Shooter游戏.我想将图像用于气泡,并且希望随机拾取图像.我使用了Random
和ImageIcon
类.我的程序在编译时没有显示任何内容,也不知道问题出在哪里.我是Java的初学者.
English is not my native language, sorry for any mistakes. I have to make a Bubble Shooter game in Java. I want to use images for the bubbles and I want the images to be picked randomly. I used Random
and ImageIcon
classes. My program doesn't show anything when I compile it and I don't know where the problem is. I'm a beginner in Java.
这是我的Game类的代码:
This is the code for my Game class:
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);
}
}
我的程序怎么了?
推荐答案
查看我的注释,仔细查看代码中的注释,看看如何重新安排类的组织.
Look over my comments, look carefully at the comments in the code, see how I rearranged the organization of the classes.
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[]{
"http://i.stack.imgur.com/gJmeJ.png",
"http://i.stack.imgur.com/IHARa.png",
"http://i.stack.imgur.com/wCF8S.png",
"http://i.stack.imgur.com/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);
}
}
提示
-
Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException: getGraphics() not valid for images created with createImage(producer) at img = createImage(null);
我不知道您认为该代码语句的作用,但是..没什么好处. - 在
JPanel
中进行自定义绘画时,我们应仅覆盖paintComponent(Graphics)
并保留paint(Graphics)
方法.覆盖前者时,请立即调用super方法. - 在
paint(Graphics)
内部添加对repaint()
的调用将导致无限循环.如果代码需要循环,请建立一个Swing计时器来调用repaint()
-
paintComponet(Graphics g)
应该为paintComponent(Graphics g)
在适当的情况下使用@Override
表示法.会警告您拼写错误的方法名称. Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException: getGraphics() not valid for images created with createImage(producer) at img = createImage(null);
I have no idea what you thought that code statement does, but ..nothing good.- When doing custom painting in a
JPanel
, we should override onlypaintComponent(Graphics)
and leave thepaint(Graphics)
method as it is. When overriding the former, immediately call the super method. - Adding a call to
repaint()
insidepaint(Graphics)
will cause an infinite loop.. If the code needs to loop, establish a Swing Timer to callrepaint()
paintComponet(Graphics g)
should bepaintComponent(Graphics g)
Use@Override
notation when appropriate. It would have warned you of the incorrectly spelled method name.- 要尽快获得更好的帮助,请发布 MCVE .
- 获取图像的一种方法是将其链接到在此答案中看到的图像 .
- 在部署时,这些映像可能会成为嵌入式资源.在这种情况下,必须由
URL
而不是File
访问它们.有关标签的信息,请参见信息页面,以了解形成URL
的方法. - For better help sooner, post an MCVE.
- One way to get image(s) for an example is to hot-link to the images seen in this answer.
- By the time of deployment, those images will likely become an embedded-resource. That being the case, they must be accessed by
URL
instead ofFile
. See the info page for the tag, for a way to form anURL
.
Tips
这篇关于Java选择随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文