Java中Jbutton按钮监听,当多个按钮做的事差不多的时候是可以用for循环的(比如计算器1-9)省事省力。
监听时变量只能是final或者static,不过这些在for循环中明显不行,所以,就在循环里加了个final变量。
嘿嘿,轻松搞定。
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={"企鹅","鸭子","兔子","老虎","小猫","猪","猴子","小狗","青蛙"};
public static void main(String[] args) {
JFrame jf=new JFrame("动物");
jf.setLayout(new GridLayout(3, 3,10,10));
for (int j=1; j < 10; 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, "这个是"+s[i]);
}
});
jf.add(jb1);
}
jf.setVisible(true);
jf.pack();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
原文地址:http://qq445493481.blog.51cto.com/9545543/1585272