有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java不透明属性在Swing中如何工作?

这是我从这里得到的一个简单的应用程序this answer How to set a Transparent Background of JPanel 这应该可以解释setOpaque()是如何工作的

public class TwoPanels {
public static void main(String[] args) {

    JPanel p = new JPanel();
    // setting layout to null so we can make panels overlap
    p.setLayout(null);

    CirclePanel topPanel = new CirclePanel();
    // drawing should be in blue
    topPanel.setForeground(Color.blue);
    // background should be black, except it's not opaque, so 
    // background will not be drawn
    topPanel.setBackground(Color.black);
    // set opaque to false - background not drawn
    topPanel.setOpaque(false);
    topPanel.setBounds(50, 50, 100, 100);
    // add topPanel - components paint in order added, 
    // so add topPanel first
     p.add(topPanel);

    CirclePanel bottomPanel = new CirclePanel();
    // drawing in green
    bottomPanel.setForeground(Color.green);
    // background in cyan
    bottomPanel.setBackground(Color.cyan);
    // and it will show this time, because opaque is true
    bottomPanel.setOpaque(true);
    bottomPanel.setBounds(30, 30, 100, 100);
    // add bottomPanel last...
    p.add(bottomPanel);

    // frame handling code...
    JFrame f = new JFrame("Two Panels");
    f.setContentPane(p);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(300, 300);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
}

// Panel with a circle drawn on it.
private static class CirclePanel extends JPanel {

    // This is Swing, so override paint*Component* - not paint
    protected void paintComponent(Graphics g) {
        // call super.paintComponent to get default Swing 
        // painting behavior (opaque honored, etc.)
        super.paintComponent(g);
        int x = 10;
        int y = 10;
        int width = getWidth() - 20;
        int height = getHeight() - 20;
        g.fillArc(x, y, width, height, 0, 360);
    }
}
}

我不明白的是,他为什么要在透明层上加不透明层?不应该反过来吗

我想象它应该如何工作的方式是在不透明层的顶部添加透明层,有点像在手机上放置屏幕保护器(很抱歉这个愚蠢的例子)

有人能解释一下透明性在java中是如何工作的吗

很抱歉,我的问题有点天真,但这已经困扰了我一段时间了


共 (1) 个答案

  1. # 1 楼答案

    是的,这个例子基于这样一个事实:使用null布局时,子组件确实是按相反的顺序绘制的。实现依赖关系。这至少值得一提。添加可见边框将使其更加明显:

    private static class CirclePanel extends JPanel {
        CirclePanel() {
            setBorder(BorderFactory.createLineBorder(Color.RED));
        }