【发布时间】:2012-01-17 17:51:59
【问题描述】:
我的最终目标是拥有一个带有背景图像的JTextArea。我在网上找到了向我展示如何执行此操作的代码,但现在我遇到了文本位于图像顶部的问题。
这就是我的意思:
有什么办法可以添加一种向内缩进,使文本不与图像边缘重叠?
这是原始评论气泡图。
代码如下:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.GrayFilter;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class myBackgroundSample {
String file;
public myBackgroundSample(String i) {
file = i;
setItUp();
}
public void setItUp() {
final ImageIcon imageIcon = new ImageIcon(file);
JTextArea textArea = new JTextArea() {
Image image = imageIcon.getImage();
public void paint(Graphics g) {
setOpaque(false);
g.drawImage(image, 0, 0, this);
super.paint(g);
}
};
JFrame frame = new JFrame("Background Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane(textArea);
Container content = frame.getContentPane();
content.add(scrollPane, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String right = "chat1.jpg";
myBackgroundSample temp = new myBackgroundSample(right);
}
}
【问题讨论】:
-
1) 为什么是
JTextArea(而不是JLabel或其他样式化的组件)? 2) 我认为最好使用 custom 边框,CommentBubbleBorder。 3) Swing 组件应该覆盖paintComponent(Graphics),而不是paint(Graphics)。 -
现在是时候为您的某些earlier questions 选择答案了吗?