setOpaque()方法

fir*_*ruq 4 java

我想知道setOpaque()方法做什么...

这是小程序的一部分:

    public class Buttons extends JFrame implements ActionListener
    {

     private JButton button;
     private JLabel label;
     private JTextArea text;
     private String t;
     public Buttons()
     {
      super("TESTING");
      label = new JLabel("Hello!!!!");
      button = new JButton("Color Change");
      text = new JTextArea("Test");
      setLayout(new FlowLayout());
      label.setOpaque(true);
      add(button);
      add(label);
      add(text);

            LabelHandler labelHandler = new LabelHandler();

      button.addActionListener(this);
            label.addMouseListener(labelHandler);

      setSize(300,200);
      setVisible(true);
     }

     public void actionPerformed(ActionEvent e)
     {
      if (e.getSource()==button)
      {
       label.setBackground(Color.red);
      }
      if (e.getSource()==text)
      {
       if (t == "\n")
       {
        setText(t);
        label.getText();
       }
      }
     }



    class LabelHandler extends MouseAdapter
    {
     public void mouseEntered(MouseEvent e)
     {
  label.setBackground(Color.GREEN);
     }
 }
Run Code Online (Sandbox Code Playgroud)

如果没有setOpaque,它就不会绘制标签.为什么?提前致谢.

akf*_*akf 6

Swing使用opaque标志ComponentUI来测试它们是否应该绘制背景或是否应该绘制背景.如果您设置了背景颜色但没有设置setOpaque(true),则不会看到bg颜色.