【问题标题】:Translate mouse coordinates to child panel将鼠标坐标转换为子面板
【发布时间】:2019-11-01 12:14:44
【问题描述】:

我正在创建简单的 Java 游戏,每个游戏状态都有单独的 JPanel。在下面的代码中,它们隐藏在AbstractPanel 下。但我在顶部面板上有键/鼠标监听器 (Game)。

不幸的是,当我尝试在 currentPanel 子面板上使用来自 Game 的鼠标坐标时,子面板上的组件过早突出显示,例如当鼠标光标位于 90,90 时,位于 100,100 的 JButton 会突出显示。有没有办法将坐标从父面板转换为子面板?

public class Game extends JPanel implements KeyListener, MouseListener, MouseMotionListener {

    private static final int WIDTH = 1024;
    private static final int HEIGHT = 768;

    private AbstractPanel currentPanel = null;

    public Game() {

        Dimension gameSize = new Dimension( WIDTH, HEIGHT );
        menuPanel.setSize( gameSize );
        menuPanel.setPreferredSize( gameSize );
    }

    public static void main( String[] args ) {

        Game game = new Game();
        game.setLayout( new BorderLayout() );
        Dimension gameSize = new Dimension( WIDTH, HEIGHT );

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
        frame.getContentPane().setLayout( new BorderLayout() );
        frame.getContentPane().add( game, BorderLayout.CENTER );
        frame.setSize( gameSize );
        frame.setPreferredSize( gameSize );
        frame.setLocationRelativeTo( null );
        frame.addKeyListener( game );
        frame.addMouseListener( game );
        frame.addMouseMotionListener( game );
        frame.setVisible( true );
    }

    public void mouseClicked( MouseEvent e ) {

        currentPanel.mousePressed( e );
        repaint();
    }

【问题讨论】:

标签: java swing mouseevent


【解决方案1】:

如果其他人需要答案,这是我的更新:主类中的鼠标方法正在传递父级JFrame,如下所示:

    public void mouseClicked( MouseEvent e ) {

        currentPanel.mousePressed( frame, e );
        repaint();
    }

在子面板中,这些侦听器从转换开始:

    @Override
    public void mousePressed( Container source, MouseEvent e ) {

        String newItem = null;
        Point clickPoint = SwingUtilities.convertPoint( source, e.getX(), e.getY(), this );
        // some code here
        if( bounds.contains( clickPoint ) ) {
        // some more code here

感谢以上评论中的Carlos Heuberger

【讨论】:

    猜你喜欢
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    相关资源
    最近更新 更多