java中给组合框加监听器,Java仅一次addMouseListener

I have a combobox in my program, with three options CIRCLE, RECTANGLE, FREEHAND. Each option is connected to a mouselistener. If I swich between the three options the mouselisteners are causing me some problems. Therefore I would like to add a mouselistener only once (for example in the constructor or in the beginning of the method, or somewhere else). Is it even possible, and how would the code look like?

If it is not possible, is there any other way I can solve it?

public void actionPerformed(ActionEvent e) {

if (e.getSource().equals(comboBox)) {

JComboBox cb = (JComboBox)e.getSource();

if (cb.getSelectedItem().equals("Rectangle")) {

contentPane.addMouseListener(new MouseAdapter() { //First mouseListener

@Override

public void mousePressed(MouseEvent e) {

startX = e.getX();

startY = e.getY();

}

@Override

public void mouseReleased(MouseEvent e) {

endX = e.getX();

endY = e.getY();

int width = startX - endX;

int height = startY - endY;

w = Math.abs(width);

h = Math.abs(height);

Rectangle r = new Rectangle(startX, startY, w, h, pickedColor, thickness);

shapeList.add(r);

repaint();

}

});

}

else if (cb.getSelectedItem().equals("Circle")) {

contentPane.addMouseListener(new MouseAdapter() { //Second

@Override

public void mousePressed(MouseEvent e) {

startX = e.getX();

startY = e.getY();

}

@Override

public void mouseReleased(MouseEvent e) {

endX = e.getX();

endY = e.getY();

int width = startX - endX;

int height = startY - endY;

w = Math.abs(width);

h = Math.abs(height);

Circle c = new Circle(startX, startY, w, h, pickedColor, thickness);

shapeList.add(c);

repaint();

}

});

}

else if (cb.getSelectedItem().equals("Freehand")) {

contentPane.addMouseListener(new MouseAdapter() { //Third

@Override

public void mousePressed(MouseEvent e) {

startX = e.getX();

startY = e.getY();

}

@Override

public void mouseDragged(MouseEvent e) {

FreeHand fh = new FreeHand(startX, startY, e.getX(), e.getY(), pickedColor, thickness);

shapeList.add(fh);

repaint();

}

});

}

}

解决方案

The simplest solution would be to store the last listener and remove that before adding a new one:

private MouseListener lastListener;

// ...

JComboBox cb = (JComboBox)e.getSource();

if (cb.getSelectedItem().equals("Rectangle")) {

if (lastListener != null)

contentPane.removeMouseListener(lastListener);

lastListener = new MouseAdapter() { //First mouseListener

// ...

};

contentPane.addMouseListener(lastListener);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值