简体   繁体   中英

How to use setOpaque(true/false) in an if statement

My JLabel won't change to a blue background. The JLabel is already set to the blue background but it is not opaque until you press the button. Why is it still not opaque? Does setOpaque work for if statements?

import java.awt.Color;
import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;

import java.awt.event.*;

public class TestOpaque {

public static void main (String args[])
{
    JFrame frame = new JFrame();
    frame.setLayout(new BorderLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JLabel label = new JLabel("Label with blue background");
    label.setBackground(Color.BLUE);
    label.setOpaque(false);
    frame.add(label, BorderLayout.WEST);
    
    JButton button = new JButton("Button");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e)
        {
            if (label.isOpaque() == false) {
            label.setOpaque(true);
            label.revalidate();
            }
        }
    });
    frame.add(button, BorderLayout.EAST);
    
    frame.pack();
    frame.setVisible(true);
}
}

The if statement works fine, although better to use if (.label.isOpaque()) {

You need to redraw the GUI component via repaint() for the background to show:

    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!label.isOpaque()) {
                label.setOpaque(true);
                label.revalidate();
                label.repaint();
            }
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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