I am learning java and while doing a MouseListener problem I am facing an error in the class declaration, tried everything known to me please help me out. According to me I have done all the coding correctly, Pasted the code in IDE too but getting the same error.
Thanks
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Sub extends JFrame
{
private JPanel mousepanel;
private JLabel statusbar;
public Sub()
{
super("Mouse Events");
// we didnt have a FlowLayout as we had in previous programs
mousepanel = new JPanel();
mousepanel.setBackground(Color.WHITE);
add(mousepanel, BorderLayout.CENTER); //BorderLayout used instead of FlowLayout and it will place it in the center of the window.
statusbar = new JLabel("Default");
add(statusbar, BorderLayout.SOUTH); // same as above
thehandler handler = new thehandler();
mousepanel.addMouseListener(handler);
mousepanel.addMouseMotionListener(handler);
private class thehandler implements MouseListener, MouseMotionListener
{
public void mouseClicked(MouseEvent event)
{
statusbar.setText(String.format("Clicked at %d, %d", event.getX(), event.getY()));
}
public void mousePressed(MouseEvent event)
{
statusbar.setText("You press down the mouse.");
}
public void mouseReleased(MouseEvent event)
{
statusbar.setText("You released the mouse.");
}
public void mouseEntered(MouseEvent event)
{
statusbar.setText("You enetered the mouse panel area.");
mousepanel.setBackground(Color.PINK);
}
public void mouseExited(MouseEvent event)
{
statusbar.setText("The mouse has left the window.");
mousepanel.setBackground(Color.WHITE);
}
//these aremouse motion events
public void mouseDragged(MouseEvent event)
{
statusbar.setText("Your are dragging the mouse.");
}
public void mouseMoved(MouseEvent event)
{
statusbar.setText("You moded the mouse.");
}
}
}
}
-
1Care to elaborate on the error that you're running into?femtoRgon– femtoRgon2012年12月12日 21:16:31 +00:00Commented Dec 12, 2012 at 21:16
-
problem has been solved...by the solutions provided below...still thanks for your reply.user1809979– user18099792012年12月14日 19:34:32 +00:00Commented Dec 14, 2012 at 19:34
3 Answers 3
You need to move the thehandler class definition out of the scope of the Sub constructor.
Sidenote: Class names begin with an uppercase letter.
Check your curly brackets and use some IDE it will help you to rectify errors more easily.
Comments
Move your class definition outside of the constructor like this:
public Sub() {
// ... rest of code
}
// ... rest of code
private class thehandler implements MouseListener, MouseMotionListener {
// ... rest of code
}