JTextPane的例子,模拟聊天客户端,演示了为每段文字设置字体、字号、样式、颜色、背景色和插入图片功能
import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.UIManager; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; /** * JTextPane的例子,模拟聊天客户端,演示了为每段文字设置字体、字号、样式、颜色、背景色和插入图片功能 * @author 五斗米 <如转载请保留作者和出处> * @blog http://blog.csdn.net/mq612 */ public class Test extends JFrame {
private static final long serialVersionUID = -2397593626990759111L; private JScrollPane scrollPane = null; // 滚动 private JTextPane text = null; // 不用说了,如果不认识的话就没必要往后看了 private Box box = null; // 放输入组件的容器 private JButton b_insert = null, b_remove = null, b_icon = null; // 插入按钮;清除按钮;插入图片按钮 private JTextField addText = null; // 文字输入框 private JComboBox fontName = null, fontSize = null, fontStyle = null, fontColor = null, fontBackColor = null; // 字体名称;字号大小;文字样式;文字颜色;文字背景颜色 private StyledDocument doc = null; // 非常重要插入文字样式就靠它了 public Test() {
super("JTextPane Test"); try { // 使用Windows的界面风格 UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception e) {
e.printStackTrace(); } text = new JTextPane(); text.setEditable(false); // 不可录入 doc = text.getStyledDocument(); // 获得JTextPane的Document scrollPane = new JScrollPane(text); addText = ne |