我正在使用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
目录
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句