在MouseListener的画布不工作 [英] MouseListener in Canvas not working

查看:201
本文介绍了在MouseListener的画布不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个游戏,我试图用Java做的一个问题。我想一个MouseListener的重视我的画布,然而,当我点击画布上,没有任何反应。我想我可能会在连接到的MouseListener错误的事情,但我不知道是什么把它连接到。我曾尝试将其连接到JFrame和画布。这里是我的code:

 进口java.awt中的*。
java.awt.event中导入*。
进口的java.util.ArrayList;进口java.io. *;进口javax.imageio.ImageIO中;
进口的javax.swing *。
进口了java.util.Random;公共类重力扩展画布{    公共静态最终诠释screenw = 1024;
    公共静态最终诠释screenh = 768;    公共静态随机根=新的随机();    公共静态布尔开始= FALSE;    公共静态INT [] = starx新INT [100];
    公共静态INT [] =斯达新INT [100];
    公共静态颜色[] = STARC新的色彩[100];    公共静态的JFrame框架;
    公共静态重力帆布;
    公共静态图像缓冲区;
    公共静态图形BG;    公共静态INT [] = XH新INT [1000];
    公共静态INT [] = YH新INT [1000];    公共静态INT I = 0;    公共静态图像标题;    公共静态的ArrayList<整数GT; PTX =新的ArrayList<整数GT;();
    公共静态的ArrayList<整数GT; PTY =新的ArrayList<整数GT;();
    双X = 100;
    双Y = 100;    公共比重(){
    }    公共无效漆(图形G){
        frame.addMouseListener(新的MouseListener(){
            公共无效的mouseClicked(的MouseEvent E){
                启动= TRUE;
                的System.out.println(鼠标被点击);
            }            公共无效的mouseEntered(的MouseEvent将arg0){}
            公共无效的mouseExited(的MouseEvent将arg0){}
            公共无效鼠标pressed(的MouseEvent将arg0){}
            公共无效的mouseReleased(的MouseEvent将arg0){}
        });
        缓冲=的createImage(screenw,screenh);
        BG = buffer.getGraphics();        INT W =的getWidth();
        INT H =的getHeight();        双像素=的getWidth()/ 2;
        双吡啶=的getHeight()/ 2;        bg.setColor(Color.BLACK);
        bg.fillRect(0,0,W,H); //黑色背景        对于(INT J = 0; J< 100; J ++){//做明星
            starx [J] = gen.nextInt(W);
            斯达[J] = gen.nextInt(H);
            STARC [J] =新的色彩(gen.nextInt(100)+156,gen.nextInt(100)+156,gen.nextInt(100)+156);
            bg.setColor(STARC [J]);
            bg.drawLine(starx [J],斯达[J],starx [J] +2,斯达[J] +2);
            bg.drawLine(starx [J],斯达[J] +2,starx [J] +2,斯达[J]);
        }        尝试{
            标题= ImageIO.read(新ByteArrayInputStream进行(Base64.de code())); //我省略了的Base64 code为图像为我的标题画面
        }赶上(IOException异常五){
            e.printStackTrace();
        }        bg.drawImage(标题,100,100,NULL);
        g.drawImage(缓冲液,0,0,NULL);        而(!开始){
            尝试{
                视频下载(50);
            }赶上(InterruptedException的E1){
                e1.printStackTrace();
            }
        }        双xvel = -15;
        双yvel = 10;        对于(INT J = 0; J< 100; J ++){//明星店
            starx [J] = gen.nextInt(W);
            斯达[J] = gen.nextInt(H);
            STARC [J] =新的色彩(gen.nextInt(100)+156,gen.nextInt(100)+156,gen.nextInt(100)+156);
        }        图像测试=的createImage(200,200);
        图形testg = test.getGraphics();
        testg.drawLine(50,50,150,150);        而(真){
            g.drawImage(缓冲液,0,0,空);
            尝试{
                视频下载(33);
            }赶上(例外五){
                e.printStackTrace();
            }            bg.setColor(Color.BLACK);
            bg.fillRect(0,0,W,H); //黑色背景
            对于(INT J = 0; J< 100; J ++){//平局明星
                bg.setColor(STARC [J]);
                bg.drawLine(starx [J],斯达[J],starx [J] +2,斯达[J] +2);
                bg.drawLine(starx [J],斯达[J] +2,starx [J] +2,斯达[J]);
            }            bg.setColor(Color.BLUE);            如果(I 0){
                对(INT z = 0的; z,其中,I-1; Z ++){
                    bg.drawLine(ptx.get(Z),pty.get(Z),ptx.get(Z + 1),pty.get(Z + 1));
                }
            }            bg.setColor(Color.CYAN);
            bg.fillOval((INT)像素,(INT)PY,25,25); //行星            bg.setColor(Color.RED);
            bg.fillRect((int)的(X-5),(INT)(Y-5),10,10); //船            双FG =(5 * 50000)/(Math.pow(DIST(X,Y,PX,PY),2));            双M =(Y-PY)/(X-PX);
            双毫秒=的Math.sqrt(Math.abs(米));
            如果(M小于0)毫秒= -ms;            双XCHG = FG;
            双ychg = FG *毫秒;            如果(X> PX){
                XCHG = -xchg;
                ychg = -ychg;
            }            xvel + = XCHG;
            yvel + = ychg;            X + = xvel;
            Y + = yvel;            ptx.add((INT)x)的;
            pty.add((INT)Y);            我++;
        }
    }    公共静态无效的主要(字串[] args){        帆布=新引力();
        帧=新的JFrame();
        frame.setSize(screenw,screenh);
        frame.setResizable(假);
        frame.setLocationRelativeTo(NULL);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        。frame.getContentPane()加(画布);        frame.setVisible(真);
    }
    公共静态双DIST(双X1,Y1双,双X2双Y2){
        双X = X2-X1;
        双Y = Y2-Y1;
        返回的Math.sqrt((X * X)+(Y * Y));
    }
}


