JAVA鼠标点击事件问题

比如说有一个JFrame窗体放置了一个JPanel面板,然后在这个面板上添加了JLabel数组,现在我就通过鼠标点击某一个JLabel数组单元,该单元的背景色改为红色,那怎样弄才能达到这个效果?

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Test {
private JFrame frame;
private JLabel label1;
private boolean flag=true;
public Test()
{
frame=new JFrame("标签测试");
label1=new JLabel("变红",JLabel.CENTER);
label1.setOpaque(true);
label1.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if(flag)
{

label1.setBackground(Color.red);
flag=false;
}
else
{
label1.setBackground(Color.white);
flag=true;
}

}
}
);
frame.getContentPane().add(label1,BorderLayout.CENTER);
frame.setSize(300,300);
frame.setLocation(300,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

}
public static void main(String[] args) {
Test t=new Test();
}

}
温馨提示:内容为网友见解,仅供参考
第1个回答  2013-07-18
//在列表框显示若干颜色选项,当单击某选项时,将文本区的背景设置为相应的颜色,当双击列表框中的某选项时,将选中颜色的文字添加到文本区中。
import java.awt.*;
import java.awt.event.*;
public class li extends Frame implements ItemListener,ActionListener
{
static li frm=new li();
static List lst=new List();
static TextArea ta=new TextArea(5,20);
public static void main(String args[])
{
frm.setLayout(new FlowLayout(FlowLayout.CENTER,10,20));
frm.setSize(350,200);
lst.add("红色");
lst.add("绿色");
lst.add("蓝色");
lst.add("黄色");
lst.addItemListener(frm);
lst.addActionListener(frm);
frm.add(lst);
frm.add(ta);
frm.setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
String clr=lst.getSelectedItem();
if(clr=="红色")
ta.setBackground(Color.red);
else if(clr=="绿色")
ta.setBackground(Color.green);
else if(clr=="蓝色")
ta.setBackground(Color.blue);
else if(clr=="黄色")
ta.setBackground(Color.yellow);
frm.setTitle("您选择了【"+clr+"】颜色");
}
public void actionPerformed(ActionEvent e)
{
String clrn=lst.getSelectedItem();
clrn="您双击的是【"+clrn+"】\n";
ta.append(clrn);
}
}
你可以参考下,试着运行,看是不是你想的那样
第2个回答  2013-07-18
private class MouseHandler extends MouseAdapter
{
//add anew square if the cursor isn't inside a square
public void mousePress(MouseEvent event) // 注意这一行,实现的方法名有误
改成
public void mousePressed(MouseEvent event)
就可以了
相似回答