java 如何在 JDesktopPane 中设置背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15681984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:29:38  来源:igfitidea点击:

How to set Background image in JDesktopPane

javaswingbackgroundjdesktoppane

提问by Majda

I want to set the background of the JDesktopPane (I add this JDesktopPanedirectly from the palette into the JFrame)

我想设置 JDesktopPane 的背景(我JDesktopPane直接从调色板添加到JFrame

I try to override the method public void paintComponent (Graphics g)but it's not working

我尝试覆盖该方法 public void paintComponent (Graphics g)但它不起作用

Here is the code:

这是代码:

JDesktop p = new JDesktop();
ImageIcon icon = new ImageIcon("images/Nénuphars6892.jpg");
final Image img = icon.getImage();
img.getScaledInstance(159, 207, Image.SCALE_SMOOTH);
p.principal = new JDesktopPane() {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(img, 0, 0, getSize().width, getSize().height, this);
    }
};
p.setVisible(true);

回答by Majda

I resolve this problem by adding that on the creation of the JDesktopPane choosing customize code(variable principal) :

我通过在选择自定义代码(变量主体)的 JDesktopPane 创建时添加来解决这个问题:

principal = new javax.swing.JDesktopPane()

{
    ImageIcon icon = new ImageIcon("images/blue_digital_waves_abstract.jpg");
    Image image = icon.getImage();

    Image newimage = image.getScaledInstance(1500, 1000, Image.SCALE_SMOOTH);

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawImage(newimage, 0, 0, this);
    }
}

;

回答by Eason Xiao

JDesktopPane desktopPane = new JDesktopPane() {

    private final ImageIcon image = new ImageIcon("sample.jpg");;

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int x = (desktopPane.getWidth() - image.getIconWidth()) / 2;
        int y = (desktopPane.getHeight() - image.getIconHeight()) / 2;
        g.drawImage(image.getImage(), x, y, this);
    }
};