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

时间:2012-12-24 03:26:08

标签: java swing colors jtextpane

我尝试了很多不同的东西但我似乎无法弄清楚如何去做。我已经阅读了大约40页关于如何设置窗格中所有文本的颜色,但没有一个特定的位。我有一些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) {}
}

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

P.S。我忘了提到这是我正在制作的基于文本的游戏。在此先感谢,Braydon

CODE:

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

2 个答案:

答案 0 :(得分:3)

如果要更改文本窗格中子字符串的颜色,则需要在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) {

                }
            }
        }
    });
}
}

答案 1 :(得分:3)

作为使用HTML标记的替代方法,TextComponentDemo显示了如何应用多个StyleConstants,包括字体大小,样式,对齐方式和颜色。这些样式可以直接应用于Document,如initAttributes()所示,也可以通过StyledEditorKit的操作应用here