所以我创建了一个简单的JFrame并添加了一个JTextPane来创建一个sorta控制台..
我的类中有以下方法和变量,它们应该改变JTextPane中文本的颜色。
private static final Object CurrentConsoleAttributes[] = new Object[4];
private static final SimpleAttributeSet ConsoleAttributes = new SimpleAttributeSet();
public Object[] getConsoleAttributes() {
CurrentConsoleAttributes[0] = StyleConstants.getForeground(ConsoleAttributes);
CurrentConsoleAttributes[1] = StyleConstants.getBackground(ConsoleAttributes);
CurrentConsoleAttributes[2] = StyleConstants.isBold(ConsoleAttributes);
CurrentConsoleAttributes[3] = StyleConstants.isItalic(ConsoleAttributes);
return CurrentConsoleAttributes;
}
public void setConsoleAttributes(Color Foreground, Color Background, boolean Bold, boolean Italics) {
synchronized(ConsoleAttributes) {
StyleConstants.setForeground(ConsoleAttributes, Foreground);
StyleConstants.setBackground(ConsoleAttributes, Background);
StyleConstants.setBold(ConsoleAttributes, Bold);
StyleConstants.setItalic(ConsoleAttributes, Italics);
}
}
private void setOutputAreaText(final String Text) {
SwingUtilities.invokeLater(new Runnable() { //I read that I need to use this when dealing with swing and JTextPane is a swing component.
@Override
public void run() {
try {
StyledDocument Document = Frame.this.OutputArea.getStyledDocument();
Document.insertString(Document.getLength(), Text, ConsoleAttributes);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
});
}
public void WriteLine(Object Value) {
try {
System.out.print("Hey");
setConsoleAttributes(java.awt.Color.red, Color.white, true, false);
System.out.print("Testing");
setConsoleAttributes(java.awt.Color.blue, Color.white, true, false);
System.out.println("Printing");
} catch (Exception Ex) {
Ex.printStackTrace();
}
}
但是,当我调用WriteLine时,整行都是用蓝色或最后使用的颜色写的。我缺少什么想法?