gpt4 book ai didi

java - 无法更新图像图标

转载 作者:行者123 更新时间:2023-11-30 08:16:06 25 4
gpt4 key购买 nike

我有一个从网站获取随机图像的应用程序。我有一个带有 JPanel 的 JFrame。图像被添加到 JLabel 中。我的问题是新图像不会显示。在菜单栏中选择“新图像”选项后,我希望将旧图像替换为新图像。

public class GUI extends JFrame implements ActionListener {
private JPanel imagePanel;
private JScrollPane scroll;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem menuItemNew;
private JLabel label;


public GUI(String title) throws MalformedURLException, IOException {
super(title);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
newImage();
initComponents();
setSize(600, 400);
setLocationRelativeTo(null);
initMenu();
setVisible(true);
}

private void initComponents() {
scroll = new JScrollPane(imagePanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
add(scroll, BorderLayout.CENTER);
}

private void initMenu() {
menuBar = new JMenuBar();
menu = new JMenu("File");
menuBar.add(menu);
menuItemNew = new JMenuItem("New image");
menu.add(menuItemNew);
menuItemNew.addActionListener(this);
setJMenuBar(menuBar);
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(menuItemNew)) {
newImage();
}
}


private void newImage() throws MalformedURLException, IOException {
URL imageURL = new URL("http://xxxxxxx");
BufferedImage buffImg = ImageIO.read(imageURL);
ImageIcon icon = new ImageIcon(buffImg);
label = new JLabel("", icon, JLabel.CENTER);
label.setIcon(icon);
imagePanel = new JPanel(new BorderLayout());
imagePanel.add(label, BorderLayout.CENTER);
revalidate();
repaint();
}
}

最佳答案

问题是,当您重新创建 imagePanel 时,它永远不会与滚动 Pane 相关联。

解决此问题的最简单方法是将 imagePanel 和标签创建移动到 initComponents 中,然后在 newImage() 中使标签成为一个字段

private JLabel imageLabel;
private void newImage() throws MalformedURLException, IOException {
...
imageLabel.setIcon(icon);
revalidate();
repaint();
}

此外,由于您几乎肯定会遇到的下一个问题是随机网络图像的大小不正确,我强烈推荐 filthyrichclients 提供的图像大小调整实用程序方法。 .

我实际上强烈推荐 book同时,因为它是为数不多的真正展示了 Swing 的力量的书之一...

关于java - 无法更新图像图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28509135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com