// 这个帖子明明回复过了,怎么过几个小时再看就没有了呢?
// 是不是论坛出现数据丢失现象了, 让人心寒
// 还有wind2005 的那个JTable 的问题也回复了,现在再让我写一遍,可是没有耐心了。
[CODE]
import java.awt.*;
import javax.swing.*;
class MyImagePanel extends JPanel
{
private static Image img;
public MyImagePanel()
{
setBackground(Color.white);
setPreferredSize(new Dimension(500, 300));
img = getToolkit().getImage(ImageAsBackgroundDemo.class.getResource("Blue hills.jpg"));
}
private void paintMyImage(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
int width = getWidth();
int height = getHeight();
if(img != null)
g2.drawImage(img, 0, 0, width, height, this);
}
private void drawMyString(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
String fontName = "Serif";
int fontStyle = Font.BOLD;
int fontSize = getWidth()/10;
Font f = new Font(fontName, fontStyle, fontSize);
g2.setFont(f);
String greeting = "Hello, I am Kai.";
int widthOfGreeting = g.getFontMetrics().stringWidth(greeting);
int widthOfPanel = getWidth();
int heightOfPanel = getHeight();
int x = (widthOfPanel - widthOfGreeting)/2;
int y = heightOfPanel/4;
g2.drawString(greeting, x, y);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
paintMyImage(g);
drawMyString(g);
}
}
public class ImageAsBackgroundDemo extends JFrame
{
public ImageAsBackgroundDemo()
{
super("ImageAsBackgroundDemo");
//create my JPanel object
MyImagePanel myImagePanel = new MyImagePanel();
setContentPane(myImagePanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String [] args)
{
new ImageAsBackgroundDemo();
}
}
[/CODE]