To create a mouse event handler for any component of a window select that component in the design pane. Next from the event tab of the inspector choose the event. Most events are self-explanatory, but the difference between clicked and pressed is subtle. Clicked means the mouse is pressed and released while pressed means pressed and held down. In the draw example below, the mouse is pressed at the start of a draw event since it is followed by a dragged event. Click on the textbox associated with the event you want to capture and press return. You will return to the source pane with the cursor at the handler.
Each time you create a mouse event JBuilder, you will find that in the class containing the component, there is a mouse event handler inserted in the MouseListener for that component. These handlers call on private functions that start with the name of the component, followed by an underline and the name of the event. This is the event handler mouse pressed.
jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(MouseEvent e) {
jPanel1_mousePressed(e);
}
});
Here is the empty function that is called by the handler.
void jPanel1_mousePressed(MouseEvent e) {
}
The following is a fairly standard mouse event sequence used to implement interactive drawing on the panel you have created. In Swing this will not give a desirable program, since menu calls will wipe out any figure that happens to fall under the menu when it is displayed. For a more practical version of this program click here .
// When mouse is clicked note where and set some basic values needed to draw
void jPanel1_mousePressed(MouseEvent e) {
e.consume();
xFirst = e.getX();
yFirst = e.getY();
firstTime = true;
radius = 0;
}
// As the mouse is dragged draw a new image in response to the current mouse position
// and erase the last version if there is one.
void jPanel1_mouseDragged(MouseEvent e) {
e.consume();
int xNew = e.getX();
int yNew = e.getY();
Graphics g = jPanel1.getGraphics();
g.setXORMode(getBackground());
if (currentTool == lineTool){
if(!firstTime)
g.drawLine(xFirst,yFirst,xLast,yLast);//erases the old line
g.drawLine(xFirst,yFirst,xNew,yNew);
}else if (currentTool == rectTool){
if (!firstTime){
int x = Math.min(xFirst,xLast);
int y = Math.min(yFirst,yLast);
g.drawRect(x,y,Math.abs(xFirst - xLast),Math.abs(yFirst-yLast));
}
int x = Math.min(xFirst,xNew);
int y = Math.min(yFirst,yNew);
g.drawRect(x,y,Math.abs(xFirst - xNew),Math.abs(yFirst-yNew));
}else if (currentTool == circleTool){
if (!firstTime)
g.drawOval(xFirst-radius,yFirst-radius,radius*2,radius*2);
radius = Math.max(Math.abs(xNew - xFirst), Math.abs(yNew-yFirst));
g.drawOval(xFirst-radius,yFirst-radius,radius*2,radius*2);
}
firstTime = false;
xLast = xNew;
yLast = yNew;
}