我有一个JFrame,用于显示图像(从网页检索)和两个横向按钮,用于显示下一个和上一个图像。原始图像尺寸太大,我会在展示之前缩放它。这是我的代码:
public class ShowPicture extends JFrame implements ActionListener {
private String link;
private JButton next;
private JButton prev;
private Image image;
public ShowPicture(String link) {
this.setSize(300, 200);
setLocationRelativeTo(null); //center
setVisible(true);
this.link = link;
this.setLayout(new FlowLayout());
prev = new JButton("prev");
next = new JButton("next");
URL url;
try {
url = new URL(link + "/front.jpg");
image = ImageIO.read(url);
} catch (MalformedURLException ex) {
Logger.getLogger(ShowPicture.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ShowPicture.class.getName()).log(Level.SEVERE, null, ex);
}
JLabel image_label = new JLabel(new ImageIcon(image));
image_label.setSize(100, 100);
this.add(prev);
this.add(image_label);
this.add(next);
pack();
}
但图像未缩放
我该怎么办?
答案 0 :(得分:2)
我会缩放图像本身而不是JLabel
。使用:
image = ImageIO.read(url);
image = image.getScaledInstance(100,100,Image.SCALE_DEFAULT);
JLabel image_label = new JLabel(new ImageIcon(image));