如何将图像从 URL 调整为 JPanel
How can I resize an image from a URL into a JPanel
try {
addImage(bodyPanel1, "https://sneakernews.com/wp-content/uploads/2020/10/jordan-1-black-mocha-555088-105-2.jpg");
} catch (MalformedURLException e) {
e.printStackTrace();
}
private void addImage(JPanel cp, String url) throws MalformedURLException{
cp.add(new JLabel(new ImageIcon(new URL(url))));
}
所以我尝试使用 URL 插入图像,然后将其调整为车身面板的大小,但每当我尝试 运行 它时,图像不会自行缩放。我有一个网格布局(3 行,2 列)的整个车身面板,我想添加一个图像以适应其中一个网格框的整个尺寸。
image
试试我找到的这段代码 (Link to code | Link to the guy who originally found this code):
ImageIcon imageIcon = new ImageIcon(new URL(url)); // load the image to a imageIcon
Image image = imageIcon.getImage(); // transform it
Image newimg = image.getScaledInstance(120, 120, java.awt.Image.SCALE_SMOOTH); // scale it the smooth way
imageIcon = new ImageIcon(newimg);
cp.add(new JLabel(imageIcon));
ImageIcon originalIcon = new ImageIcon("slovakia.png");
JLabel originalLabel = new JLabel(originalIcon);
int width = originalIcon.getIconWidth() / 2;
int height = originalIcon.getIconHeight() / 2;
Image scaled = scaleImage(originalIcon.getImage(), width, height);
ImageIcon scaledIcon = new ImageIcon(scaled);
JLabel newLabel = new JLabel(scaledIcon);
try {
addImage(bodyPanel1, "https://sneakernews.com/wp-content/uploads/2020/10/jordan-1-black-mocha-555088-105-2.jpg");
} catch (MalformedURLException e) {
e.printStackTrace();
}
private void addImage(JPanel cp, String url) throws MalformedURLException{
cp.add(new JLabel(new ImageIcon(new URL(url))));
}
所以我尝试使用 URL 插入图像,然后将其调整为车身面板的大小,但每当我尝试 运行 它时,图像不会自行缩放。我有一个网格布局(3 行,2 列)的整个车身面板,我想添加一个图像以适应其中一个网格框的整个尺寸。 image
试试我找到的这段代码 (Link to code | Link to the guy who originally found this code):
ImageIcon imageIcon = new ImageIcon(new URL(url)); // load the image to a imageIcon
Image image = imageIcon.getImage(); // transform it
Image newimg = image.getScaledInstance(120, 120, java.awt.Image.SCALE_SMOOTH); // scale it the smooth way
imageIcon = new ImageIcon(newimg);
cp.add(new JLabel(imageIcon));
ImageIcon originalIcon = new ImageIcon("slovakia.png");
JLabel originalLabel = new JLabel(originalIcon);
int width = originalIcon.getIconWidth() / 2;
int height = originalIcon.getIconHeight() / 2;
Image scaled = scaleImage(originalIcon.getImage(), width, height);
ImageIcon scaledIcon = new ImageIcon(scaled);
JLabel newLabel = new JLabel(scaledIcon);