public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2=(Graphics2D)g;
LinearGradientPaint p=new LinearGradientPaint(0,0,0,height,new float[]{0f,1f},new Color[]{new Color(0.2498f,0.2498f,0.2498f,0.3f),new Color(0.1598f,0.1598f,0.1598f,0.8f)});
g2.setPaint(p);
g2.fillRect(0, 0, width,height);
}
当您使用函数进行绘制时,您是在绘制子组件之后paint()
使用图形实例进行绘制。转到函数的源代码,您将看到正在调用三个后续函数:g
panel
super.paint(g)
protected void paintComponent(Graphics g)
:这个画你的组件,例如:背景
protected void paintBorder(Graphics g)
:这个绘制组件的边框
protected void paintChildren(Graphics g)
:这个在其中绘制组件的子项
因此,在此super.paint(g)
调用之后,您绘制的任何内容都将出现在使用上述三个函数制作的所有绘画之上:因此在子组件之上,对于您的上下文,panel
具有蓝色背景。
现在,一个解决方案是:
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g.create();
// note, we are creating a graphics object here for safe painting
LinearGradientPaint p=new LinearGradientPaint(0,0,0,height,new float[]{0f,1f},new Color[]{new Color(0.2498f,0.2498f,0.2498f,0.3f),new Color(0.1598f,0.1598f,0.1598f,0.8f)});
g2.setPaint(p);
g2.fillRect(0, 0, width,height);
g2.dispose(); // disposing the object which we created
super.paint(g);
}
但是,您不是这样做,而是使用一个类,例如MyCanvas extends JComponent
并覆盖它的paintComponent(Graphics)
函数并在其中绘制。然后你可以设置一个实例MyCanvas
作为JFrame
使用它的setContentPane(component)
功能的内容窗格。
查看A Closer Look at the Paint Mechanism
编辑您的用例的一个小演示实现:
class AMyContainer extends JComponent
{
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g.create();
// note, we are creating a graphics object here for safe painting
LinearGradientPaint p=new LinearGradientPaint(0, 0, 0, getHeight(),new float[]{0f,1f},new Color[]{new Color(0.2498f,0.2498f,0.2498f,0.3f),new Color(0.1598f,0.1598f,0.1598f,0.8f)});
g2.setPaint(p);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose(); // disposing the object which we created
}
}
class Home extends JFrame
{
int width=GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
int height=GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
public Home()
{
super("WiND");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setUndecorated(true);
setSize(width,height);
setBackground(new Color(0,0,0,0));
setUndecorated(true);
JComponent container = new AMyContainer();
container.setLayout(new FlowLayout());
add(container);
JPanel p=new JPanel();
p.setBackground(new Color(0x0D70E8));
p.setPreferredSize(new Dimension(width,height/10));
container.add(p);
}
public static void main(String[] args)
{
new Home().setVisible(true);
}
}