這似乎微不足道,但你可以簡單地做:
myLabel.removeMouseListener(this);
方案二是離開的MouseListener到位,但要聰明 - 即給它的邏輯,允許它忽略如果需要輸入。這可能是一個簡單的,如果塊如
@Override
public void mousePressed(MouseEvent me) {
if (someBoolean) {
return;
}
// here have your usual code
}
,然後在你的代碼,當你想重新激活的MouseListener,只需將聽者的someBoolean字段更改爲false。使用布爾型開關或標誌對於需要重複打開和關閉偵聽器時非常有用。
作爲一個便箋,你通常最好不要爲你的聽衆使用this
,因爲這給主GUI類帶來了太多的責任。相反,對於簡單的幾行代碼或命名類,使用匿名內部類來獲取更多涉及的偵聽器代碼。
例如:
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.border.Border;
public class TurnListenerOnAndOff extends JPanel {
private JLabel myLabel = new JLabel("My Label");
private JCheckBox listenerEnabledCheckBox = new JCheckBox("Listener Enabled", true);
public TurnListenerOnAndOff() {
// make label bigger with a border
Border outsideBorder = BorderFactory.createLineBorder(Color.black);
Border insideBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
myLabel.setBorder(BorderFactory.createCompoundBorder(outsideBorder, insideBorder));
// create and add MyMouseListener to my label
myLabel.addMouseListener(new MyMouseListener());
// add components to the GUI's main JPanel
add(myLabel);
add(listenerEnabledCheckBox);
}
private class MyMouseListener extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
// if the JCheckBox isn't checked...
if (!listenerEnabledCheckBox.isSelected()) {
return; // let's get out of here
}
// otherwise if the check box is checked, do following code
System.out.println("myLabel pressed!");
}
}
private static void createAndShowGui() {
TurnListenerOnAndOff mainPanel = new TurnListenerOnAndOff();
JFrame frame = new JFrame("On and Off");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
謝謝,這是我正在尋找:) –
在選項2中,不要忘了添加一個'me.consume()'如果你不希望任何其他事件被觸發。 – lvr123
me.consume()做什麼?我應該在哪裏使用它? –