5
I have code to add a background image to a JDesktopPaneand it works perfectly on widescreen 16:10 screens. However, when the screen is a little wider (16:9), it does not fill the rest of the background. I’ve seen some other possible ways to do it, but they make the picture lose a lot of quality, because they just stretch it out.
Is it possible to make a middle ground ? something that fills when necessary, and that there is not so significant loss in the image?
package novo;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class TesteJDP extends JFrame {
    private static MeuJDesktopPane jdp = new MeuJDesktopPane();
    public TesteJDP() {
        getContentPane().add(jdp);
        setSize(500, 450);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        TesteJDP teste = new TesteJDP();
        teste.setVisible(true);
    }
}
class MeuJDesktopPane extends JDesktopPane {
    private Image imagem;
    public MeuJDesktopPane() {
        try {
            imagem = new ImageIcon(getClass().getResource("/imagens/fundo.png")).getImage();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Não foi possivel ler a imagem !");
        }
    }
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Dimension dimension = this.getSize();
        int x = (int) (dimension.getWidth() - imagem.getWidth(this)) / 2;
        int y = (int) (dimension.getHeight() - imagem.getHeight(this)) / 2;
        g.drawImage(imagem, x, y, imagem.getWidth(this), imagem.getHeight(this), this);
    }
}
						
The middle term you already answered, fix the window size as the image or put a larger image.
– user28595
@diegofm has tried to put a very large image, I do not know what happens, it does not fill everything. There’s no way to add some dimension or something to fill in ?
– Java
What are the dimensions of the image?
– user28595
@diegofm 2.362 px X 1.570 px
– Java
Your window is only (500, 450) in size, as a 3x larger image does not fill everything?
– user28595