【发布时间】: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 方法。你能解释一下吗?