简体   繁体   English

借助 html 在 java 中创建多色 JLabel

[英]Creating a multi-colored JLabel in java with the help of html

I am trying to change the color of a part of my JLabel to a specific color.I am trying to make it so that "Blue Wins" in Blue Wins: 0 becomes the color blue, I know that I should use html function and that the function should look something like this new JLabel("<html>Blue Wins: 0 <font color='Blue Wins'>blue</font></html>"));我正在尝试将我的 JLabel 的一部分的颜色更改为特定颜色。我正在尝试使 Blue Wins: 0 中的“Blue Wins”变成蓝色,我知道我应该使用 html function 和function 应该看起来像这样 new JLabel("<html>Blue Wins: 0 <font color='Blue Wins'>blue</font></html>")); . . But I am not sure if that's how it should look and more importantly where I should place this function in my code ( the GUI section and not the logic section)但我不确定它是否应该是这样,更重要的是我应该在我的代码中放置这个 function 的位置(GUI 部分而不是逻辑部分)

These Two snippets of code are the ones connected to the Jlabel and the Gui part of the colors and fonts of it.这两个代码片段是连接到 Jlabel 和它的 colors 和 fonts 的 Gui 部分的代码片段。

JLabel infoLabel;
    JLabel XWinCounter = new JLabel("X Wins: 0");
    JLabel OWinCounter = new JLabel("O Wins: 0");
    GameLogic gameLogic;

infoLabel.setHorizontalAlignment(JLabel.CENTER);
        panel.setBorder(new LineBorder(Color.black,1));
        XWinCounter.setForeground(Color.BLUE);
        XWinCounter.setOpaque(true);
        infoPanel.add(XWinCounter);
        infoPanel.add(OWinCounter);
        infoPanel.add(infoLabel);
        getContentPane().add(infoPanel, BorderLayout.NORTH);
        getContentPane().add(panel,BorderLayout.CENTER); 

Gui Jlabel桂杰标签

This is how the GUI with the Jlabel currently looks, The whole foreground color is blue, I only want the Blue Wins: Part to be blue the: and 0 should remain the same color it is currently.这就是带有 Jlabel 的 GUI 当前的样子,整个前景色是蓝色的,我只希望 Blue Wins: Part 是蓝色的:并且 0 应该保持与当前颜色相同。

Your'e need to add the HTML on the construcror of the JLabel, like this:您需要在 JLabel 的构造器上添加 HTML,如下所示:

public class Answers {
    public static JFrame f = new JFrame("Colors");
    public static void main(String[] args) {
        JLabel XWinCounter = new JLabel("<html>X Wins: <font color='blue'>0</font></html>");
        JLabel OWinCounter = new JLabel("<html>Y Wins: <font color='red'>0</font></html>");
        f.add(OWinCounter, BorderLayout.NORTH);
        f.add(XWinCounter, BorderLayout.SOUTH);
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM