0
我正在嘗試將這個用於掃雷遊戲。在Swing組件上顯示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。
的你搖一點點?通常他們不適合。只是給它一個好的搖動 – gpasch
*「圖像與類文件在同一個文件中」* - 那麼你應該使用更像'icon = new ImageIcon(getClass()。getResource(「flag.gif」)) ;'而是,'ImageIcon(String)'假定文件位於磁盤上,對於嵌入式資源來說不是這樣。我還鼓勵你使用'ImageIO.read',因爲當圖像無法加載時它會拋出一個'IOException' – MadProgrammer