鼠标事件“无法找到符号”错误的解决方案

时间:2013-07-18 18:37:50

标签: java applet awt

我一直在导入更多的软件包,但是我得到了与所有包含鼠标事件的方法相同的“错误:无法找到符号”。我想我错过了一个需要扩展或实现的包或类,但我找不到哪一个。有什么想法吗?

import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.*;

public class t1 implements MouseListener
{ 
    public static void main(String[] args)
    {
    // Create frame with title
        Frame frame = new Frame("Click Counter Project");

        // Create a component to add to the frame
        final TextArea textArea = new TextArea("Click");
    }
    public void mousePressed(MouseEvent event)
    { 
            textArea.setText("Mouse pressed. x = "+ event.getX() + " y = " +         event.getY());
    } 
    public void mouseReleased(MouseEvent event)
    { 
        textArea.setText("Mouse released. x = "+ event.getX() + " y = " + event.getY());
} 
public void mouseClicked(MouseEvent event)
{ 
    textArea.setText("Mouse clicked. x = "+ event.getX() + " y = " + event.getY());
    } 
    public void mouseEntered(MouseEvent event)
    { 
        textArea.setText("Mouse entered. x = "+ event.getX() + " y = " + event.getY());
    } 
    public void mouseExited(MouseEvent event)
    { 
            textArea.setText("Mouse exited. x = "+ event.getX() + " y = " + event.getY());
    }
    public void t1()
    {
        frame.add(textArea, BorderLayout.NORTH);
            int width = 300;
            int height = 300;
            frame.setSize(width, height);
            frame.setVisible(true);
    }
}

2 个答案:

答案 0 :(得分:1)

您的变量textAreamain内被声明为局部变量,因此它超出了其他方法的范围。

在类中但在所有方法之外声明textArea - 作为实例变量。然后它将适用于您的整个课程,包括您的所有方法。

public class t1 implements MouseListener
{
    // Here!
    final TextArea textArea = new TextArea("Click");

    public static void main(String[] args)
    {
        // ...

您需要对frame变量执行相同的操作。

答案 1 :(得分:1)

已导入所有必需的包和文件。存在“无法找到符号”错误的原因是因为“textArea”字段和“frame”变量是本地的。将它们声明为静态类变量,如下面的代码所示,然后在main方法中初始化它们,并且找不到符号错误。

代码应该是这样的: -

 public class t1 implements MouseListener
    { 
    static TextArea textArea;
    static Frame frame;
        public static void main(String[] args)
        {
        // Create frame with title
          frame = new Frame("Click Counter Project");

            // Create a component to add to the frame
             textArea = new TextArea("Click");
             t1 clickCount= new t1();
        }
    ...
 t1()
    {
        frame.add(textArea, BorderLayout.NORTH);
            int width = 300;
            int height = 300;
            frame.setSize(width, height);
            frame.addMouseListener(this);
            frame.setVisible(true);
    }
    }