解决方案

一般提示,逐点:


  1. 请不要混合使用AWT(例如画布)与Swing(例如的JFrame )组件。取而代之的是帆布的,使用的JP​​anel 和覆盖的paintComponent(图形),而不是漆(图形)

  2. 请不要叫视频下载(N)在EDT。相反,使用基于Swing的定时调用重绘()

  3. 请不要执行长在paint方法运行的操作,尤其是在开始一个无限循环!即使在缓冲图像的创建只应在的情况下进行的屏幕尺寸的变化。 (左为TODO - BNI)

  4. 添加的MouseListener 一旦在构造函数或的init()方法,而不是每次油漆被调用。

  5. 强烈推荐所有Nate的编号笔记列表中。

试试这个code和仔细比较它原来看到的变化。

 进口java.awt.Color中;
进口java.awt.Graphics;
进口java.awt.Image中;
进口java.awt.Dimension中;
java.awt.event中导入*。
进口的java.util.ArrayList;进口java.io. *;进口javax.imageio.ImageIO中;
进口的javax.swing *。
进口了java.util.Random;公共类重力继承JPanel {    公共静态最终诠释screenw = 800;
    公共静态最终诠释screenh = 600;    公共静态随机根=新的随机();    公共静态INT [] = starx新INT [100];
    公共静态INT [] =斯达新INT [100];
    公共静态颜色[] = STARC新的色彩[100];    公共静态图像缓冲区;
    公共静态图形BG;    公共静态INT [] = XH新INT [1000];
    公共静态INT [] = YH新INT [1000];    公共静态INT I = 0;    公共静态的ArrayList<整数GT; PTX =新的ArrayList<整数GT;();
    公共静态的ArrayList<整数GT; PTY =新的ArrayList<整数GT;();
    双X = 100;
    双Y = 100;    定时器定时器;    公共比重(){
        //设置THRE preFERRED大小!
        集preferredSize(新尺寸(screenw,screenh));
        addMouseListener将(新的MouseListener(){
                    公共无效的mouseClicked(的MouseEvent E){
                        的System.out.println(鼠标被点击);
                        timer.start();
                    }                    公共无效的mouseEntered(的MouseEvent将arg0){}
                    公共无效的mouseExited(的MouseEvent将arg0){}
                    公共无效鼠标pressed(的MouseEvent将arg0){}
                    公共无效的mouseReleased(的MouseEvent将arg0){}
        });
        ActionListener的动画=新的ActionListener(){
            @覆盖
            公共无效的actionPerformed(ActionEvent的AE){
                重绘();
            }
        };
        定时器=新定时器(50,动画);
    }    @覆盖
    公共无效的paintComponent(图形G){
        缓冲=的createImage(screenw,screenh);
        BG = buffer.getGraphics();        INT W =的getWidth();
        INT H =的getHeight();        双像素=的getWidth()/ 2;
        双吡啶=的getHeight()/ 2;        bg.setColor(Color.BLACK);
        bg.fillRect(0,0,W,H); //黑色背景        对于(INT J = 0; J< 100; J ++){//做明星
            starx [J] = gen.nextInt(W);
            斯达[J] = gen.nextInt(H);
            STARC [J] =新的色彩(gen.nextInt(100)+156,gen.nextInt(100)+156,gen.nextInt(100)+156);
            bg.setColor(STARC [J]);
            bg.drawLine(starx [J],斯达[J],starx [J] +2,斯达[J] +2);
            bg.drawLine(starx [J],斯达[J] +2,starx [J] +2,斯达[J]);
        }        g.drawImage(缓冲液,0,0,NULL);        双xvel = -15;
        双yvel = 10;        对于(INT J = 0; J< 100; J ++){//明星店
            starx [J] = gen.nextInt(W);
            斯达[J] = gen.nextInt(H);
            STARC [J] =新的色彩(gen.nextInt(100)+156,gen.nextInt(100)+156,gen.nextInt(100)+156);
        }        图像测试=的createImage(200,200);
        图形testg = test.getGraphics();
        testg.drawLine(50,50,150,150);        g.drawImage(缓冲液,0,0,空);
        尝试{
            视频下载(33);
        }赶上(例外五){
            e.printStackTrace();
        }        bg.setColor(Color.BLACK);
        bg.fillRect(0,0,W,H); //黑色背景
        对于(INT J = 0; J< 100; J ++){//平局明星
            bg.setColor(STARC [J]);
            bg.drawLine(starx [J],斯达[J],starx [J] +2,斯达[J] +2);
            bg.drawLine(starx [J],斯达[J] +2,starx [J] +2,斯达[J]);
        }        bg.setColor(Color.BLUE);        如果(I 0){
            对(INT z = 0的; z,其中,I-1; Z ++){
                bg.drawLine(ptx.get(Z),pty.get(Z),ptx.get(Z + 1),pty.get(Z + 1));
            }
        }        bg.setColor(Color.CYAN);
        bg.fillOval((INT)像素,(INT)PY,25,25); //行星        bg.setColor(Color.RED);
        bg.fillRect((int)的(X-5),(INT)(Y-5),10,10); //船        双FG =(5 * 50000)/(Math.pow(DIST(X,Y,PX,PY),2));        双M =(Y-PY)/(X-PX);
        双毫秒=的Math.sqrt(Math.abs(米));
        如果(M小于0)毫秒= -ms;        双XCHG = FG;
        双ychg = FG *毫秒;        如果(X> PX){
            XCHG = -xchg;
            ychg = -ychg;
        }        xvel + = XCHG;
        yvel + = ychg;        X + = xvel;
        Y + = yvel;        ptx.add((INT)x)的;
        pty.add((INT)Y);        我++;
    }    公共静态无效的主要(字串[] args){
        SwingUtilities.invokeLater(Runnable的新(){
            公共无效的run(){
                JFrame的帧=新的JFrame();                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                。frame.getContentPane()增加(新引力());
                frame.setResizable(假);
                frame.pack();                frame.setLocationByPlatform(真);
                frame.setVisible(真);
            }
        });
    }
    公共静态双DIST(双X1,Y1双,双X2双Y2){
        双X = X2-X1;
        双Y = Y2-Y1;
        返回的Math.sqrt((X * X)+(Y * Y));
    }
}

