I have code to add a background image to a JDesktopPane
and it works perfectly on 16:10 widescreen screens. However, when the screen is a bit 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 image lose a lot of quality as it just stretches them.
Is it possible to make a middle ground? something that fills when needed , and does not have such 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);
}
}