将组件插入JTextPane组件的Java程序

Java program to insert a component into a JTextPane component

假设以下是我们的JTextPane-

1
2
3
JTextPane textPane = new JTextPane();
textPane.setForeground(Color.white);
textPane.setBackground(Color.blue);

现在,设置样式和属性。 另外,设置字体-

1
2
3
4
5
6
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet, true);
textPane.setCharacterAttributes(attributeSet, true);
textPane.setText("Press the Button");
Font font = new Font("Verdana", Font.BOLD, 22);
textPane.setFont(font);

在上面显示的文本之后,我们将使用setComponent()插入一个组件-

1
2
3
4
StyledDocument doc = (StyledDocument) textPane.getDocument();
Style style = doc.addStyle("StyleName", null);
StyleConstants.setComponent(style, new JButton("Submit"));
doc.insertString(doc.getLength(),"invisible text", style);

以下是将组件插入组件的示例。 在这里,我们在JTextPane中设置了一个按钮组件-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class SwingDemo {
 public static void main(String args[]) throws BadLocationException {
   JFrame frame = new JFrame("Demo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container container = frame.getContentPane();
   JTextPane textPane = new JTextPane();
   textPane.setForeground(Color.white);
   textPane.setBackground(Color.blue);
   SimpleAttributeSet attributeSet = new SimpleAttributeSet();
   StyleConstants.setItalic(attributeSet, true);
   textPane.setCharacterAttributes(attributeSet, true);
   textPane.setText("Press the Button");
   Font font = new Font("Verdana", Font.BOLD, 22);
   textPane.setFont(font);
   StyledDocument doc = (StyledDocument) textPane.getDocument();
   Style style = doc.addStyle("StyleName", null);
   StyleConstants.setComponent(style, new JButton("Submit"));
   doc.insertString(doc.getLength(),"invisible text", style);
   JScrollPane scrollPane = new JScrollPane(textPane);
   scrollPane = new JScrollPane(textPane);
   container.add(scrollPane, BorderLayout.CENTER);
   frame.setSize(550, 300);
   frame.setVisible(true);
 }
}

输出量