开发者

Easy multicolored text in Java

After writing a console application (For mundane I/O tasks not worth mentioning here), I decided I needed to make the text multicolored for 开发者_StackOverflow社区readability. I would've liked to keep it in a command prompt, being inexperienced with Swing, but as far as I could figure there was no way to do that, I looked around the Swing API and can't find anything.

Ideally, I'd be able to use something like

for(int i=0; i<aString.length(); i++){
    if(aString.charAt(i) == '?'){
        String pre = aString.substring(0,i);
        String post = aString.substring(i);
        aString = pre + red("?") + post;    //As you can see by red("?"), I have no idea what I'm doing
    }
}

so that I could just loop through the text I would have previously printed, insert the coloring information, and display it.

Can anyone point me in the right direction? Method, class, snippet, anything?


You can output your string in html format adding tag where coloring is expected. Then assign the HTML to JLabel or JTextPane.


I would've liked to keep it in a command prompt, being inexperienced with Swing

You might get some ideas from Message Console.

Easy multicolored text in Java


Refer the swing api

Link is a small example to use all the functionalities available in JLabel including the color of text in it.

If you want to just display text in different colors then:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class MainClass extends JPanel {

  public void paint(Graphics g) {
    Dimension d = this.getPreferredSize();
    int fontSize = 20;

    g.setFont(new Font("TimesRoman", Font.PLAIN, fontSize));

    g.setColor(Color.red);

    g.drawString("Hello 1", 10, 20);

    g.setColor(Color.black);

    g.drawString("Hello 2", 30, 50);
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.getContentPane().add(new MainClass());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200,200);
    frame.setVisible(true);
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