我正在尝试将图像放入JFrame。在下面的代码中,我创建了一个1020 x 720矩形,我想在该矩形内放置一个图像。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Screen extends JFrame
{
private BufferedImage image;
public Screen () {
super("DVD Screensaver");
Container container = getContentPane();
setSize(1020, 720);
setVisible(true);
}
public void paint(Graphics g) {
int windowHorizantal = 0, windowVerticle = 0;
windowHorizantal = 1020;
windowVerticle = 720;
g.setColor(Color.BLACK);
g.fillRect(1, 1, windowHorizantal, windowVerticle);
try {
image = ImageIO.read(getClass().getResource("dvd.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
g.drawImage(image, 50, 50, null);
}
public static void main(String[] args) {
Screen prog = new Screen ();
prog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
运行此代码时,出现以下错误:“线程“ AWT-EventQueue-0”中的异常java.lang.IllegalArgumentException:input == null!”,但它确实绘制了黑色矩形。我也无法验证代码是否正在实际读取我的图像(dvd.png)。