我想人們會恨我重複這個:P:
- 不要延長JFrame類
- 類名與captial字母開頭即
Guikopie
而且取決於背景是什麼用於ie,如果它的徽標將被添加到JPanel
上的特定位置,然後使用JLabel
是好的,但是,如果它被用作背景它不是;因爲隨着更多組件的添加,它會移動,因此我們不應該將背景作爲組件添加,而是在組件上繪製背景。
至於你的問題:
我的問題是:爲什麼這個代碼不顯示圖片?
您的代碼適合我,因此您的圖片的位置必須錯誤。
我沒有展示如何添加Image
到JPanel
背景,然後添加JPanel
到JFrame
一個簡單的例子,它也包括ImgUtils
類調整畫面:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JFrameWithPicture {
public JFrameWithPicture() throws MalformedURLException, IOException {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
new JFrameWithPicture();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
private void initComponents() throws MalformedURLException, IOException {
JFrame frame = new JFrame("Frame with JPanel and background");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Image background = ImageUtils.scaleImage(300, 300, ImageIO.read(new URL("http://images2.layoutsparks.com/1/98191/naruto-14-red-design.jpg")));
final Dimension jpanelDimensions = new Dimension(new ImageIcon(background).getIconWidth(), new ImageIcon(background).getIconHeight());
frame.add(new JPanel() {
@Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
grphcs.drawImage(background, 0, 0, this);
}
@Override
public Dimension getPreferredSize() {
return jpanelDimensions;
}
});
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
}
class ImageUtils {
public static BufferedImage scaleImage(int width, int height, String filename) {
BufferedImage bi;
try {
ImageIcon ii = new ImageIcon(filename);
bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(ii.getImage(), 0, 0, width, height, null);
} catch (Exception e) {
return null;
}
return bi;
}
static Image scaleImage(int width, int height, BufferedImage filename) {
BufferedImage bi;
try {
bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(filename, 0, 0, width, height, null);
} catch (Exception e) {
return null;
}
return bi;
}
}
或者,您可能希望使用Image#getScaledInstance(int width,int height,int hints)調整大小,但是this has its perils,主要問題是:
Image.getScaledInstance()
不會返回完成的縮放圖像。 當使用圖像 像素時,稍後會留下大量縮放工作。
它在我的電腦上工作。請檢查您的圖像的路徑。 – Juvanis
你採取了哪條路? – maximus
「src/icon.png」這是我的java源文件夾中的圖像。 – Juvanis