在标签中使用多种背景颜色

时间:2012-03-06 10:32:53

标签: java eclipse swing background jlabel

我正在构建JFrame,我想在其上有3个JLabel个实例,有3种不同的颜色。

  1. WHITE
  2. RED
  3. WHITE
  4. 这是我的代码:

    package View;
    
    import java.awt.*;
    import javax.swing.*;
    
    public class Home extends JFrame {
    
        private JLabel label, label1;
        private JPanel panel;
        private Container window = getContentPane();
    
        public Home (){
            initGUI();
        }
    
        public void initGUI(){
            setLayout(null);
            setTitle("");
            setPreferredSize(new Dimension(800,600));
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            label = new JLabel();       
            label.setBounds(0, 0, 266, 800);
            label.setBackground(Color.WHITE);
            label.setOpaque(true);
            this.add(label);
    
            panel = new JPanel();
    
            pack();
        }
    }
    

    但是当我添加第二个标签时,红色必须站在白色背景旁边,白色背景会消失

1 个答案:

答案 0 :(得分:0)

使用html作为文本标签

public class test {

public static void main(String[] args) {
    String initialText = "<html>\n" +
    "Color and font test:\n" +
    "<table>"+
    "<ul>\n" +
    "<tr>"+
    "<td bgcolor=\"#C0C0C0\">"+
    "<li><font color=red>red</font>\n" +
    "</td>"+
    "</tr>"+
    "<tr>"+
    "<td bgcolor=\"#FF0000\">"+
    "<li><font color=blue>blue</font>\n" +
    "</td>"+
    "</tr>"+
    "<tr>"+
    "<td bgcolor=\"#800000\">"+
    "<li><font color=green>green</font>\n" +
    "</td>"+
    "</tr>"+
    "<tr>"+
    "<td bgcolor=\"#FFFF00\">"+
    "<li><font size=-2>small</font>\n" +
    "</td>"+
    "</tr>"+
    "<tr>"+
    "<td bgcolor=\"#808000\">"+
    "<li><font size=+2>large</font>\n" +
    "</td>"+
    "</tr>"+
    "<tr>"+
    "<td bgcolor=\"#00FFFF\">"+
    "<li><i>italic</i>\n" +
    "</td>"+
    "</tr>"+
    "<tr>"+
    "<td bgcolor=\"#008080\">"+
    "<li><b>bold</b>\n" +
    "</td>"+
    "</tr>"+
    "</ul>\n"+
    "</table>"
    ;
    JFrame f = new JFrame("This is a test");
    f.setSize(400, 150);
    Container content = f.getContentPane();
    content.setBackground(Color.white);
    content.setLayout(new FlowLayout()); 
    content.add(new JLabel(initialText));


    f.setVisible(true);
  }

}