I am having a problem with a game that I am trying to make in Java. I am trying to attach a MouseListener to my canvas, however, when I click on the canvas, nothing happens. I think I may be attaching the MouseListener to the wrong thing, but I don't know what to attach it to. I have tried attaching it to the JFrame and the canvas. Here is my code:

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;

import java.io.*;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.util.Random;

public class Gravity extends Canvas {

    public static final int screenw = 1024;
    public static final int screenh = 768;

    public static Random gen = new Random();

    public static Boolean started = false;

    public static int[] starx = new int[100];
    public static int[] stary = new int[100];
    public static Color[] starc = new Color[100];

    public static JFrame frame;
    public static Gravity canvas;
    public static Image buffer;
    public static Graphics bg;

    public static int[] xh = new int[1000];
    public static int[] yh = new int[1000];

    public static int i = 0;

    public static Image title;

    public static ArrayList<Integer> ptx = new ArrayList<Integer>();
    public static ArrayList<Integer> pty = new ArrayList<Integer>();
    double x = 100;
    double y = 100;

    public Gravity(){
    }

    public void paint (Graphics g) {
        frame.addMouseListener(new MouseListener(){
            public void mouseClicked(MouseEvent e){
                started = true;
                System.out.println("Mouse was clicked");
            }

            public void mouseEntered(MouseEvent arg0) {}
            public void mouseExited(MouseEvent arg0) {}
            public void mousePressed(MouseEvent arg0) {}
            public void mouseReleased(MouseEvent arg0) {}
        });


        buffer = createImage(screenw, screenh);
        bg = buffer.getGraphics();

        int w = getWidth();
        int h = getHeight();

        double px = getWidth()/2; 
        double py = getHeight()/2;

        bg.setColor(Color.BLACK);
        bg.fillRect(0, 0, w, h); //black background

        for (int j=0; j < 100; j++){ //make stars
            starx[j] = gen.nextInt(w);
            stary[j] = gen.nextInt(h);
            starc[j] = new Color(gen.nextInt(100)+156, gen.nextInt(100)+156, gen.nextInt(100)+156);
            bg.setColor(starc[j]);
            bg.drawLine(starx[j], stary[j], starx[j]+2, stary[j]+2);
            bg.drawLine(starx[j], stary[j]+2, starx[j]+2, stary[j]);
        }

        try {
            title = ImageIO.read(new ByteArrayInputStream(Base64.decode(""))); //I have omitted the Base64 code for the image for my title screen
        } catch (IOException e) {
            e.printStackTrace();
        }

        bg.drawImage(title, 100, 100, null);
        g.drawImage(buffer, 0, 0, null);

        while (!started){
            try {
                Thread.sleep(50);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }

        double xvel = -15;
        double yvel = 10;

        for (int j=0; j < 100; j++){ //store stars
            starx[j] = gen.nextInt(w);
            stary[j] = gen.nextInt(h);
            starc[j] = new Color(gen.nextInt(100)+156, gen.nextInt(100)+156, gen.nextInt(100)+156);
        }

        Image test = createImage(200,200);
        Graphics testg = test.getGraphics();
        testg.drawLine(50,50,150,150);

        while(true){
            g.drawImage(buffer, 0,0, null);
            try {
                Thread.sleep(33);
            } catch (Exception e) {
                e.printStackTrace();
            }

            bg.setColor(Color.BLACK);
            bg.fillRect(0, 0, w, h); //black background


            for (int j=0; j < 100; j++){ //draw stars
                bg.setColor(starc[j]);
                bg.drawLine(starx[j], stary[j], starx[j]+2, stary[j]+2);
                bg.drawLine(starx[j], stary[j]+2, starx[j]+2, stary[j]);
            }

            bg.setColor(Color.BLUE);

            if (i > 0){
                for (int z=0; z < i-1; z++){
                    bg.drawLine(ptx.get(z), pty.get(z), ptx.get(z+1), pty.get(z+1));
                }
            }

            bg.setColor(Color.CYAN);
            bg.fillOval((int)px, (int)py, 25, 25); //planet

            bg.setColor(Color.RED);
            bg.fillRect((int)(x-5),(int)(y-5),10,10); //ship

            double fg = (5*50000)/(Math.pow(dist(x,y,px,py),2));

            double m = (y-py)/(x-px);
            double ms = Math.sqrt(Math.abs(m));
            if (m < 0) ms = -ms;

            double xchg = fg;
            double ychg = fg*ms;

            if (x > px){
                xchg = -xchg;
                ychg = -ychg;
            }

            xvel += xchg;
            yvel += ychg;

            x += xvel;
            y += yvel;

            ptx.add((int)x);
            pty.add((int)y);

            i++;
        }
    }

    public static void main(String[] args){

        canvas = new Gravity();
        frame = new JFrame();
        frame.setSize(screenw, screenh);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(canvas);

        frame.setVisible(true);
    }


    public static double dist(double x1, double y1, double x2, double y2){
        double x = x2-x1;
        double y = y2-y1;
        return Math.sqrt((x*x)+(y*y));
    }
}

解决方案

General tips, in point form:

