Hello,
I'm doing a project in java using swings ,im able to create a panel and frame but i have a problem in event handling.I have added the MouseMotionListener but it's giving some error .Here i want to draw a rectangle when the user clicks and drags the mouse button and releases a rectangle has to be drawn.can somebody help me to debug the error ASAP.
My code goes like this:
import javax.swing.*;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
//import javax.swing.SwingUtilities;
public class Swing_Create_Frame
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Frame in Java Swing");
frame.setBounds(400,400, 400,450);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
frame.add(new MyPanel());
frame.pack();
}
}
class MyPanel extends JPanel {
public MyPanel() {
setBorder(BorderFactory.createLineBorder(Color.red ));
}
public Dimension getPreferredSize() {
return new Dimension(400,400);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw Text
g.drawString("This is my custom Panel!",10,20);
}
MyListener myListener = new MyListener();
void addMouseListener(myListener);
addMouseMotionListener(myListener);
public class MyListener extends MouseInputAdapter {
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
currentRect = new Rectangle(x, y, 0, 0);
updateDrawableRect(getWidth(), getHeight());
repaint();
}
public void mouseDragged(MouseEvent e) {
updateSize(e);
}
public void mouseReleased(MouseEvent e) {
updateSize(e);
}
void updateSize(MouseEvent e) {
int x = e.getX();
int y = e.getY();
currentRect.setSize(x - currentRect.x,
y - currentRect.y);
updateDrawableRect(getWidth(), getHeight());
Rectangle totalRepaint = rectToDraw.union(previouseRectDrawn);
repaint(totalRepaint.x, totalRepaint.y,
totalRepaint.width, totalRepaint.height);
}
}
}
}
Errors i'm getting are
Multiple markers at this line
- MyListener cannot be resolved to a type
- Watchpoint:MyPanel [access and modification] - myListener
- MyListener cannot be resolved to a type
Multiple markers at this line
- Syntax error on token ")", { expected after this token
- myListener cannot be resolved to a type
- Syntax error on token "myListener", VariableDeclaratorId expected after this token
These are the errors i'm getting at line no 38 and 39 which i have underlined.
Can anybody tell me what should i do?
Thanks in anticipation,