问答题
本程序的功能是将图像“exam_36.gif”显示在窗口的正中间,并且设置窗口的颜色为白色,如图所示。
import java.awt.*;
import javax.swing.*;
public class exam_36
public static void main(String[] args)
{
ImageFrame frame=new ImageFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class ImageFrame extends JFrame
{
public ImageFrame()
{
setTitle("exam_36");
setSize(WIDTH, HEIGHT);
ImagePanel panel=new ImagePanel();
Container
contentPane=getContentPane();
contentPane.add(panel);
}
public static final int WIDTH=300;
public static final int HEIGHT=200;
}
class ImagePanel extends JPanel
{
public ImagePanel()
{
setBackground(Color.white);
image=Toolkit.getDefaultToolkit().
MediaTracker tracker=new MediaTracker(this);
tracker.addImage(image, i);
try
{
tracker.waitForID(1);
}
catch (InterruptedException exception)
{}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int imageWidth=image.getWidth(this);
int imageHeight=image.getHeight(this);
int FrameWidth=getWidth();
int FrameHeight=getHeight();
int x=(FrameWidth - imageWidth ) / 2;
int y=(FrameHeight - imageHeight ) / 2;
______(image, x, y, null);
}
private Image image;
}
【参考答案】
第1处:getImage("exam_36.gif")
第2处:g.drawImage