java - 使用 JTextPane 更改 setText() 方法的颜色

标签 java swing colors jtextpane

我已经尝试了很多不同的事情,但我似乎无法弄清楚该怎么做。我已经阅读了大约 40 页关于如何设置 Pane 中所有文本的颜色,但不是一个特定的位。我有一些源代码是 SSCCEE(不管它叫什么),但它没有我试过的东西,它只是显示了我想要改变颜色的东西。

tf.addActioListener() 中有一点

else {
tf.setText("> ");
tp.setText(tp.getText() + "> ERROR: Invalid Command" + newline);
try {
FileWriter fw = new FileWriter(file);
fw.write(tp.getText());
fw.close();
} catch (IOException ioe) {}
}

我想将“>错误:无效命令”的颜色更改为红色。

附言我忘了提及这是针对我正在制作的基于文本的游戏。提前致谢,布雷登

代码:

package net.GUI.frame;

import java.awt.event.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;

public class Frame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        final JTextPane tp = new JTextPane();
        final JTextField tf = new JTextField();
        JScrollPane sp = new JScrollPane();
        JPanel panel = new JPanel();
        final File file = new File("log.txt");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setSize(350,410);
        tp.setEditable(false);
        tp.setForeground(Color.blue);
        tf.setText("> ");
        sp.setViewportView(tp);
        GroupLayout jPanel2Layout = new javax.swing.GroupLayout(panel);
        panel.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addComponent(tf)
                .addComponent(sp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
            );
        jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                    .addComponent(sp, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(tf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            );
        GroupLayout layout = new javax.swing.GroupLayout(frame.getContentPane());
        frame.getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
        );
        frame.addWindowListener( new WindowAdapter() {
            public void windowOpened( WindowEvent e ){
                tf.requestFocus();
            }
        });
        /**File file10 = new File("Rooms/Room1/roomDescription.txt");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        PrintStream old = System.out;
        System.setOut(ps);

        try {
            FileReader fr = new FileReader(file10);
            int ch = fr.read();

            while(ch != -1) {
                System.out.print((char) ch);
                ch = fr.read();
            }
        } catch (Exception ex) {

        }
        System.out.flush();
        System.setOut(old);
        tp.setText(baos.toString());
        try {
            FileWriter fw = new FileWriter(file);
            fw.write(tp.getText());
            fw.close();
        } catch (IOException ioe) {

        }*/

        tp.setText("You find yourself in a blank room with a cot and a small stool. The walls are made of cold " +
                "grey concrete and have been sanded smooth. There is a solid iron door set into one of the walls." +
                " There are no windows." +
                "\nWhat do you want to do?" +
                "\n" +
                "\n");

        tf.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String newline = "\n";
                if(tf.getText().equals("> inspect cot")) {  
                    String string = tf.getText();
                    tp.setText(tp.getText()+string + newline);
                    tf.setText("> ");
                    File file1 = new File("Rooms/Room1/inspectCot.txt");
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    PrintStream ps = new PrintStream(baos);
                    PrintStream old = System.out;
                    System.setOut(ps);

                    try {
                        FileReader fr = new FileReader(file1);
                        int ch = fr.read();

                        while(ch != -1) {
                            System.out.print((char) ch);
                            ch = fr.read();
                        }
                    } catch (Exception ex) {

                    }

                    System.out.flush();
                    System.setOut(old);
                    tp.setText(tp.getText() + (baos.toString()));
                    try {
                        FileWriter fw = new FileWriter(file);
                        fw.write(tp.getText());
                        fw.close();
                    } catch (IOException ioe) {

                    }
                } else {
                    tf.setText("> ");
                    tp.setText(tp.getText() + "> ERROR: Invalid Command" + newline);
                    try {
                        FileWriter fw = new FileWriter(file);
                        fw.write(tp.getText());
                        fw.close();
                    } catch (IOException ioe) {

                    }
                }
            }
        });
    }
}

我已经使用 JTextArea 制作了这款游戏,但我想让它在美学上更令人愉悦,如果你明白我的意思吗?

这是原始游戏的链接:http://www.mediafire.com/?vp8baa2u03aafob

最佳答案

