我的代码的问题是我的图片只获得JFrame
的开头大小 - 但我希望每次用户更改窗口大小时都会改变大小。
图片尺寸是否应相对于JFrame
尺寸或JPanel
?如果是这样,我将如何实现这一目标?
这是我的代码:
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();
}
});
}
}
答案 0 :(得分:1)
图像可以(确实应该)在 paintComponent(Graphics)
方法中进行缩放。这样它可以改变为面板的大小。
另见代码中的注释:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
public class MainFrame2 extends JFrame {
private JPanel card1;
private BufferedImage image;
public MainFrame2() {
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
// if there is a problem with URL - no point trying to load
URL url = new URL("https://i.stack.imgur.com/7bI1Y.jpg");
image = ImageIO.read(url);
} catch (Exception e) {
System.out.println("Problem loading image");
e.printStackTrace();
}
/* The frame will actually be larger than the panel.
Better to scale the image to the SIZE OF THE PANEL ...
Image scaledImage = image.getScaledInstance(this.getWidth(),
this.getHeight(), Image.SCALE_SMOOTH); */
card1 = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// .. this is how.
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
};
setContentPane(card1);
setVisible(true); // this should be last!
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MainFrame2();
}
});
}
}