我想在编译exec文件后以红色显示错误(文本)结果 并使用java中的swing将其显示在gui的textarea中。
答案 0 :(得分:2)
普通的JTextArea不支持不同颜色的文本等花哨的东西。但是,有类似的组件。见http://java.sun.com/docs/books/tutorial/uiswing/components/text.html
答案 1 :(得分:2)
JEditorPane可以获取以HTML格式化的内容。 official Sun tutorial也提供了一些见解:
JTextArea类提供了一个显示多行文本的组件,并可选择允许用户编辑文本。如果您只需要从用户那里获得一行输入,则应使用文本字段。如果希望文本区域使用多种字体或其他样式显示其文本,则应使用编辑器窗格或文本窗格。如果显示的文本长度有限且用户从未编辑过,请使用标签。
答案 2 :(得分:1)
以下是使用AttributeSet和StyleConstants向JEditorPane添加文本的快速示例。
这会带来一个带有JEditorPane的小框架,您可以使用它来添加大量颜色的文本而不使用HTML。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
public class TextColor extends JFrame implements ActionListener {
JTextPane myTextPane;
JTextArea inputTextArea;
public TextColor() {
super();
JPanel temp = new JPanel(new BorderLayout());
inputTextArea = new JTextArea();
JButton btn = new JButton("Add");
btn.addActionListener(this);
temp.add(btn, BorderLayout.SOUTH);
temp.add(inputTextArea, BorderLayout.NORTH);
this.getContentPane().add(temp, BorderLayout.SOUTH);
myTextPane = new JTextPane();
myTextPane.setBorder(new EtchedBorder());
this.getContentPane().add(myTextPane, BorderLayout.CENTER);
this.setSize(600, 600);
this.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
Color newTextColor = JColorChooser.showDialog(this, "Choose a Color", Color.black);
//here is where we change the colors
SimpleAttributeSet sas = new SimpleAttributeSet(myTextPane.getCharacterAttributes());
StyleConstants.setForeground(sas, newTextColor);
try {
myTextPane.getDocument().insertString(myTextPane.getDocument().getLength(),
inputTextArea.getText(), sas);
} catch (BadLocationException ble) {
ble.printStackTrace();
}
}
public static void main(String args[]) {
new TextColor();
}
}
答案 3 :(得分:0)
史密塔,
注意粘贴代码片段,以便人们可以了解问题的确切位置或需要帮助。
来你的问题,
据我所知,没有办法在java中的textArea中为不同的文本元素设置不同的颜色。您只能为所有颜色设置一种颜色。
替代方法是使用JTextPane。
查看以下代码是否有助于您的事业。
String text = "Some Text..."; //This can be any piece of string in your code like
output of your program...
JTextPane myTextPane = new JTextPane();
SimpleAttributeSet sas = new SimpleAttributeSet(myTextPane.getCharacterAttributes());
// As what error you were referring was not clear, I assume there is some code in your
program which pops out some error statement. For convenience I use Exception here..
if( text.contains("Exception") ) //Checking if your output contains Exception...
{
StyleConstants.setForeground(sas, Color.red); //Changing the color of
StyleConstants.setItalic(sas, true);
try
{
myTextPane.getDocument().insertString
(
myTextPane.getDocument().getLength(),
text + "\n",
sas
);
}
catch( BadLocationException ble )
{
text.append(ble.getMessage());
}
}
else
{
StyleConstants.setForeground(sas, Color.GREEN);
try
{
myTextPane.getDocument().insertString
(
myTextPane.getDocument().getLength(),
text + "\n",
sas
);
}
catch(BadLocationException ble)
{
text.append(ble.getMessage());
}
}
我想这可以解决您的问题,但很少有修改。
感谢。
苏希尔