java中setOpaque()用法

本文详细介绍了Java组件的setOpaque()方法的用途和工作原理,通过创建两个面板来演示设置为true和false时的差异,其中设置为false时组件背景颜色会透明显示,而设置为true时则会正常显示组件中的每个像素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是我在csdn写的第一篇博客,本人本人比较懒,即使有一些新的东西想写出来,到最后还是不了了之。这篇博客算是一个新的开始吧!


setOpaque(true/false);看看API文档是怎么说的:

“if true the component paints every pixel within its bounds. 

Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.”。

即如果设置为true的话,原样显示组件中的每个像素,也就是正常显示;这里主要讲解设置为false时。

当设置为false时,组件并未不会显示其中的某些像素,允许控件下面的像素显现出来。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package mainclass;

import java.awt.Color;
import java.awt.FlowLayout;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MainClass extends JFrame {

  public MainClass() {
    super("Opaque JPanel Demo");
    setSize(400, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

<span style="background-color: rgb(204, 204, 204);">    JPanel opaque = createNested(true);
    JPanel notOpaque = createNested(false);</span>

    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(opaque);
    getContentPane().add(notOpaque);
  }

  public static void main(String[] args) {
    MainClass oe = new MainClass();
    oe.setVisible(true);
  }

  public JPanel createNested(boolean opaque) {
    JPanel outer = new JPanel(new FlowLayout());
    JPanel inner = new JPanel(new FlowLayout());
<span style="background-color: rgb(192, 192, 192);">    outer.setBackground(Color.BLUE);
    inner.setBackground(Color.red);</span>

    inner.setOpaque(opaque);
    inner.setBorder(BorderFactory.createLineBorder(Color.gray));

    inner.add(new JButton("Button"));
    outer.add(inner);

    return outer;
  }
}

运行结果如图:


如图,第一个panel中inner设置setOpaque(true),则inner区域中的背景色红色就会遮挡住外层组件中的蓝色;而在第二个panel中,由于inner设置为setOpaque(false),则inner区域中的背景色就是透明的了,因此就显示为外围组件outer的颜色蓝色。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值