Java Mouselistener未添加

时间:2015-02-01 23:12:02

标签: java swing mouseevent mouselistener

我创建了一个基本上是我游戏的GUI的新游戏类。我想添加一个mouselistener,以便我可以检查用户何时点击不同的东西。但是,我努力让基础工作起作用。这是我到目前为止所拥有的。游戏类明显更复杂但工作正常,只有mouselistener没有。游戏本身基本上是一个有很多不同形状的大广场。

public class Game extends JPanel {
public Game() {

f = new JFrame();

f.getContentPane().addMouseListener(new MouseAdapter() {


        @Override
        public void mousePressed(MouseEvent e) {
            System.out.println(e.getX() + " " + e.getY());

        }

    });

或者我已尝试将mouselistener添加到Game类中,但这也没有。

1 个答案:

答案 0 :(得分:1)

查看How to Write a Mouse Listener

下面的示例更多的是向MouseListener添加JPanel,跟踪MouseEvent发生的点并相应地重新绘制组件。

Click

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Point clickPoint;

        public TestPane() {
            addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    clickPoint = e.getPoint();
                    repaint();
                }

            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (clickPoint != null) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.fillOval(clickPoint.x - 5, clickPoint.y - 5, 10, 10);
                g2d.dispose();
            }
        }

    }

}

现在也许你想提供一个runnable example来证明你的特殊问题。