java swing中給面板或者文字域設定背景圖片的方法!
以JPanel為例
public class MyTextArea extends JPanel{
/**
* @param args
*/
private Image bgImg = null;
public MyTextArea()
{
setOpaque(false);
bgImg = Toolkit.getDefaultToolkit().createImage(
BGTextArea.class.getResource( "login2.gif ")); //圖片要放在包下面
}
protected void paintComponent(Graphics g) {
g.drawImage(bgImg, 0, 0, getWidth(), getHeight(), this);
super.paintComponent(g);
}
public static void main(String[] args) {
MyTextArea ta = new MyTextArea();
ta.setLayout(new FlowLayout());
JFrame f = new JFrame();
f.getContentPane().add(ta, BorderLayout.CENTER);
JTextField tf=new JTextField(14);
ta.add(tf);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(390, 300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}