Reputation: 5
I was making a program and I wanted to know how to make certain areas of a JFrame activate something when clicked, although without a button, like you clicked in the upper-right quarter of a picture to activate something.
Upvotes: 0
Views: 690
Reputation: 438
create a JLabel object and set its icon to the image you want to display. Then add a mouse listener to the label object and implement all of its abstract classes especially the mouse clicked method to do what you want to do when clicked. Then when you click your JLabel you will see what you want.
The below code is an example to print "hello" when label is clicked:-
java.awt.event.MouseListener ml = new java.awt.event.MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("hello");
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
};
jLabel1.addMouseListener(ml);
Upvotes: 0
Reputation: 324098
Create an List of Shape objects to represent the areas that you want to click on:
List<Shape> shapes = new ArrayList<Shape>();
Then you can add different shapes to the List:
areas.add( new Rectangle(5, 5, 10, 10) );
Then you add a MouseListener to the frame and in the mousePressed event you would do something like:
for (Shape shape: shapes)
{
if (shape.contains(theMousePointFromTheMouseEvent)
// do something
}
Upvotes: 2