【问题标题】:How does the opaque property work in Swing?不透明属性在 Swing 中是如何工作的?
【发布时间】:2014-10-04 00:29:28
【问题描述】:

这是我从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 中是如何工作的吗?

抱歉,我的问题有点幼稚,但这已经困扰了我一段时间!

【问题讨论】:

  • 你知道“阿尔法”吗?
  • 我知道 alpha 值是什么意思。但这与我的问题有什么关系?
  • so alpha 可以用来控制java中任何组件的不透明度
  • 好的。我认为更好的问题可能是面板的涂漆顺序是什么?我在每个面板的paintComponent 方法中添加了一个打印语句,令我惊讶的是,后来添加的面板(底部面板)首先调用了它的paintComponent 方法。你能解释一下吗?

标签: java swing opacity


【解决方案1】:

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

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

【讨论】:

  • 即使我设置了布局管理器,paintComponent 方法仍会以相反的顺序调用。
  • 布局定位在validation(invalidate/validate),调用paintChildren方法,当然使用相同的代码。
猜你喜欢
  • 1970-01-01
  • 2015-05-11
  • 2020-07-07
  • 2011-04-13
  • 2012-02-11
  • 2011-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多