无论如何,我得到了使用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);
}
}
答案 0 :(得分:2)
有许多事情不适合你...
drawClient
,因此永远不会创建该框架。我实际上会摆脱这种方法,因为它没有添加任何值,实际上是混淆了问题。setVisible
在您完成框架设置后,如果您不尝试使用类似......
的内容public class Client extends JPanel {
private Image backgroundImage;
public Client(Image backgroundImage) {
this.backgroundImage = backgroundImage;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
BufferedImage background = null;
try {
background = ImageIO.read(new File("Resources/Images/Background.png"));
JFrame client = new JFrame();
client.setTitle("Keldagrim: The lost Empire");
client.setSize(1280, 720);
client.setDefaultCloseOperation(client.EXIT_ON_CLOSE);
client.setContentPane(new Client(background));
client.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
另外,作为附注,你实际上并没有画背景,但我怀疑这是另一个问题;)
试着看看
答案 1 :(得分:0)
试试这个:
if (backgroundImage != null) {
Client c = new Client(backgroundImage);
c.drawClient();
} else {
System.out.println("Error: No background Image.");
}