formatting text in jdialog box

ε祈祈猫儿з 提交于 2019-11-26 14:40:10

问题


I have a JOptionPane:

JOptionPane.showMessageDialog(null, text);

The text is a sting:

String text = "Hello world."

What I want to do is change the color of the text, specifically a single word, lets say 'Hello'. SO what I've tried is:

String t1 = "Hello";
String t2 = "world."
Font serifFont = new Font("Serif", Font.BOLD, 12);
AttributedString as = new AttributedString(t1);
as.addAttribute(TextAttribute.FONT, serifFont); 
as.addAttribute(TextAttribute.FOREGROUND, Color.red);


JOptionPane.showMessageDialog(null, as+t2);

I'm not familiar with attributedtext() and this wont work. It does this:

"java.text.AttributedString@479c479cworld"

Is there a step I'm missing? Is this not the right way? Any suggestions?


回答1:


It should be possible to use html to solve this, ie

String t = "<html><font color=#ffffdd>Hello</font> world!";

See http://docs.oracle.com/javase/tutorial/uiswing/components/html.html for more info.




回答2:


You can pass a Component to JOptionPane in the message parameter and will use that to display your message.

Something like a JLabel or a JPanel with labels on it.

UPDATED

JLabel, JPanel and HTML text examples

public class TestOptionPane {

    public static void main(String[] args) {

        JLabel label = new JLabel("Hello");
        label.setForeground(Color.RED);

        JOptionPane.showMessageDialog(null, label);

        JPanel pnl = new JPanel(new GridBagLayout());
        pnl.add(createLabel("The quick"));
        pnl.add(createLabel(" brown ", Color.ORANGE));
        pnl.add(createLabel(" fox "));

        JOptionPane.showMessageDialog(null, pnl);

        String text = "<html>The Quick <span style='color:green'>brown</span> fox</html>";
        JOptionPane.showMessageDialog(null, text);

    }

    public static JLabel createLabel(String text) {

        return createLabel(text, UIManager.getColor("Label.foreground"));

    }

    public static JLabel createLabel(String text, Color color) {

        JLabel label = new JLabel(text);
        label.setForeground(color);

        return label;

    }

}

On the Mac-

On Windows -



来源:https://stackoverflow.com/questions/12008100/formatting-text-in-jdialog-box

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!