`

扩展文本字段风格

阅读更多
package Assis;

import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Shape;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Element;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.ParagraphView;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;

public class ExtendedParagraph {
	public static void createDocumentStyles(StyleContext sc) {
		Style defaultStyle = sc.getStyle(StyleContext.DEFAULT_STYLE);

		// Create and add the main document style
		Style mainStyle = sc.addStyle(mainStyleName, defaultStyle);
		StyleConstants.setLeftIndent(mainStyle, 16);
		StyleConstants.setRightIndent(mainStyle, 16);
		StyleConstants.setFirstLineIndent(mainStyle, 16);
		StyleConstants.setFontFamily(mainStyle, "serif");
		StyleConstants.setFontSize(mainStyle, 12);

		// Create and add the constant width style
		Style cwStyle = sc.addStyle(charStyleName, null);
		StyleConstants.setFontFamily(cwStyle, "monospaced");
		StyleConstants.setForeground(cwStyle, Color.white);

		// Create and add the heading style
		Style heading2Style = sc.addStyle(heading2StyleName, null);
		StyleConstants.setForeground(heading2Style, Color.red);
		StyleConstants.setFontSize(heading2Style, 16);
		StyleConstants.setFontFamily(heading2Style, "serif");
		StyleConstants.setBold(heading2Style, true);
		StyleConstants.setLeftIndent(heading2Style, 8);
		StyleConstants.setFirstLineIndent(heading2Style, 0);

		// Create and add the extended para styles
		Style paraStyle = sc.addStyle(paraStyleName, null);
		Color bgColor = Color.gray;
		ExtendedStyleConstants.setParagraphBackground(paraStyle, bgColor);
		Border bd1 = BorderFactory.createEtchedBorder(bgColor.brighter(),
				bgColor.darker());
		Border bd2 = BorderFactory.createEmptyBorder(4, 4, 4, 4);
		CompoundBorder cb1 = BorderFactory.createCompoundBorder(bd1, bd2);
		Border bd3 = BorderFactory.createEmptyBorder(2, 2, 2, 2);
		CompoundBorder cb2 = BorderFactory.createCompoundBorder(bd3, cb1);
		ExtendedStyleConstants.setParagraphBorder(paraStyle, cb2);
	}

	public static void addText(JTextPane pane, StyleContext sc,
			Style logicalStyle, Paragraph[] content) {
		// The outer loop adds paragraphs, while the
		// inner loop adds character runs.
		int paragraphs = content.length;
		for (int i = 0; i < paragraphs; i++) {
			Run[] runs = content[i].content;
			for (int j = 0; j < runs.length; j++) {
				pane.setCharacterAttributes(
						runs[j].styleName == null ? SimpleAttributeSet.EMPTY
								: sc.getStyle(runs[j].styleName), true);
				pane.replaceSelection(runs[j].content);
			}

			// At the end of the paragraph, add the logical style and
			// any overriding paragraph style and then terminate the
			// paragraph with a newline.
			pane.setParagraphAttributes(SimpleAttributeSet.EMPTY, true);

			if (logicalStyle != null) {
				pane.setLogicalStyle(logicalStyle);
			}

			if (content[i].styleName != null) {
				pane.setParagraphAttributes(sc.getStyle(content[i].styleName),
						false);
			}

			if (i != paragraphs - 1) {
				pane.replaceSelection("\n");
			}
		}
	}

	public static void main(String[] args) {
		try {
			UIManager
					.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (Exception evt) {
		}

		JFrame f = new JFrame("Extended Paragraph Example");

		// Create the StyleContext, the document and the pane
		final StyleContext sc = new StyleContext();
		final DefaultStyledDocument doc = new DefaultStyledDocument(sc);
		final JTextPane pane = new JTextPane(doc);
		pane.setEditorKit(new ExtendedStyledEditorKit());

		try {
			// Add the text and apply the styles
			SwingUtilities.invokeAndWait(new Runnable() {
				public void run() {
					// Build the styles
					createDocumentStyles(sc);

					// Add the text
					addText(pane, sc, sc.getStyle(paraStyleName), content);
				}
			});
		} catch (Exception e) {
			System.out.println("Exception when constructing document: " + e);
			System.exit(1);
		}

		f.getContentPane().add(new JScrollPane(pane));
		f.setSize(400, 300);
		f.setVisible(true);
	}

	// Style names
	public static final String mainStyleName = "MainStyle";

	public static final String heading2StyleName = "Heading2";

	public static final String charStyleName = "ConstantWidth";

	public static final String paraStyleName = "ExtendedPara";

	// Inner classes used to define paragraph structure
	public static class Run {
		public Run(String styleName, String content) {
			this.styleName = styleName;
			this.content = content;
		}

		public String styleName;

		public String content;
	}

	public static class Paragraph {
		public Paragraph(String styleName, Run[] content) {
			this.styleName = styleName;
			this.content = content;
		}

		public String styleName;

		public Run[] content;
	}

	public static final Paragraph[] content = new Paragraph[] {
			new Paragraph(null, new Run[] { new Run(null,
					"Attributes, Styles and Style Contexts") }),
			new Paragraph(
					paraStyleName,
					new Run[] {
							new Run(null, "The simple "),
							new Run(charStyleName, "PlainDocument"),
							new Run(
									null,
									" class that you saw in the previous "
											+ "chapter is only capable of holding text. "
											+ "The more complex text components use a more "
											+ "sophisticated model that implements the "),
							new Run(charStyleName, "StyledDocument"),
							new Run(null, " interface. "),
							new Run(charStyleName, "StyledDocument"),
							new Run(null, " is a sub-interface of "),
							new Run(charStyleName, "Document"),
							new Run(
									null,
									" that contains methods for manipulating attributes "
											+ "that control the way in which the text in the "
											+ "document is displayed. The Swing text package "
											+ "contains a concrete implementation of "),
							new Run(charStyleName, "StyledDocument"),
							new Run(null, " called "),
							new Run(charStyleName, "DefaultStyledDocument"),
							new Run(null,
									" that is used as the default model for "),
							new Run(charStyleName, "JTextPane"),
							new Run(
									null,
									" and is also the base class from which "
											+ "more specific models, such as the "),
							new Run(charStyleName, "HTMLDocument"),
							new Run(
									null,
									" class that handles input in HTML format, can be "
											+ "created. In order to make use of "),
							new Run(charStyleName, "DefaultStyledDocument"),
							new Run(null, " and "),
							new Run(charStyleName, "JTextPane"),
							new Run(null,
									" you need to understand how Swing represents "
											+ "and uses attributes.") }) };
}

class ExtendedStyleConstants {
	public ExtendedStyleConstants(String name) {
		this.name = name;
	}

	public String toString() {
		return name;
	}

	/**
	 * The border to be used for a paragraph. Type is javax.swing.border.Border
	 */
	public static final Object ParagraphBorder = ExtendedParagraphConstants.ParagraphBorder;

	/**
	 * The background to be used for a paragraph. Type is java.awt.Color
	 */
	public static final Object ParagraphBackground = ExtendedParagraphConstants.ParagraphBackground;

	/* Adds the border attribute */
	public static void setParagraphBorder(MutableAttributeSet a, Border b) {
		a.addAttribute(ParagraphBorder, b);
	}

	/* Gets the border attribute */
	public static Border getParagraphBorder(AttributeSet a) {
		return (Border) a.getAttribute(ParagraphBorder);
	}

	/* Adds the paragraph background attribute */
	public static void setParagraphBackground(MutableAttributeSet a, Color c) {
		a.addAttribute(ParagraphBackground, c);
	}

	/* Gets the paragraph background attribute */
	public static Color getParagraphBackground(AttributeSet a) {
		return (Color) a.getAttribute(ParagraphBackground);
	}

	/* A typesafe collection of extended paragraph attributes */
	public static class ExtendedParagraphConstants extends
			ExtendedStyleConstants implements AttributeSet.ParagraphAttribute {
		/**
		 * The paragraph border attribute.
		 */
		public static final Object ParagraphBorder = new ExtendedParagraphConstants(
				"ParagraphBorder");

		/**
		 * The paragraph background attribute.
		 */
		public static final Object ParagraphBackground = new ExtendedParagraphConstants(
				"ParagraphBackground");

		private ExtendedParagraphConstants(String name) {
			super(name);
		}
	}

	protected String name; // Name of an attribute
}

@SuppressWarnings("serial")
class ExtendedStyledEditorKit extends StyledEditorKit {
	public Object clone() {
		return new ExtendedStyledEditorKit();
	}

	public ViewFactory getViewFactory() {
		return defaultFactory;
	}

	/* The extended view factory */
	static class ExtendedStyledViewFactory implements ViewFactory {
		public View create(Element elem) {
			String elementName = elem.getName();
			if (elementName != null) {
				if (elementName.equals(AbstractDocument.ParagraphElementName)) {
					return new ExtendedParagraphView(elem);
				}
			}

			// Delegate others to StyledEditorKit
			return styledEditorKitFactory.create(elem);
		}
	}

	private static final ViewFactory styledEditorKitFactory = (new StyledEditorKit())
			.getViewFactory();

	private static final ViewFactory defaultFactory = new ExtendedStyledViewFactory();
}

class ExtendedParagraphView extends ParagraphView {
	public ExtendedParagraphView(Element elem) {
		super(elem);
	}

	// Override ParagraphView methods
	protected void setPropertiesFromAttributes() {
		AttributeSet attr = getAttributes();
		if (attr != null) {
			super.setPropertiesFromAttributes();
			paraInsets = new Insets(getTopInset(), getLeftInset(),
					getBottomInset(), getRightInset());

			border = ExtendedStyleConstants.getParagraphBorder(attr);
			bgColor = ExtendedStyleConstants.getParagraphBackground(attr);
			if (bgColor != null && border == null) {
				// Provide a small margin if the background
				// is being filled and there is no border
				border = smallBorder;
			}

			if (border != null) {
				Insets borderInsets = border.getBorderInsets(getContainer());
				setInsets((short) (paraInsets.top + borderInsets.top),
						(short) (paraInsets.left + borderInsets.left),
						(short) (paraInsets.bottom + borderInsets.bottom),
						(short) (paraInsets.right + borderInsets.right));
			}
		}
	}

	public void paint(Graphics g, Shape a) {
		Container comp = getContainer();
		Rectangle alloc = new Rectangle(a.getBounds());

		alloc.x += paraInsets.left;
		alloc.y += paraInsets.top;
		alloc.width -= paraInsets.left + paraInsets.right;
		alloc.height -= paraInsets.top + paraInsets.bottom;

		if (bgColor != null) {
			Color origColor = g.getColor();
			g.setColor(bgColor);
			g.fillRect(alloc.x, alloc.y, alloc.width, alloc.height);
			g.setColor(origColor);
		}

		if (border != null) {
			// Paint the border
			border.paintBorder(comp, g, alloc.x, alloc.y, alloc.width,
					alloc.height);
		}
		super.paint(g, a); // Note: pass ORIGINAL allocation
	}

	// Attribute cache
	protected Color bgColor; // Background color, or null for transparent.

	protected Border border; // Border, or null for no border

	protected Insets paraInsets; // Original paragraph insets

	protected static final Border smallBorder = BorderFactory
			.createEmptyBorder(2, 2, 2, 2);
}

 

分享到:
评论

相关推荐

    polymer-input:单行文本字段素材组件演示

    "polymer-input:单行文本字段素材组件演示" 指的是一个基于 Polymer 技术的特定组件——polymer-input,它的主要功能是提供一个用于用户输入的单行文本字段。在 Web 开发中,这样的组件通常用于收集用户的基本信息,...

    chrome-extension-password-revealer:使用此Chrome扩展程序,所有输入字段均为文本

    使用此Chrome扩展程序,所有输入字段均为text类型,而不是password类型。 | 开始使用 这款Chrome扩展程序是在本周末以黑客风格开发的,目的是为了个人目的,并在阅读Google Chrome扩展程序文档后为您带来乐趣。 此...

    instant-sloth:一个 Chrome 扩展程序,它返回一个 HTML 面板,显示各种心情的树懒,可以方便地用作在线社交网站上的React帖子。 单击树懒将其插入活动文本字段。 “随机树懒”功能在 Flickr 上搜索并随机化树懒图像的顺序

    单击树懒将其插入活动文本字段。 “随机树懒”[目前在开发中禁用] 功能在 Flickr 上搜索和随机化树懒图像的顺序。 在 Chrome 商店中查看: : 说明/功能 单击工具栏中的树懒图标打开 InstaSloth 从“心情树懒”...

    数据库同步过程中如何解决大字段的同步

    - 存储空间:大字段可能导致数据库占用过多空间,影响数据库的扩展性和备份效率。 - 事务影响:大字段的更新可能导致事务变大,影响并发性能。 3. 解决策略: - 分离存储:将大字段存储在独立的表或存储服务中,...

    asp.net多功能文本编辑框

    它们提供了一套完整的文本编辑功能,包括字体选择、颜色设定、链接插入、图片上传等,且可以通过API进行定制和扩展。 5. **AJAX支持**:为了提高用户体验,可以利用ASP.NET AJAX控件工具包中的UpdatePanel,使得...

    文本输入视图CBTextFieldView.zip

    传统的文本字段通常只包含一个静态的占位符文本,而CBTextFieldView则引入了动态效果,使得占位符在用户开始输入或失去焦点时,能够以平滑的动画方式消失或出现,这为原本单调的输入过程增添了生动的视觉元素。...

    完整版超文本编辑框.e.rar

    10. **扩展功能**:通过插件或API扩展,如代码高亮、地图集成、PDF预览等。 **富文本编辑器的应用场景:** 1. **博客系统**:让作者能方便地编辑和格式化文章内容。 2. **论坛和社区**:用户发布帖子时可以编辑...

    SSCustomEditTextOutLineBorder:与“材料设计”页面中显示的“概述”文本字段相同,但有一些动态更改

    SSCustomEditTextOutLineBorder是一个基于Android的自定义编辑文本组件,它模仿了“材料设计”(Material Design)规范中的“概述”文本字段(Outline Text Field)的外观和行为,但在此基础上添加了一些动态变化...

    bcms企业站程序支持自定义字段

    管理员可以在这里新增、修改或删除自定义字段,指定它们的类型(如文本、数字、日期等)、是否必填、显示顺序等属性。 【template】文件夹:模板文件夹包含了一系列CSS、HTML和可能的JavaScript文件,用于定义bcms...

    elasticsearch查询模版-模糊查询,多字段查询,相似度计算等

    Elasticsearch(简称ES)是一个基于Apache Lucene构建的开源、分布式、RESTful风格的搜索和数据分析引擎。它允许你以前所未有的速度和规模,即时地存储、搜索和分析大量数据。Elasticsearch通常用于全文搜索、结构化...

    Chrome扩展及应用开发.pdf

    - 通常包含以下字段:`name`、`version`、`description`、`manifest_version`、`background`、`permissions`等。 - **DOM简述** - DOM(Document Object Model)是HTML或XML文档的标准化表示方法,用于处理和操作...

    dayrui-xunruicms-master.zip

    1、文本字段,有单行文本、多行文本、文本事件字段 2、上传字段,有单文件上传、多文件上传 3、日期时间字段,支持自定义年月格式显示 4、联动菜单字段,用于无限分类层级显示的数据,例如城市 5、百度地图字段...

    项目代码风格要求(C#)

    ##### 1.13 类型内部的私有和受保护字段,使用Camel风格命名,但加“_”前缀 - **字段命名**:类型内部的私有和受保护字段应使用camelCase命名,并在前面加上下划线`_`作为前缀。 ##### 1.14 不能出现公有字段 - ...

    富文本编辑器.zip(0积分免费下载)

    富文本编辑器在这个上下文中,意味着用户可以在表单的某些字段中插入和编辑格式化的文本,如添加粗体、斜体、颜色、链接等效果。 2. **SoDiaoEditor.rar**: “SoDiaoEditor”可能是一个独特的富文本编辑器组件,...

    学习Discuz数据库字段说明.pdf

    11. `cdb_bbcodes`:BB代码资料表,定义论坛支持的特殊文本格式。 12. `cdb_blogcaches`:博客缓存表,存储博客的缓存信息。 13. `cdb_buddys`:好友信息表,记录用户之间的朋友关系。 14. `cdb_creditslog`:积分...

    smarter_text_field:更智能的文本表单字段小部件

    在本文中,我们将深入探讨`smarter_text_field`,这是一个专为Dart语言构建的智能文本表单字段小部件。这个库旨在提供比标准`TextField`组件更丰富的功能,以优化用户界面和交互体验,特别是在移动应用开发中。 1. ...

    通用查询GRID风格数据窗口要显示的列

    GRID风格是指将数据组织成网格或表格形式,每一行代表一条记录,每一列对应数据的一个字段。这种布局使得数据易于阅读和理解,且通常支持排序、筛选、分页等交互功能。GRID风格在用户界面设计中广泛使用,因为其...

    tinymce富文本4.7.5资源

    3. **扩展的API支持**:4.7.5版提供了更丰富的API接口,允许开发者更灵活地控制编辑器的行为,如自定义按钮、事件监听等。 4. **新插件与主题**:新增或更新了一系列插件,如拼写检查、代码编辑器等,满足不同场景...

    易语言五步生成数据库完全版(易语言2005年大赛三等奖)

    数据库,数据库应用程序,数据操作支持库一,高级表格支持库,网络通讯支持库,XP风格界面库,扩展界面支持库一,超文本浏览框支持库,操作系统界面功能支持库, 五步数据库设计系统通过向导式的步聚,引导用户创建自己的...

Global site tag (gtag.js) - Google Analytics