-1

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

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

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);
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Majda
  • 99
  • 1
  • 3
  • 11
  • 3
    You could at least post some code so we don't have to read your mind to find it... – tckmn Mar 28 '13 at 12:36
  • Among other things, you're throwing away the result returned by `getScaledInstance()`. Use `ImageIO.read()`. Edit your question to include a _foramtted_ [sscce](http://sscce.org/). – trashgod Mar 28 '13 at 16:39

2 Answers2

5

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

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);
    }
}

;
Majda
  • 99
  • 1
  • 3
  • 11
2
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);
    }
};
sorak
  • 2,607
  • 2
  • 16
  • 24
Eason Xiao
  • 65
  • 2
  • 1
    Answers which are just code may technically solve the problem but do little to convey the actual solution. Please edit your answer to describe why this will work. – sorak Mar 21 '18 at 20:43