在Swing组件上显示ImageIcon

时间:2016-02-25 18:25:46

标签: java swing netbeans imageicon

我正在尝试将其用于扫雷游戏。

import javax.swing.ImageIcon;
public class Testing extends javax.swing.JFrame {
    private ImageIcon icon;
    public Testing() {
        initComponents();
        icon = new ImageIcon("flag.gif");
    }
    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel = new javax.swing.JLabel();
    jButton = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(new java.awt.FlowLayout());

    jLabel.setPreferredSize(new java.awt.Dimension(32, 32));
    getContentPane().add(jLabel);

    jButton.setPreferredSize(new java.awt.Dimension(32, 32));
    jButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButtonActionPerformed(evt);
        }
    });
    getContentPane().add(jButton);

    pack();
}// </editor-fold>                        
private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
        //diplay the icon
        jButton.setIcon(icon);
        jLabel.setIcon(icon);
}                                       
    public static void main(String args[]) {
       /* Create and display the form */
       java.awt.EventQueue.invokeLater(new Runnable() {
           public void run() {
               new Testing().setVisible(true);
           }
       });
   }
// Variables declaration - do not modify                     
private javax.swing.JButton jButton;
private javax.swing.JLabel jLabel;
// End of variables declaration                   
}

我需要能够在按钮上显示图像,但我甚至无法将其显示在标签上。该图像与类文件位于同一文件中,为32x32。

1 个答案:

答案 0 :(得分:0)

修改

你的代码对我来说非常好。您的问题几乎可以肯定是指向错误的文件位置。确保flag.gif位于项目的根目录中,不一定与您的类位于同一目录中:

DataTable

祝你好运