gpt4 book ai didi

Java只addMouseListener一次

转载 作者:行者123 更新时间:2023-12-01 22:37:28 24 4
gpt4 key购买 nike

我的程序中有一个组合框,其中包含三个选项“圆形”、“矩形”、“徒手画”。每个选项都连接到一个鼠标监听器。如果我在三个选项之间切换,鼠标监听器会给我带来一些问题。因此,我只想添加一次鼠标监听器(例如在构造函数中或在方法的开头或其他地方)。这是否可能,代码会是什么样子?如果不行的话还有其他办法可以解决吗?

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();
}
});
}

}

最佳答案

您应该在构造函数中向面板添加一个鼠标监听器,而不是每次在组合框中进行选择时向面板添加不同的监听器。并且此监听器在调用其方法之一时,应首先检查选择了哪个选项,并采取相应的操作(即绘制矩形或圆形,或根据选择徒手绘制)。

关于Java只addMouseListener一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26684750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com