[英]using an image as a background in java
我正在使用Java來實現一個包含圖像作為背景的窗口。
這是我做的代碼
import java.awt.*;
import javax.swing.*;
public class FenImage extends JFrame {
private JLabel question ;
private JButton valider ;
private JPanel pan ;
public FenImage()
{
this.setTitle("Image");
this.setBounds(200, 500,600,450);
this.setLayout(new BorderLayout());
JLabel question = new JLabel(" \t \t L'image qu'on peux utiliser pour présenter ce mot est : ");
//this.add(question);
this.getContentPane().add(question,BorderLayout.NORTH);
JPanel pan = new JPanel()
{
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
ImageIcon m = new ImageIcon("1.jpg");
Image monImage = m.getImage();
g.drawImage(monImage, 0, 0,this);
}
};
this.getContentPane().add(pan);
但是當我運行時,我只會得到我添加的標簽。
有什么問題 ? 以及如何正確添加
將標簽添加到面板而不是框架
JLabel question = new JLabel(" \t \t L'image qu'on peux utiliser pour présenter ce mot est : ");
JPanel pan = new JPanel()
{
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
ImageIcon m = new ImageIcon("1.jpg");
Image monImage = m.getImage();
g.drawImage(monImage, 0, 0,this);
}
};
pane.setLayout(new BorderLayout());
pane.add(question, BorderLayout.NORTH);
this.getContentPane().add(pan);
您應該避免在paint方法中加載資源,因為這會增加內存使用量,從而降低繪畫速度
更新
ImageIcon(String)
假定String值是對文件系統上文件的引用。 存儲在src
目錄中的內容將被構建到jar中,從而將其轉換為嵌入式資源。
為了加載這些資源,您需要使用Class#getResource
,例如
ImageIcon m = new ImageIcon(getClass().getResource("/1.jpg"));
假設資源位於src
目錄的默認目錄(頂層目錄)中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.