【问题标题】:How to update an image in a Java GUI如何在 Java GUI 中更新图像
【发布时间】:2014-07-10 14:55:43
【问题描述】:

我有一个带有几个按钮的 GUI,我正在使用 NetBeans GUI Builder 来做这件事。 单击其中一个,我希望它打开另一个包含图片的框架。

因此,我将一个侦听器 (actionPerformed) 关联到该按钮,并在单击它时打开实际发布新框架。

在新框架中,我给 JLabel 打蜡,然后关联标签的图像。我看到 NetBeans 会生成以下代码:

label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/tree.png")));

我的问题是图片在程序执行过程中被覆盖了好几次,帧中还没有改变。 也就是说,在新框架中总是显示旧版本的图像。

我怎样才能使图像始终是最新的? 非常感谢


代码:

package View;

import Controller.Util;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

public class AlberoIpotesi extends javax.swing.JFrame {

   /** Creates new form AlberoIpotesi */
   public AlberoIpotesi() {
      initComponents();

      remove(label);
      revalidate(); 
      repaint();
      Decifra.sessioneDec.toString(".../src/img/tree");
      revalidate(); 
      repaint();
   }

   /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
   // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
   private void initComponents() {

      jLabel1 = new javax.swing.JLabel();
      scroll = new javax.swing.JScrollPane();
      label = new javax.swing.JLabel();

      setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
      setTitle("Albero delle ipotesi");

      jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
      jLabel1.setText("Albero delle ipotesi");

      label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
      label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/tree.png"))); // NOI18N
      label.setVerticalAlignment(javax.swing.SwingConstants.TOP);
      scroll.setViewportView(label);

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(layout.createSequentialGroup()
            .addGap(29, 29, 29)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addComponent(scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 342, javax.swing.GroupLayout.PREFERRED_SIZE)
               .addComponent(jLabel1))
            .addContainerGap(29, Short.MAX_VALUE))
      );
      layout.setVerticalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(25, Short.MAX_VALUE))
      );

      pack();
   }// </editor-fold>                        

   /**
    * @param args the command line arguments
    */
   public static void start() {
      /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
       * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
       */
      try {
         for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
               javax.swing.UIManager.setLookAndFeel(info.getClassName());
               break;
            }
         }
      } catch (ClassNotFoundException ex) {
         java.util.logging.Logger.getLogger(AlberoIpotesi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (InstantiationException ex) {
         java.util.logging.Logger.getLogger(AlberoIpotesi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (IllegalAccessException ex) {
         java.util.logging.Logger.getLogger(AlberoIpotesi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (javax.swing.UnsupportedLookAndFeelException ex) {
         java.util.logging.Logger.getLogger(AlberoIpotesi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      }
        //</editor-fold>

      /* Create and display the form */
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            new AlberoIpotesi().setVisible(true);
         }
      });
   }

   // Variables declaration - do not modify                     
   private javax.swing.JLabel jLabel1;
   public static javax.swing.JLabel label;
   public static javax.swing.JScrollPane scroll;
   // End of variables declaration                   
}

【问题讨论】:

  • 尝试函数 revalidate();和重绘();
  • @schlagi123 感谢您的回复,但它不起作用,图像总是没有更新......
  • 你能添加你前面提到的框架的代码吗?
  • @RichardKennethNiescior 我编辑了主要信息。

标签: java image swing user-interface


【解决方案1】:

我会在 JLabel 上分别创建图标和 setIcon,如下所示:

ImageIcon icon = new ImageIcon("path/to/picture.png");
label.setIcon(icon);

这样您以后可以更改图标的图像并更新标签

icon = new ImageIcon("path/to/new_picture.png"); // Changes the icon
label.setIcon(icon); // Updates the label's icon

【讨论】:

  • 感谢您的回复,但我需要一些不同的东西。我有一个更新的图像(同名和相同路径),而不是两个不同的图像。
【解决方案2】:

所以基本上我的理解是你有一个按钮,它可以创建你希望显示的框架的新实例对象,对吗?然后,您将图像存储在项目的特定位置,您将在其中调用对象以显示更新后的图像?

我不知道您选择如何启动框架。但我可以建议的是,每次调用框架时(如果需要),您可以使用参数化构造函数来更改图像。

https://www.dropbox.com/s/mpqvy9hgsvsgq9t/PeanutsAndPretzels.zip

我不确定 stackoverflow 和外部项目文件的条款和条件。但是我编译了一些可能对你有帮助也可能没有帮助的东西。不妨试一试,或许可以得到一个想法。

【讨论】:

  • 我运行了你的项目,但这不是我需要的。您有两个从未修改过的静态图像。我每次单击按钮时都会创建一个图像(它始终具有相同的名称和相同的路径)。基本上我有一个通用树,我在上面执行操作(添加、删除等)。当我单击按钮时,我调用了一个生成树图像的方法(使用 Graphviz)。所以我有一张随时间变化的图像......
猜你喜欢
  • 2015-07-12
  • 2023-03-20
  • 2014-06-07
  • 2011-04-18
  • 2012-11-12
  • 2023-04-02
  • 2022-01-18
  • 1970-01-01
  • 2021-09-01
相关资源
最近更新 更多