java如何设置一幅图像为jframe的背景图,要求,背景图能够随着jframe的调整缩放。

2024-12-14 20:46:22
推荐回答(1个)
回答1:

import java.awt.*;
import javax.swing.*;

public class MainFrame extends JFrame {
MainFrame() {
add(new ContentPanel());
setSize(500, 300);
}

public static void main(String[] args) {
MainFrame jrframe = new MainFrame();
jrframe.setVisible(true);
}
}

class ContentPanel extends JPanel {
Image bgimage = null;

ContentPanel() {
MediaTracker mt = new MediaTracker(this);
bgimage = Toolkit.getDefaultToolkit().getImage("a.gif");
mt.addImage(bgimage, 0);
try {
mt.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

protected void paintComponent(Graphics g) {
g.drawImage(bgimage, 0, 0, getSize().width, getSize().height, null);
}
}