1

I have tried alot of different things yet i can't seem to figure out how to do it. I have read about 40 pages on how to set the color of ALL the text in the pane, but not one specific bit. I have some source code that is an SSCCEE(whatever it is called) but it does not have what i have tried, it just shows what i want to have the color changed.

In the tf.addActioListener() there is a bit that has

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) {}
}

I want the color of "> ERROR: Invalid Command" to be changed to red.

P.S. I forgot to mention this is for the Text-Based game i am making. Thanks in advance, 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) {

                    }
                }
            }
        });
    }
}

I have already made the game using JTextArea but would like to make it a bit more aesthetically pleasing, if you know what i mean?

here is a link to the original game: http://www.mediafire.com/?vp8baa2u03aafob

2 Answers2

3

If you want to change the color for a substring in text pane, you need to set text in HTML rather than normal text. You can set it like: tp.setContentType ( "text/html" ); and use it like : tp.setText("<html>any string <font color='red'>> ERROR: Invalid Command</font></html>");. You can cover substring in font tag only and other within simple html tags.

Just for example you can try your own example (but you need to change it to html at all places):

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) {

                }
            }
        }
    });
}
}
vishal_aim
  • 7,636
  • 1
  • 20
  • 23
  • So anything that i want in a different color i have to make HTML? – CasePenguin Dec 24 '12 at 04:08
  • JUST the text i want to change color? or any text in general? – CasePenguin Dec 24 '12 at 04:10
  • you have to write in html all text I think, and I think it's just easy you can just enclose your text in html tags even if you do not intend to change color. You need to check for confirmation though – vishal_aim Dec 24 '12 at 04:15
  • Well i just tested it and it didn't work... It didn't come up saying "> ERROR: Invalid Command" and it didn't read the file into the TextPane... :( WHAT DO I DO????? – CasePenguin Dec 24 '12 at 04:16
  • Yep. I will thats for sure – CasePenguin Dec 24 '12 at 04:34
  • Im actually thinking of removing the file reading bit and just putting the text in the code... – CasePenguin Dec 24 '12 at 04:35
  • try: `tp.setText("" + tp.getText().replace("", "").replace("", "").replace("", "").replace("", "") + "
    > ERROR: Invalid Command");`, This is very crude example but I think enough for you to get the idea. You need to manage html tags in better way
    – vishal_aim Dec 24 '12 at 04:42
  • THANKS A MILLION!!! it works perfectly. I had to make a few extra adjustments but it works how i want it to now. – CasePenguin Dec 24 '12 at 04:50
  • you can use `tp.getText().replaceAll("|||", "")` or even better regex to remove existing tags while reusing the text, or store the string without tags elsewhere and reuse it... – vishal_aim Dec 24 '12 at 04:51
  • wait, say what? and how do you use this new bit of code? where does the text you want go? – CasePenguin Dec 24 '12 at 04:54
  • `tp.setText("" + tp.getText().replaceAll("|||", "") + "
    > ERROR: Invalid Command");`
    – vishal_aim Dec 24 '12 at 04:56
  • i compiled and ran the code and it works, but it gave this error: – CasePenguin Dec 24 '12 at 05:00
  • @CasePenguin: HTML markup is _permitted_ but not _required_. Some alternatives are mentioned [here](http://stackoverflow.com/a/14017588/230513). – trashgod Dec 24 '12 at 06:51
3

As an alternative to using HTML markup, TextComponentDemo shows how to apply a number of StyleConstants, including font size, style, alignment and color. The styles may applied either directly to the Document, as shown in initAttributes(), or via the actions of StyledEditorKit, also seen here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045