  1. Don't mix AWT (e.g. Canvas) with Swing (e.g. JFrame) components. Instead of the Canvas, use a JPanel and override paintComponent(Graphics) rather than paint(Graphics).
  2. Don't call Thread.sleep(n) on the EDT. Instead use a Swing based Timer to call repaint()
  3. Don't perform long running operations on the paint method, especially starting an infinite loop! Even the creation of the buffer image should only be done in the case the screen size changes. (left as 'TODO' - BNI)
  4. Add the MouseListener once in the constructor or an init() method rather than every time paint is called.
  5. Highly recommend all of Nate's numbered list of notes.

Try this code, and compare it carefully to the original to see the changes.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Dimension;
import java.awt.event.*;
import java.util.ArrayList;

import java.io.*;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.util.Random;

public class Gravity extends JPanel {

    public static final int screenw = 800;
    public static final int screenh = 600;

    public static Random gen = new Random();

    public static int[] starx = new int[100];
    public static int[] stary = new int[100];
    public static Color[] starc = new Color[100];

    public static Image buffer;
    public static Graphics bg;

    public static int[] xh = new int[1000];
    public static int[] yh = new int[1000];

    public static int i = 0;

    public static ArrayList<Integer> ptx = new ArrayList<Integer>();
    public static ArrayList<Integer> pty = new ArrayList<Integer>();
    double x = 100;
    double y = 100;

