JAVA鼠标点击事件问题

来源:百度知道 编辑:UC知道 时间:2024/05/16 04:14:42
比如说有一个JFrame窗体放置了一个JPanel面板,然后在这个面板上添加了JLabel数组,现在我就通过鼠标点击某一个JLabel数组单元,该单元的背景色改为红色,那怎样弄才能达到这个效果?
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);
}