Swing 对话框渐变绘制问题

Swing Dialog gradient paint Issue

想为对话框绘制渐变背景

  1. 不要玩弄根窗格或分层窗格。

  2. 不要覆盖 JFrame 或 JDialog 上的 paint()。

如果您想为背景做自定义绘画,那么您可以覆盖 JPanel 的 paintComponent(...) 方法。然后将此面板设置为对话框的内容面板。

阅读 Swing 教程中关于 Custom Painting 的部分以获取工作示例以帮助您入门。

此外,Swing 不能正确支持透明背景。

绘制透明背景的基本逻辑是:

JPanel panel = new JPanel()
{
    protected void paintComponent(Graphics g)
    {
        g.setColor( getBackground() );
        g.fillRect(0, 0, getWidth(), getHeight());
        super.paintComponent(g);
    }
};
panel.setOpaque(false); // background of parent will be painted first
panel.setBackground( new Color(255, 0, 0, 20) );
frame.add(panel);

查看 Background With Transparency 了解更多信息。

所以首先使用非透明颜色在自定义面板上进行渐变绘画。一旦您了解了进行自定义绘画的正确方法,您就可以担心透明度了。