在Java中,EventListener是一種接口,用于處理特定類型事件的監聽器。以下是一些常見的事件監聽器類型:
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
JButton button = new JButton("Click me");
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Button clicked!");
}
});
JFrame frame = new JFrame("KeyListener Example");
frame.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + KeyEvent.getKeyText(e.getKeyCode()));
}
});
JTextField textField = new JTextField();
textField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
System.out.println("TextField gained focus.");
}
@Override
public void focusLost(FocusEvent e) {
System.out.println("TextField lost focus.");
}
});
JCheckBox checkBox = new JCheckBox("Check me");
checkBox.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
System.out.println("Checkbox state changed: " + checkBox.isSelected());
}
});
JRadioButton radioButton1 = new JRadioButton("Option 1");
JRadioButton radioButton2 = new JRadioButton("Option 2");
ButtonGroup group = new ButtonGroup();
group.add(radioButton1);
group.add(radioButton2);
radioButton1.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
System.out.println("Selected radio button: " + e.getItem());
}
});
這些只是一些常見的事件監聽器類型,實際上Java還提供了許多其他類型的監聽器接口,可以根據需要選擇合適的監聽器來處理不同類型的事件。