Java Swing 设置三个颜色的标签

// 设置文本相对于图片的位置(文本默认在图片右边垂直居中)
void setHorizontalTextPosition(int textPosition)//横轴对齐方式
void setVerticalTextPosition(int textPosition)//纵轴对齐方式

// 设置标签内容(在标签内)的对其方式(默认左对齐并竖直方向垂直居中)
void setHorizontalAlignment(int alignment)//标签内容(在标签内)的横轴对齐方式
void setVerticalAlignment(int alignment)//(在标签内)的纵轴对齐方式
import javax.swing.*;
import java.awt.*;
public class Main {
    private static  class ColorfulLabel extends JLabel {
        private static final long serialVersionUID = 1L;
        ColorfulLabel(String text,Color color)
        {
            super(text);//设置标签聂荣
            setFont(new Font(null, Font.PLAIN, 20));
            setBackground(color);
            setOpaque(true);//设置为不透明
            setPreferredSize(new Dimension(100, 100));//设置标签的最佳尺寸
           setHorizontalAlignment(SwingConstants.CENTER);//标签内容(在标签内)的横轴对齐方式
setVerticalAlignment(SwingConstants.BOTTOM);//设置标签内容沿y轴的对齐方式
        }
    }
    public static void main(String[] args) throws AWTException {
        JFrame jf = new JFrame("测试窗口");
        jf.setSize(500, 300);
        jf.setLocationRelativeTo(null);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel panel = new JPanel(new FlowLayout());

        JLabel lab1 = new ColorfulLabel("1",Color.CYAN);
        JLabel lab2 = new ColorfulLabel("2",Color.YELLOW);
        JLabel lab3 = new ColorfulLabel("3",Color.ORANGE);
        panel.add(lab1);
        panel.add(lab2);
        panel.add(lab3);
        jf.setContentPane(panel);
        jf.setVisible(true);
    }  
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值