Java窗体JTextArea添加背景图片
本来是想把文本框透明化显示出底层的图片的,但是没有找到方法,只能退而求其次,希望有大佬教一下。
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Test extends JFrame {
private static final long serialVersionUID = 4785452373598819719L;
private JScrollPane sp = null;
private JTextArea text = null;
private ImageIcon imageIcon = null;
public Test() {
super("JTextArea");
//图片路径
imageIcon = new ImageIcon("D:\\eclipse-workspace\\et\\bin\\test\\bg.gif");
// 构造文本组件并使之透明
text = new JTextArea();
text.setOpaque(false);
// 构造滚动组件并使之透明
sp = new JScrollPane(text);
sp.setOpaque(false);
sp.getViewport().setOpaque(false);
// 构造一个背景JPanel
JPanel backdrop = new JPanel() {
private static final long serialVersionUID = 1957203784117943458L;
{
this.setOpaque(false);
this.setLayout(new BorderLayout());
}
public void paintComponent(Graphics g) {
g.drawImage(imageIcon.getImage(), 0, 0, this);
super.paintComponents(g);
}
};
// 将滚动组件加入
backdrop.add(sp);
// 将背景组件加入窗体
this.getContentPane().add(backdrop);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(655, 400);
int screen_width = Toolkit.getDefaultToolkit().getScreenSize().width;
int screen_height = Toolkit.getDefaultToolkit().getScreenSize().height;
this.setLocation((screen_width - this.getWidth()) / 2,(screen_height - this.getHeight()) / 2);
this.setVisible(true);
}
public static void main(String args[]) {
new Test();
}
}