如果要更改文本 Pane 中子字符串的颜色,您需要在 HTML 中设置文本而不是普通文本。你可以这样设置:tp.setContentType ( "text/html" );并像这样使用它:tp.setText("<html>any string <font color='red'>> ERROR: Invalid Command</font></html>"); .您可以仅在字体标签中覆盖子字符串,而在简单的 html 标签中覆盖其他子字符串。

例如,您可以尝试自己的示例(但您需要在所有地方将其更改为 html):

import java.awt.event.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;

public class Test {
public static void main(String[] args) {
    JFrame frame = new JFrame();
    final JTextPane tp = new JTextPane();
    tp.setContentType ( "text/html" );
    final JTextField tf = new JTextField();
    JScrollPane sp = new JScrollPane();
    JPanel panel = new JPanel();
    final File file = new File("log.txt");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setSize(350,410);
    tp.setEditable(false);
    tp.setForeground(Color.blue);
    tf.setText("> ");
    sp.setViewportView(tp);
    GroupLayout jPanel2Layout = new javax.swing.GroupLayout(panel);
    panel.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addComponent(tf)
            .addComponent(sp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
        );
    jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addComponent(sp, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    GroupLayout layout = new javax.swing.GroupLayout(frame.getContentPane());
    frame.getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
    layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
    );
    frame.addWindowListener( new WindowAdapter() {
        public void windowOpened( WindowEvent e ){
            tf.requestFocus();
        }
    });
    /**File file10 = new File("Rooms/Room1/roomDescription.txt");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    PrintStream old = System.out;
    System.setOut(ps);

    try {
        FileReader fr = new FileReader(file10);
        int ch = fr.read();

        while(ch != -1) {
            System.out.print((char) ch);
            ch = fr.read();
        }
    } catch (Exception ex) {

    }
    System.out.flush();
    System.setOut(old);
    tp.setText(baos.toString());
    try {
        FileWriter fw = new FileWriter(file);
        fw.write(tp.getText());
        fw.close();
    } catch (IOException ioe) {

    }*/

    tp.setText("You find yourself in a blank room with a cot and a small stool. The walls are made of cold " +
            "grey concrete and have been sanded smooth. There is a solid iron door set into one of the walls." +
            " There are no windows." +
            "\nWhat do you want to do?" +
            "\n" +
            "\n");

    tf.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String newline = "\n";
            if(tf.getText().equals("> inspect cot")) {  
                String string = tf.getText();
                tp.setText(tp.getText()+string + newline);
                tf.setText("> ");
                File file1 = new File("Rooms/Room1/inspectCot.txt");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(baos);
                PrintStream old = System.out;
                System.setOut(ps);

                try {
                    FileReader fr = new FileReader(file1);
                    int ch = fr.read();

                    while(ch != -1) {
                        System.out.print((char) ch);
                        ch = fr.read();
                    }
                } catch (Exception ex) {

                }

                System.out.flush();
                System.setOut(old);
                tp.setText(tp.getText() + (baos.toString()));
                try {
                    FileWriter fw = new FileWriter(file);
                    fw.write(tp.getText());
                    fw.close();
                } catch (IOException ioe) {

                }
            } else {
                tf.setText("> ");
                tp.setText("<html>any string <font color='red'>> ERROR: Invalid Command</font></html>" + newline);
                try {
                    FileWriter fw = new FileWriter(file);
                    fw.write(tp.getText());
                    fw.close();
                } catch (IOException ioe) {

                }
            }
        }
    });
}
}

关于java - 使用 JTextPane 更改 setText() 方法的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14016712/

相关文章:

java - 向 JList 添加滚动条?

matlab - 绘制带有插值颜色的二维矩形

android - 找到三种颜色之间的比例

python - 如何从字符串中删除所有 IRC 颜色代码

java - getView() 从未在自定义适配器上调用过

java - 使用 JList 显示 TreeMap 对象

java - 如何在 jtabbedpane 中为选项卡标题设置字体

java - 抛出 javax.validation.UnexpectedTypeException : HV000030 exception when validating Scala's Map with @NotEmpty

java - 将其他两个之间的单词作为正则表达式排除

java - 将长日期解析为月-日-年字符串的快速方法