我需要在mouselistener事件处理程序内外输出数据

时间:2012-07-15 14:25:55

标签: java jframe jlabel mouselistener

请原谅我,如果答案是相当微不足道的,因为我还没有编程一段时间。我的应用程序的目标是从我在框架中显示的图像中获取RGB值,其中(x,y)坐标由鼠标监听器给出,但是当我在我的事件处理程序中时,我只能访问x,y值而不是我的BufferedImage。救命!我被困了几个小时!!

来自MouseHandler类的

代码:

    public void mouseClicked (MouseEvent e)
{
    int x = e.getX();
    int y = e.getY();
    System.out.printf("You clicked at: %d,%d\n", x, y);
}

应用程序类的代码:

    public static void main(String args[]) 
{
    String file_name = args[0];

    BufferedImage image = readImage2(file_name);
    Frame frame = createFrame(file_name);

    //somehow get x,y from listener;
    //int RGB = image.getRGB(x,y);
}

1 个答案:

答案 0 :(得分:1)

我建议您在创建BufferedImage课程时发送MouseHandler

public class MouseHandler implents MouseListener {

  private BufferedImage image;

  public MouseHandler(BufferedImage image) {
    this.image = image;
  }
  public void mouseClicked (MouseEvent e) {
    int x = e.getX();
    int y = e.getY();
    System.out.printf("You clicked at: %d,%d\n", x, y);
    System.out.printf("Color is: %d", image.getRGB(x, y));
  }
  ...
}