java jlabel背景透明,为所有JLabel设置背景/不透明

See my code:

package hsleiden.webcat.exercise12_08;

import java.awt.*;

import javax.swing.*;

import javax.swing.border.Border;

public class newFrame extends JFrame {

public static void main(String[] args){

newFrame frame = new newFrame();

frame.setLayout(new GridLayout(2,3));

frame.setSize(200, 200);

frame.setTitle("Opdracht 12.8");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

public newFrame(){

JLabel label1 = new JLabel("Black", JLabel.CENTER);

JLabel label2 = new JLabel("Blue", JLabel.CENTER);

JLabel label3 = new JLabel("Cyan", JLabel.CENTER);

JLabel label4 = new JLabel("Green", JLabel.CENTER);

JLabel label5 = new JLabel("Magenta", JLabel.CENTER);

JLabel label6 = new JLabel("Orange", JLabel.CENTER);

Border border = BorderFactory.createLineBorder(Color.YELLOW);

label1.setBackground(Color.WHITE);

label2.setBackground(Color.WHITE);

label3.setBackground(Color.WHITE);

label4.setBackground(Color.WHITE);

label5.setBackground(Color.WHITE);

label6.setBackground(Color.WHITE);

label1.setForeground(Color.BLACK);

label2.setForeground(Color.BLUE);

label3.setForeground(Color.CYAN);

label4.setForeground(Color.GREEN);

label5.setForeground(Color.MAGENTA);

label6.setForeground(Color.ORANGE);

label1.setBorder(border);

label2.setBorder(border);

label3.setBorder(border);

label4.setBorder(border);

label5.setBorder(border);

label6.setBorder(border);

label1.setOpaque(true);

label2.setOpaque(true);

label3.setOpaque(true);

label4.setOpaque(true);

label5.setOpaque(true);

label6.setOpaque(true);

add(label1);

add(label2);

add(label3);

add(label4);

add(label5);

add(label6);

}

}

As you can see its very troublesome to apply background, border, opaque per label.. thats 18 lines for 1 and the same thing. I was wondering if someone could tell me how I can apply all the things (background, opaque, border) to all labels without having to do it per label. Since they are all the same(except foreground).

Hope someone has a solution for me.

Thanks!

解决方案

You can create your own class that extends JLabel and implements Clonable. You can override the clone method and create as many copies of a JLabel as you want.

Spring provides a handy way of doing this with BeanUtils.copyProperties

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值