2 回答
TA贡献1802条经验 获得超4个赞
我很确定您的意思是要在面板上绘制图像。首先,我建议您在项目 src 文件夹中创建一个资源文件夹,并在那里添加所有图像。完成后,您必须使用 imageIO 加载图像并使用 drawImage 绘制它。这是一个简短的示例:
package asteroid;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Nave {
BufferedImage iconeNave;
public Nave( ... ) {
try{
iconeNave = ImageIO.read(getClass().getResource("/resources/nave.png"));
}catch(IOException e){e.printStackTrace();}
catch(Exception e){e.printStackTrace();}
}
@Override
public void paint(Graphics2D g2){
AffineTransform at = new AffineTransform();
at.translate((int)x + radius/2.5,(int)y + radius/2.5);
at.rotate(Math.PI/2 + angle);
at.translate(-iconeNave.getWidth()/2, -iconeNave.getHeight()/2);
g2.drawImage(iconeNave, at, null);
}
}
TA贡献1812条经验 获得超5个赞
为了在 Java 中创建图像,您首先需要创建一个 JPanel(本质上是屏幕上的一个窗口)。它看起来像这样(取自 javacodex.com):
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import javax.imageio.ImageIO;
public class JPanelExample {
public static void main(String[] arguments) throws IOException {
JPanel panel = new JPanel();
BufferedImage image = ImageIO.read(new File("./java.jpg"));
JLabel label = new JLabel(new ImageIcon(image));
panel.add(label);
// main window
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JPanel Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the Jpanel to the main window
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
但是,我假设“图像”是指在屏幕上绘制的形状(因为您在示例中使用了绘制圆的绘制方法)。然后,您的代码采用正确的方法,但需要实现 JPanel(因为没有 JPanel 或 JFrame,您实际上无法在屏幕上以图形方式显示任何内容)。
下面是取自我的 Atari Breakout 迷你游戏的 Board.java 的示例:
public class Board extends JPanel implements KeyListener {
// Other Game Code
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
// Shows lives left and score on screen
g2.drawString("Lives left: " + lives, 400, 600);
g2.drawString("Score: " + score, 400, 500);
// Paints Walls (separate paint method created in wall class)
topWall.paint(g2);
bottomWall.paint(g2);
leftWall.paint(g2);
rightWall.paint(g2);
// Paints 2 Balls (separate paint method created in ball class)
b.paint(g2);
b2.paint(g2);
// Paints Paddle (separate paint method created in paddle class)
paddle.paint(g2);
// Paints Bricks based on current level (separate paint method created in brick class)
// Bricks were created/stored in 2D Array, so drawn on screen through 2D Array as well.
if (level == 1) {
for (int x = 0; x < bricks.length; x++) {
for (int i = 0; i < bricks[0].length; i++) {
bricks[x][i].paint(g2);
}
}
}
if (level == 2) {
for (int x = 0; x < bricks.length; x++) {
for (int i = 0; i < bricks[0].length; i++) {
bricks[x][i].paint(g2);
}
}
}
}
这是 Paddle 类中的 Paint 方法的示例:
// Constructor
public Paddle(int x, int y, int w, int h){
xpos = x;
ypos = y;
width = w;
height = h;
r = new Rectangle(xpos, ypos, width, height);
}
public void paint(Graphics2D g2){
g2.fill(r);
}
输出(屏幕上显示的内容):
添加回答
举报