    Timer timer;

    public Gravity(){
        // set thre PREFERRED size!
        setPreferredSize(new Dimension(screenw, screenh));
        addMouseListener(new MouseListener(){
                    public void mouseClicked(MouseEvent e){
                        System.out.println("Mouse was clicked");
                        timer.start();
                    }

                    public void mouseEntered(MouseEvent arg0) {}
                    public void mouseExited(MouseEvent arg0) {}
                    public void mousePressed(MouseEvent arg0) {}
                    public void mouseReleased(MouseEvent arg0) {}
        });
        ActionListener animation = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                repaint();
            }
        };
        timer = new Timer(50, animation);
    }

    @Override
    public void paintComponent(Graphics g) {
        buffer = createImage(screenw, screenh);
        bg = buffer.getGraphics();

        int w = getWidth();
        int h = getHeight();

        double px = getWidth()/2;
        double py = getHeight()/2;

        bg.setColor(Color.BLACK);
        bg.fillRect(0, 0, w, h); //black background

        for (int j=0; j < 100; j++){ //make stars
            starx[j] = gen.nextInt(w);
            stary[j] = gen.nextInt(h);
            starc[j] = new Color(gen.nextInt(100)+156, gen.nextInt(100)+156, gen.nextInt(100)+156);
            bg.setColor(starc[j]);
            bg.drawLine(starx[j], stary[j], starx[j]+2, stary[j]+2);
            bg.drawLine(starx[j], stary[j]+2, starx[j]+2, stary[j]);
        }

        g.drawImage(buffer, 0, 0, null);

        double xvel = -15;
        double yvel = 10;

        for (int j=0; j < 100; j++){ //store stars
            starx[j] = gen.nextInt(w);
            stary[j] = gen.nextInt(h);
            starc[j] = new Color(gen.nextInt(100)+156, gen.nextInt(100)+156, gen.nextInt(100)+156);
        }

        Image test = createImage(200,200);
        Graphics testg = test.getGraphics();
        testg.drawLine(50,50,150,150);

        g.drawImage(buffer, 0,0, null);
        try {
            Thread.sleep(33);
        } catch (Exception e) {
            e.printStackTrace();
        }

        bg.setColor(Color.BLACK);
        bg.fillRect(0, 0, w, h); //black background


        for (int j=0; j < 100; j++){ //draw stars
            bg.setColor(starc[j]);
            bg.drawLine(starx[j], stary[j], starx[j]+2, stary[j]+2);
            bg.drawLine(starx[j], stary[j]+2, starx[j]+2, stary[j]);
        }

        bg.setColor(Color.BLUE);

        if (i > 0){
            for (int z=0; z < i-1; z++){
                bg.drawLine(ptx.get(z), pty.get(z), ptx.get(z+1), pty.get(z+1));
            }
        }

        bg.setColor(Color.CYAN);
        bg.fillOval((int)px, (int)py, 25, 25); //planet

        bg.setColor(Color.RED);
        bg.fillRect((int)(x-5),(int)(y-5),10,10); //ship

        double fg = (5*50000)/(Math.pow(dist(x,y,px,py),2));

        double m = (y-py)/(x-px);
        double ms = Math.sqrt(Math.abs(m));
        if (m < 0) ms = -ms;

        double xchg = fg;
        double ychg = fg*ms;

        if (x > px){
            xchg = -xchg;
            ychg = -ychg;
        }

        xvel += xchg;
        yvel += ychg;

        x += xvel;
        y += yvel;

        ptx.add((int)x);
        pty.add((int)y);

        i++;
    }

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();

                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().add(new Gravity());
                frame.setResizable(false);
                frame.pack();

                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        });
    }


    public static double dist(double x1, double y1, double x2, double y2){
        double x = x2-x1;
        double y = y2-y1;
        return Math.sqrt((x*x)+(y*y));
    }
}

这篇关于在MouseListener的画布不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