大声笑,我刚才完全失败了。删除某些内容后上传代码。
无论如何,我使用 ImageIcons 加载了背景,但我正在尝试使用 BufferedImage,因为这就是我被告知您必须这样做才能在其上绘制更多图像的方式。
BufferedImage 不返回错误,但不绘制任何内容。
代码如下:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Client {
static JFrame client = new JFrame();
public static void drawBackground() throws IOException {
BufferedImage background = ImageIO.read(new File("Resources/Images/Background.png"));
client.setTitle("Keldagrim: The lost Empire");
client.setSize(1280, 720);
client.setDefaultCloseOperation(client.EXIT_ON_CLOSE);
Container pane = client.getContentPane();
BackgroundPanel backgroundPanel = new BackgroundPanel(background);
pane.add(backgroundPanel);
client.pack();
client.setVisible(true);
}
public static void drawLogin() {
ImagePanel loginBox = new ImagePanel(new ImageIcon("Resources/Images/LoginBox.png").getImage());
client.add(loginBox);
client.repaint();
System.out.println("Painted");
}
public static void main(String[] args) {
try {
drawBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
drawLogin();
}
}
class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
class BackgroundPanel extends JPanel {
BufferedImage backgroundImage;
public BackgroundPanel(BufferedImage image){
backgroundImage = image;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(backgroundImage, null, 50,50);
}
}