在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还提供了许多其他类型的监听器接口,可以根据需要选择合适的监听器来处理不同类型的事件。