用java编图形界面,想要用图片作为窗口的背景怎样实现?求大哥些帮帮忙
2个回答
展开全部
直接改窗体的背景不太好,因为窗体的重画方法的调用时机不太好弄.
实现方法如下.
继承PANEL类,实现一个自己的panel类,然后重写paint()方法来搞定.
下边是实现的代码.你参考一下.
------------------------------------------------------------------------------------------------------
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Img extends JFrame {
public Img() {
setSize(400, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(null);
JPanel panel = new MyImage();
panel.setBounds(0, 0, 400, 500);
getContentPane().add(panel);
setVisible(true);
}
public static void main(String[] args) {
new Img();
}
class MyImage extends JPanel {
public MyImage() {
setLayout(null);
}
public void paint(Graphics g) {
super.paint(g);
ImageIcon img = new ImageIcon("G:\\4.jpg");
g.drawImage(img.getImage(), 0, 0, 400, 500, this);
}
}
}
实现方法如下.
继承PANEL类,实现一个自己的panel类,然后重写paint()方法来搞定.
下边是实现的代码.你参考一下.
------------------------------------------------------------------------------------------------------
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Img extends JFrame {
public Img() {
setSize(400, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(null);
JPanel panel = new MyImage();
panel.setBounds(0, 0, 400, 500);
getContentPane().add(panel);
setVisible(true);
}
public static void main(String[] args) {
new Img();
}
class MyImage extends JPanel {
public MyImage() {
setLayout(null);
}
public void paint(Graphics g) {
super.paint(g);
ImageIcon img = new ImageIcon("G:\\4.jpg");
g.drawImage(img.getImage(), 0, 0, 400, 500, this);
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询