Java如何在JTextPane中添加背景图像?
下面的示例演示如何创建JTextPane具有背景图像的自定义组件。
package org.nhooo.example.swing;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class TextPaneWithBackgroundImage extends JFrame {
public TextPaneWithBackgroundImage() {
initUI();
}
private void initUI() {
setSize(400, 400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
String imageFile = "/logo.png";
CustomTextPane textPane = new CustomTextPane(imageFile);
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setPreferredSize(new Dimension(getWidth(), getHeight()));
getContentPane().add(scrollPane);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TextPaneWithBackgroundImage().setVisible(true);
}
});
}
}
/**
* A custom text pane that have a background image. To customize the
* JTextPane we override the paintComponent(Graphics g) method. We have
* to draw an image before we call the super class paintComponent method.
*/
class CustomTextPane extends JTextPane {
private String imageFile;
/**
* Constructor of custom text pane.
* @param imageFile image file name for the text pane background.
*/
CustomTextPane(String imageFile) {
super();
// 为了能够绘制背景图像,组件必须
// 不透明。
setOpaque(false);
setForeground(Color.BLUE);
this.imageFile = imageFile;
}
@Override
protected void paintComponent(Graphics g) {
try {
// 为out JTextPane的背景图像加载图像。
BufferedImage image = ImageIO.read(getClass().getResourceAsStream(imageFile));
g.drawImage(image, 0, 0, (int) getSize().getWidth(),
(int) getSize().getHeight(), this);
} catch (IOException e) {
e.printStackTrace();
}
super.paintComponent(g);
}
}热门推荐
10 闺蜜小孩祝福语简短
11 祝福语简短的微信
12 生日祝福语男生韩语简短
13 谢谢学校老师祝福语简短
14 同学毕业祝福语有趣简短
15 结婚伴娘祝福语简短精辟
16 伴娘祝福语简短朋友的话
17 生日奶茶红包祝福语简短
18 新郎致辞诗句祝福语简短