我一直在寻找这一段时间,到目前为止,我已经能够想出的是如何创建一个风格,并将其应用于如下所示的角色:
StyledDocument doc = (StyledDocument) new DefaultStyledDocument(); JTextPane textpane = new JTextPane(doc); textpane.setText("Test"); javax.swing.text.Style style = textpane.addStyle("Red",null); StyleConstants.setForeground(style,Color.RED); doc.setCharacterAttributes(0,1,textpane.getStyle("Red"),true);
如果您的文档中只有几种样式,并希望按名称存储它们,这样可以轻松应用,这很有用.在我的应用程序中,我想要为文本中的每个字符独立设置前景色(只有几个值之一)和背景颜色(灰度,许多不同的值).为此创造潜在的数百种/不同的风格似乎是一个巨大的浪费.有没有办法设置这些属性,而不必每次创建一个新的样式?如果我只需要呈现文本就会更容易,但是我也需要使其可编辑.有没有办法用JTextPane做这个,还是有另一个摆放类提供这个功能?
解决方法
如果要更改文本框中每个字符的样式,这里是一个完整的随机方式来执行.您为每个字符创建一个不同的属性集.由你找到适当的组合(前景/背景对比,字符大小不同等等).您还可以存储已应用的不同样式,以使两次不使用相同的样式.
import java.awt.Color; import java.util.Random; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.text.DefaultStyledDocument; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; public class TestDifferentStyles { private void initUI() { JFrame frame = new JFrame(TestDifferentStyles.class.getSimpleName()); frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); StyledDocument doc = new DefaultStyledDocument(); JTextPane textPane = new JTextPane(doc); textPane.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has " + "been the industry's standard dummy text ever since the 1500s,when an unknown printer took a galley of " + "type and scrambled it to make a type specimen book. It has survived not only five centuries,but also the " + "leap into electronic typesetting,remaining essentially unchanged. It was popularised in the 1960s with the" + " release of Letraset sheets containing Lorem Ipsum passages,and more recently with desktop publishing " + "software like Aldus PageMaker including versions of Lorem Ipsum."); Random random = new Random(); for (int i = 0; i < textPane.getDocument().getLength(); i++) { SimpleAttributeSet set = new SimpleAttributeSet(); // StyleConstants.setBackground(set,new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256))); StyleConstants.setForeground(set,random.nextInt(256))); StyleConstants.setFontSize(set,random.nextInt(12) + 12); StyleConstants.setBold(set,random.nextBoolean()); StyleConstants.setItalic(set,random.nextBoolean()); StyleConstants.setUnderline(set,random.nextBoolean()); doc.setCharacterAttributes(i,set,true); } frame.add(new JScrollPane(textPane)); frame.setSize(500,400); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new TestDifferentStyles().initUI(); } }); } }