我有一个Graphics2D
对象,想要设置该对象的背景。该对象有一个setBackground
方法,需要传入一个Color参数来设置背景颜色。
我的问题是:如何设置对象背景的透明度?我能否将其完全透明?我能否将其完全不透明?我能否将其透明度设置为0.8?我如何设置这些值?
我看到有一些预定义的int值称为TRANSLUCENT
和OPAQUE
,但我不确定如何使用它们。
也许正确的用法是使用带有int参数的Color构造函数吗?
我有一个Graphics2D
对象,想要设置该对象的背景。该对象有一个setBackground
方法,需要传入一个Color参数来设置背景颜色。
我的问题是:如何设置对象背景的透明度?我能否将其完全透明?我能否将其完全不透明?我能否将其透明度设置为0.8?我如何设置这些值?
我看到有一些预定义的int值称为TRANSLUCENT
和OPAQUE
,但我不确定如何使用它们。
也许正确的用法是使用带有int参数的Color构造函数吗?
Color c=new Color(1f,0f,0f,.5f );
#setColor()
+ #fillRect()
,对吗? - CampasetBackground
方法与setColor
方法类似,只设置画笔的颜色。如果要用背景色填充整个画布,请使用clear
。 - wcharginColor c = new Color(r,g,b,a);
其中a代表透明度。
与所有Java类一样,您可以在官方API中找到此信息:http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html
这是一个非常好的资源,可以避免您在这里等待答案。
jPanel1.setBackground(new Color(0,0,0,200));
/*This will put a transparent black color on a panel, the important part of the code is: .setBackground(new Color(0,0,0,200));*/
Java在这方面表现得非常出色,您可以实现透明度和更多功能。以下是我从Oracle 复制的简单透明窗口代码:
package misc;
import java.awt.*;
import javax.swing.*;
import static java.awt.GraphicsDevice.WindowTranslucency.*;
public class TranslucentWindowDemo extends JFrame {
public TranslucentWindowDemo() {
super("TranslucentWindow");
setLayout(new GridBagLayout());
setSize(300,200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add a sample button.
add(new JButton("I am a Button"));
}
public static void main(String[] args) {
// Determine if the GraphicsDevice supports translucency.
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
//If translucent windows aren't supported, exit.
if (!gd.isWindowTranslucencySupported(TRANSLUCENT)) {
System.err.println(
"Translucency is not supported");
System.exit(0);
}
JFrame.setDefaultLookAndFeelDecorated(true);
// Create the GUI on the event-dispatching thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TranslucentWindowDemo tw = new TranslucentWindowDemo();
// Set the window to 55% opaque (45% translucent).
tw.setOpacity(0.55f);
// Display the window.
tw.setVisible(true);
}
});
}
}
查看这里获取更多信息。
如果您想要实现透明效果,请使用颜色属性设置4个变量:
this.setBackground(new Color(0, 0, 0, .5f));
这将为背景设置RGB颜色的前三个参数(*new Color(** 0,0,0,** .5f)*),第四个参数用于确定不透明度的百分比(opaque)。
如果您希望背景不显示,请使用值null
this.setBackground(null);
许多人使用setOpaque(false);但这会去除填充而不是背景。
Color color = new Color(152,251,152, 50);
数值50表示透明度。