The problem with my code is that my image only gets the beginning size of the JFrame
- but I want it to change size every time the user changes the size of the window.
Also should the image size be relative to JFrame
size or its JPanel
? If so, how would I achieve that?
Here is my code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class MainFrame extends JFrame {
private JPanel card1;
private JPanel principalPanel,centerPanel;
private BufferedImage image;
public MainFrame() {
setSize(800,600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
URL url = null;
try {
url = new URL("https://i.stack.imgur.com/7bI1Y.jpg");
} catch (MalformedURLException e) {
}
try {
image = ImageIO.read(url);
} catch (IOException e) {
System.out.println("Can not find image");
}
Image scaledImage = image.getScaledInstance(this.getWidth(),
this.getHeight(),Image.SCALE_SMOOTH);
card1 = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(scaledImage,0,0,this);
}
};
centerPanel = new JPanel();
centerPanel.setLayout(new CardLayout());
centerPanel.add(card1,"1");
principalPanel = new JPanel();
principalPanel.setLayout(new BorderLayout());
principalPanel.add(centerPanel,BorderLayout.CENTER);
setContentPane(principalPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MainFrame();
}
});
}
}