关于Java:使用JTextPane设置代码样式

Use JTextPane to style code

如何像在论坛上经常看到的那样,或者在此处出现堆栈溢出的情况下,如何使用JTextPane将一段文字设置为" CODE "样式?

1
2
3
4
5
6
public static main(String[] args) {
    /**
     * Look at this Code Block, ain't it grand?
     * I wish I had something like this in my program.
     */

}

或者我如何看待维基百科上的文字,如下所示:
http://img39.imageshack.us/img39/4516/example.JPG

谢谢!

最终更新
Vishal K \\的答案正是我所需要的。并非如建议那样重复。

更新
感谢您的答复。我正在寻找的内容与上面建议的可能答案之间的区别是,我不仅对更改字体感兴趣,而且还对添加背景感兴趣(在该背景周围的边框是一个加号,但不是必需的。)我认为HTML标记可能是解决问题的方法,如果是这样,这的确是个问题:如何使用html来格式化代码?在答案中,让您知道。
P.s.在问这个问题之前,我已经阅读了指向Oracle教程的链接。


How can I use JTextPane to style a section of text as"CODE," like you
often see on forums, or you see here on stack overflow?

使用HTML标记。但是在此之前,您必须将contentType设置为(" text / html ")。
这是一个简单的例子:
enter

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
import java.awt.BorderLayout;
import java.awt.Container;

import javax.swing.JTextPane;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class TextPaneDemo {
  static void addIt(JTabbedPane tabbedPane, String text) {
    JPanel panel = new JPanel();
    JTextPane ta = new JTextPane();
    ta.setContentType("text/html");
    ta.setText("<HTML><BODY><wyn> import java.io.*;  public class MyIO{}</wyn></BODY></HTML>");
    JScrollPane jsp = new JScrollPane(ta);
    panel.setLayout(new BorderLayout());
    panel.add(jsp);
    tabbedPane.addTab(text, panel);
  }

  public static void main(String args[]) {
    JFrame f = new JFrame("JTabbedPane Sample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = f.getContentPane();
    JTabbedPane tabbedPane = new JTabbedPane();
    addIt(tabbedPane,"Tab One");
    content.add(tabbedPane, BorderLayout.CENTER);
    f.setSize(300, 200);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}