我有一個簡單的應用程序,顯示由平鋪圖像(名爲u1,u2,...,u16.jpg)組成的圖片。現在我想添加一些事件給它,以便只有在單擊正確的按鈕時才能顯示這些圖像。我嘗試過自己做,但它不起作用。我在哪裏做錯了什麼?從事件聽衆開始
原始代碼:
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.border.BevelBorder;
public class Tiles_2 {
public static void main(String[] args) {
final JFrame f = new JFrame("Usmiech");
JPanel panel = new JPanel(new GridLayout(4, 4, 3, 3));
JLabel l = new JLabel();
for (int i = 1; i < 17; i++) {
String path = "u"+ i+".jpg";
l = new JLabel(new ImageIcon(path));
l.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
panel.add(l);
}
f.setContentPane(panel);
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
新代碼:
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.event.*;
public class Zad_8_1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton b = (JButton)(e.getSource());
String i = b.getText();
b = new JButton(new ImageIcon("u"+i+".jpg"));
}
public static void main(String[] args) {
final JFrame f = new JFrame("Smile");
JPanel panel = new JPanel(new GridLayout(4, 4, 3, 3));
JButton l = null;
for (int i = 1; i < 17; i++) {
String path = "u"+ i+".jpg";
l = new JButton(""+i);
l.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
l.setSize(53,53);
panel.add(l);
}
f.setContentPane(panel);
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
這應該像這樣工作: this http://img535.imageshack.us/img535/3129/lab8a.jpg
+1,因爲是第一次提到添加ActionListener(我假設這是在我發佈我的答案時完成的)。 – camickr 2010-05-31 03:40:16