Java JButton button monitoring, when more than one button to do things can be used for the loop (such as calculator 1-9) Save effort.
The variables can only be final or static when listening, but these are obviously not possible in the For loop, so we add a final variable in the loop.
Hey, easy to fix.
Package Com.xinbo;
Import Java.awt.FlowLayout;
Import Java.awt.GridLayout;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import Javax.swing.ImageIcon;
Import Javax.swing.JButton;
Import Javax.swing.JFrame;
Import Javax.swing.JOptionPane;
public class Test4 {
Static string[] s={"Penguin", "Duck", "Rabbit", "Tiger", "Kitten", "Pig", "monkey", "Puppy", "Frog"};
public static void Main (string[] args) {
JFrame jf=new JFrame ("Animal");
Jf.setlayout (New GridLayout (3, 3,10,10));
for (int j=1; J <; J + +) {
JButton jb1=new JButton (New ImageIcon ("f:/tupian/00" +j+ ". png"));
Jb1.setborder (NULL);
final int i=j-1;
Jb1.addactionlistener (new ActionListener () {
@Override
public void actionperformed (ActionEvent e) {
Joptionpane.showmessagedialog (NULL, "This is" +s[i]);
}
});
Jf.add (JB1);
}
Jf.setvisible (TRUE);
Jf.pack ();
Jf.setdefaultcloseoperation (Jframe.exit_on_close);
}
}
Use a For loop to listen to multiple JButton buttons in Java