我正在創建支持透明度的JPanel
,並且遇到問題,我不確定如何將相同級別的透明度應用於添加到所有Component
的s這個面板。到目前爲止我的代碼:Java Swing - 將透明度應用到透明組件上JPanel
package de.uebertreiberman.project.swing;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class JTransparancyPanel extends JPanel {
float opacity = 1.0f;
/**Constructor for JTransparentPanel
*/
public JTransparancyPanel()
{
super();
this.setOpaque(false);
}
/**Getter for opacity value of panel
*
* @return float containing opacity value of frame (0-1)
*/
public float getOpacity()
{
return opacity;
}
/**Setter for opacity value of panel
*
* @param value as float for opacity of frame (0-1)
*/
public void setOpacity(float value)
{
opacity = value;
repaint();
}
/**Converts opacity value (0-1) to opacity color (0-255)
*
* @param opacity as float opacity value (0-1)
* @return integer containing converted opacity value (0-255)
*/
public static int getOpacityColor(float opacity)
{
return (int)(opacity * 255);
}
/**Converts opacity color (0-255) to opacity value (0-1)
*
* @param opacity as integer value (0-255)
* @return float containing converted opacity value (0-1)
*/
public static float getOpacityValue(int opacity)
{
//Returns more or less the correct, capped value
//Just ignore it, it works, leave it :D
return capFloat((3.9216f*opacity)/1000f, 0.0f, 1.0f);
}
/**Returns float capped between minimum and maximum value
*
* @param value as original value
* @param min as minimum cap value
* @param max as maximum cap value
* @return float containing capped value
*/
public static float capFloat(float value, float min, float max)
{
if(value < min) value = min;
else if(value > max) value = max;
return value;
}
/**Merges color and opacity to new color
*
* @param bg as color for old color, only RGB will be used from that
* @return color with RGB from bg and A from opacity of frame
*/
Color getTransparencyColor(Color bg)
{
return new Color(getOpacityValue(bg.getRed()), getOpacityValue(bg.getGreen()), getOpacityValue(bg.getBlue()), opacity);
}
@Override
public void paintComponent(Graphics g)
{
//Draw transparent background before painting other Components
g.setColor(getTransparencyColor(getBackground()));
Rectangle r = g.getClipBounds();
g.fillRect(r.x, r.y, r.width, r.height);
//Paint other components
super.paintComponent(g);
}
}
的重要組成部分,基本上是在那裏我overwride的paintComponent(Graphics g)
方法結束。
我只需要backgroundcolor
,將透明度應用於它並進行設置。
現在我想讓這個面板的所有Component子元素都變得透明,我不太確定什麼是最有效的方法。
你會建議什麼?
這是難以在不覆蓋的各成分的'paint' /'paintComponent'方法。沒有任何東西可以阻止兒童組件以明顯不透明的顏色公然填充其區域。人們可以嘗試將子組件繪製成圖像,然後使用適當的不透明度繪製該圖像。我會試試看,但它可能有點煩瑣。 – Marco13
我還沒有嘗試,今天也沒有時間,但是你能不能只獲取組件('Component [] components = jpanel.getComponents();'),遍歷它們並使用'getGraphics() .setBackgroundColour()'? – MrB