将多个JLable放入单个addMouseListener

时间:2016-05-28 19:16:37

标签: java jlabel

我得到了3 JLable,我点击了l3时的功能,将JLabel文本设置为值存储到数组中(ans.get( 0,0))

JLabel l1 = new JLabel("Obtener x1");

JLabel l2 = new JLabel("Obtener x2");

JLabel l3 = new JLabel("Obtener x3");
l3.setBounds(30, 180, 100, 25);
l3.addMouseListener(new MouseListener() {

  @Override
  public void mouseClicked(MouseEvent e) 
  {
  l3.setText("X1 = "+ ans.get(0, 0));
  }
  @Override
  public void mouseEntered(MouseEvent e) {
  //MouseEntered, MousePressed, MouseRelease overriden methods....

这里的问题是,是否可行实现其余的JLabel s(l1l2)成为一个addMouseListener(同一个mouseListener属于{{1} }} JLabel)?

1 个答案:

答案 0 :(得分:1)

MouseListener创建一个本地变量,并为其分配实例。然后将MouseListener添加到您的每个JLable

JLabel l1 = new JLabel("Obtener x1");
JLabel l2 = new JLabel("Obtener x2");
JLabel l3 = new JLabel("Obtener x3");

MouseListener ml = new MouseListener() {...}

l1.addMouseListener(ml);
l2.addMouseListener(ml);
l3.addMouseListener(ml);

然后每个JLable将共享相同的MouseListener对象。