JAVA鼠标点击事件问题
来源:百度知道 编辑:UC知道 时间:2024/05/16 04:14:42
1楼,我添加了MouseListener事件,但我写的处理方法可以编译,但不能运行!
3楼,我要的是JLabel控件,不是JButton。
//我有个差不多的例子..
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LabelTest
{
JFrame frame = new JFrame("JButtonTest");
int len = 4;
JButton[] lbs = new JButton[len];
GridLayout glayout = new GridLayout(len,1);
boolean hc = true;
public void lunachFrame(){
frame.setLayout(glayout);
frame.setLocation(200, 200);
for(int i = 0; i < len ; i ++){
lbs[i] = new JButton("我是Button" + (i + 1));
final int n = i;
lbs[i].addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(hc){
lbs[n].setBackground(Color.RED);
hc = !hc;
}
else{
lbs[n].setBackground(Color.BLUE);
hc = !hc;
}
}
});
frame.add(lbs[i]);
}
frame.pack();
frame.setVisible(true);
}