import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; public class MouseEventExample extends JFrame implements MouseListener { public MouseEventExample() { super("Mouse Event Example"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 300); setLocationRelativeTo(null); addMouseListener(this); } public void mouseClicked(MouseEvent e) { if (e.isControlDown()) { // Control key was pressed System.out.println("Control key was pressed during mouse click."); } else { // Control key was not pressed System.out.println("Control key was not pressed during mouse click."); } } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public static void main(String[] args) { MouseEventExample example = new MouseEventExample(); example.setVisible(true); } }
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import javax.swing.JButton; public class ControlButton extends JButton implements ActionListener { public ControlButton(String text) { super(text); addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == this) { if (isControlDown()) { // Control key was pressed System.out.println("Control key was pressed when button was clicked."); // Perform different action when Control key is pressed } else { // Control key was not pressed System.out.println("Control key was not pressed when button was clicked."); // Perform default action when Control key is not pressed } } } public void mousePressed(MouseEvent e) { if (e.isControlDown()) { // Control key was pressed System.out.println("Control key was pressed when button was clicked."); // Perform different action when Control key is pressed } else { // Control key was not pressed System.out.println("Control key was not pressed when button was clicked."); // Perform default action when Control key is not pressed } } }In this example, we create a custom JButton that implements the ActionListener interface. In the actionPerformed() method, we check if the Control key was pressed using the isControlDown() method. If it was, we perform a different action than if it wasn't pressed. We also override the mousePressed() method to handle mouse clicks as well. This custom component could be used in a Java Swing application that needs to perform different actions based on the state of the Control key.