lee*_*.zd 2 java swing jpanel jframe
我读了几个关于我的主题的答案,但我没有找到答案.我想要一个我的java代码的背景.我在这里仅指代放置图像的代码,但它不起作用.
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class background extends JFrame {
private Container c;
private JPanel imagePanel;
public background() {
initialize();
}
private void initialize() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
c = getContentPane();
imagePanel = new JPanel() {
public void paint(Graphics g) {
try {
BufferedImage image = ImageIO.read(new File("http://www.signe-zodiaque.com/images/signes/balance.jpg"));
g.drawImage(image, 1000, 2000, null);
} catch (IOException e) {
e.printStackTrace();
}
}
};
imagePanel.setPreferredSize(new Dimension(640, 480));
c.add(imagePanel);
}
Run Code Online (Sandbox Code Playgroud)
你在哪里找到那个代码?如果从教程中,请丢弃它,因为它教你很不好的习惯.例如,...
paint(...)或paintComponent(...)方法中读取图像文件(或任何文件).首先,为什么每次重新绘制程序时都要重新读取程序,只需一次读取它就可以完成.但更重要的是,你希望你的paint/paintComponent方法尽可能精简,尽可能快,因为如果没有,你的绘图很慢而且很笨拙,用户会感觉你的程序很慢而且很笨拙.paintComponent(...)方法绘制你的绘图,而不是它的paint(...)方法.当你画画时,你将失去Swing免费提供的所有双重缓冲,你的动画将是生涩的.paintComponent(...)方法.例如...
public class ZodiacImage extends JPanel {
private static final String IMG_PATH = "http://www.signe-zodiaque.com/" +
"images/signes/balance.jpg";
private BufferedImage image;
public ZodiacImage() {
// either read in your image here using a ImageIO.read(URL)
// and place it into the image variable, or else
// create a constructor that accepts an Image parameter.
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
// draw your image here.
}
}
@Override //if you want the size to match the images
public Dimension getPreferredSize() {
if (image != null) {
return new Dimension(image.getWidth(), image.getHeight());
}
return super.getPreferredSize();
}
}
Run Code Online (Sandbox Code Playgroud)