为所有JLabel设置背景/不透明 [英] Set background/opaque to all JLabels

查看:341
本文介绍了为所有JLabel设置背景/不透明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看我的代码:

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);

    }
}

正如您所看到的,为每个标签应用背景,边框,不透明是非常麻烦的.多数民众赞成在18行1和同一件事.我想知道是否有人可以告诉我如何将所有内容(背景,不透明,边框)应用于所有标签,而不必按标签进行操作.因为它们都是相同的(前景除外).

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.

谢谢!

推荐答案

  1. 您可以创建自己的类,该类扩展JLabel并实现Clonable.您可以覆盖clone方法,并根据需要创建任意数量的JLabel副本.
  2. Spring通过BeanUtils.copyProperties提供了一种方便的方法

这篇关于为所有JLabel设置背景/不透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