I have a simple app, showing picture made of tiled images(named u1, u2,...,u16.jpg). Now I'd like to add some Events to it, so that I can show these images only when proper button is clicked. I've tried doing it on my own, but it's not working. Where am I doing something wrong?
Original code :
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);
}
}
New code :
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 should work like this :