0

我试图有一个图像背景,所以我在 JFrame 中创建了以下代码:

@Override
public void paint(Graphics g) {
    super.paint(g);
    try {
        final Image image = ImageIO.read(getClass().getResource("/images/login/gentlenoise100.png"));
        int iw = 256;
        int ih = 256;
        for (int x = 0; x < getWidth(); x += iw) {
            for (int y = 0; y < getHeight(); y += ih) {
                g.drawImage(image, x, y, iw, ih, this);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
    }
    for(Component componente:getComponents()){
        componente.repaint();
    }

}

我看到背景颜色有某种偏好,我决定将其设置为不可见:

setBackground(new java.awt.Color(0,0,0,0));

它在 Mac OS X (java 1.6) 中运行良好,我不得不在 Windows 中对其进行探测,如果我删除 setBackground 调用,它不会显示我的背景,如果我保持背景颜色不可见,它会引发异常并说框架装饰!

我尝试使用setUndecorate(true),但在 macOS 中它丢失了标题栏(当然),在 Windows 中它给了我一个透明窗口。

我该如何解决?

4

2 回答 2

1

如果可以避免,请不要覆盖paint顶级容器(如JFrame)的方法,它们会做很多重要的事情。

在这种情况下,您最好使用 aJPanel并将框架内容窗格设置为它...

就像是...

public class BackgroundPane extends JPanel {

    private Image background;
    public BackgroundPane() {
        try {
            background = ImageIO.read(getClass().getResource("/images/login/gentlenoise100.png"));
        } catch (IOException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int iw = 256;
        int ih = 256;
        for (int x = 0; x < getWidth(); x += iw) {
            for (int y = 0; y < getHeight(); y += ih) {
                g.drawImage(background, x, y, iw, ih, this);
            }
        }
    }
}

//...

JFrame frame = new JFrame();
frame.setContentPane(new BackgroundPane());
//...

不要在您的绘制方法中做任何耗时或可能导致重绘管理器安排您的组件再次重​​绘的事情

像...

final Image image = ImageIO.read(getClass().getResource("/images/login/gentlenoise100.png"));

for(Component componente:getComponents()){
    componente.repaint();
}

在里面你是油漆方法是一个非常糟糕的主意。

第二个可能导致重绘管理器决定父容器(您的框架)需要一遍又一遍地重绘......最终消耗你的CPU......

请注意,从 Java 7 开始,setBackground使用包含小于 255 的 alpha 值的颜色调用Window会导致窗口变得透明。

Window.setBackground(Color) 将 new Color(0,0,0,alpha) 传递给此方法,其中 alpha 小于 255,安装每像素半透明

如果窗口被装饰,这也会抛出异常......

于 2012-10-05T11:44:00.943 回答
1

有三种方式,使用

  1. JComponent#setOpaque()如果您不想喘气背景

  2. 如何在 Win、OSX 上创建半透明和异形 Windows 一些 *** unix

  3. 透明度必须更改 AlphaComposite 的


不要paint()随便JFrame,放在那里JPanel并覆盖paintComponent()

于 2012-10-05T11:34:19.273 回答