Reputation: 257
How do I go about writing a mouse listener that will react to pressing on any object in a JFrame
, or on one particular object?
Here's my mouse listener -
class mouse extends MouseAdapter
{
public void mousePressed(MouseEvent event)
{
yearLabel.setText("nu");
}
}
Upvotes: 3
Views: 5681
Reputation: 852
you can add a global mouse listener by Toolkit.getDefaultToolkit().addAWTEventListener(listener,mask)
here is a example
public class SwingTest{
public static void main(String[] args) {
JPanel mainPanel = new JPanel();
mainPanel.add(new JButton("button"));
final JLabel label = new JLabel("label");
mainPanel.add(label);
showFrame("", mainPanel);
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
public void eventDispatched(AWTEvent event) {
if(event instanceof MouseEvent){
MouseEvent evt = (MouseEvent)event;
if(evt.getID() == MouseEvent.MOUSE_CLICKED){
label.setText("mouse clicked at: " + evt.getPoint());
}
}
}
}, AWTEvent.MOUSE_EVENT_MASK);
}
public static JFrame showFrame(String title, Component component) {
JFrame frame = new JFrame();
frame.setTitle(title);
frame.getContentPane().add(component, BorderLayout.CENTER);
frame.setSize(900, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
return frame;
}
}
Upvotes: 9
Reputation: 4889
Did you attach this listener to the component containing yearLabel
? Additionally, I should comment that class names are by convention capitalized. Otherwise, you will confuse other programmers.
Upvotes: 2