简体   繁体   English

在Java中单击JLabel时如何更改JLabel背景

[英]How to change JLabel background when I click the JLabel in Java

I want to change my JLabel background to blue using mouseClicked. 我想使用mouseClicked将JLabel背景更改为蓝色。 The name of my JLabel is lblKembali. 我的JLabel的名称是lblKembali。 I tried this code and when I tried to click the label it didnt change the background. 我尝试了这段代码,当我尝试单击标签时,它没有更改背景。 Please help. 请帮忙。 Thank you. 谢谢。

lblKembali = new JLabel("Kembali");
lblKembali.setPreferredSize(new Dimension(400,30));
lblKembali.setMaximumSize(getPreferredSize());    
lblKembali.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                    lblKembali.setBackground(Color.BLUE);
            }
        });

By default a JLabel is non-opaque so its background is not painted. 默认情况下,JLabel是不透明的,因此不会绘制其背景。 You need to make the label opaque when you create it: 创建标签时,需要使标签不透明:

lblKembali = new JLabel("Kembali");
lblKembali.setOpaque( true );

Also you can make your listener more generic so it can be shared by multiple components by doing: 另外,您还可以使您的侦听器更通用,以便可以通过以下方式由多个组件共享:

public void mouseClicked(MouseEvent e) 
{
    Component c = e.getComponent();
    c.setBackground(Color.BLUE);
}

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

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