gio*_*ine 1 java swing text jtextpane jeditorpane
我在任何地方都进行了搜索和研究,找到了一个没有结果的答案.所以我再次寻求帮助.
我想在桌面java swing应用程序中显示格式化文本.该文本将在一些变量对象的基础上编程生成,并且不可编辑.
我不知道是否最好使用JTextPane或JEditorPane,或者是什么.问题是我找不到任何解释如何使用它们的手册或教程.我是否必须创建HTMLDocument才能插入文本?我该如何创建它?...
在这种情况下,是显示文本的正确方法吗?或者我可以使用表格或标签或类似的东西.
我需要你的一些建议,如果有一些地方我可以学习如何去做,请告诉我.
下面看一下这个代码示例,如果你想再修改一下这个例子,可以添加Font作为参数,并在指定位置使用适当的参数.在里面JTextField写点东西并按ENTER几次.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class TextPaneTest extends JFrame {
private JPanel topPanel;
private JTextPane tPane;
private JTextField tfield;
private int counter;
private Color[] colours = {
Color.RED,
Color.BLUE,
Color.DARK_GRAY,
Color.PINK,
Color.BLACK,
Color.MAGENTA,
Color.YELLOW,
Color.ORANGE
};
public TextPaneTest() {
counter = 0;
}
private void createAndDisplayGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EmptyBorder eb = new EmptyBorder(new Insets(10, 10, 10, 10));
tPane = new JTextPane();
tPane.setBorder(eb);
tPane.setMargin(new Insets(5, 5, 5, 5));
JScrollPane scroller = new JScrollPane();
scroller.setViewportView(tPane);
tfield = new JTextField();
tfield.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
counter++;
if (counter == 8)
counter = 0;
String text = tfield.getText() + "\n";
appendToPane(tPane, text, colours[counter]);
tfield.selectAll();
}
});
getContentPane().add(scroller, BorderLayout.CENTER);
getContentPane().add(tfield, BorderLayout.PAGE_END);
setSize(200, 100);
setVisible(true);
tfield.requestFocusInWindow();
}
private void appendToPane(JTextPane tp, String msg, Color c) {
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
int len = tp.getDocument().getLength();
tp.setCaretPosition(len);
tp.setCharacterAttributes(aset, false);
tp.replaceSelection(msg);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TextPaneTest().createAndDisplayGUI();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6540 次 |
| 最近记录: |