java中给frame(不是JFrame)设置背景,如何不覆盖组件
2个回答
展开全部
可以直接重写Frame的paint方法 , 但是不推荐,
推荐重写Panel的paint方法方法即可,在paint方法里, 绘制背景图片
import java.awt.Button;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//Panel 组件, 让他绘制背景图片
class ImgPanel extends Panel {
Image img;
public ImgPanel(Image img) {
this.img=img;
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), 0, 0, this.getWidth(), this.getHeight(), this);
}
}
public class MyFrame extends Frame {
public MyFrame() {
TextField tf=new TextField(8);
Button btn = new Button("按钮");
//在imgs包下有一张图片叫1.png
Image img = Toolkit.getDefaultToolkit().createImage(this.getClass().getResource("/imgs/1.png"));
ImgPanel panel = new ImgPanel(img);
panel.add(tf);
panel.add(btn);
add(panel);
setSize(300, 300);
setLocationRelativeTo(null);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new MyFrame().setVisible(true);
}
});
}
}
关于g.drawImage 方法的说明. 请具体查看API, 因为绘制图片的方法很多,参数也不少
java.awt.Graphics.drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer)
Parameters:
img the specified image to be drawn. This method does nothing if img is null.
dx1 the x coordinate of the first corner of the destination rectangle.
dy1 the y coordinate of the first corner of the destination rectangle.
dx2 the x coordinate of the second corner of the destination rectangle.
dy2 the y coordinate of the second corner of the destination rectangle.
sx1 the x coordinate of the first corner of the source rectangle.
sy1 the y coordinate of the first corner of the source rectangle.
sx2 the x coordinate of the second corner of the source rectangle.
sy2 the y coordinate of the second corner of the source rectangle.
observer object to be notified as more of the image is scaled and converted.
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询