gpt4 book ai didi

java - 我的 MouseWheelListener 不起作用

转载 作者:行者123 更新时间:2023-12-01 23:51:30 25 4
gpt4 key购买 nike

我正在开发一个游戏,但我发现我的 MouseWheelListener 不起作用。我简化了代码以使问题更清晰。

首先,在窗口显示后,单击Go In。然后旋转鼠标滚轮,什么也没发生! 我该如何解决这个问题?

为了表明我没有犯一个非常愚蠢的错误,请最小化和最大化您的窗口或单击不执行任何操作(根本不执行任何操作)并再次旋转鼠标滚轮,然后打印正常!

我使用的是 Windows 7 SP1 和 JavaSE-1.6 64 位。

这是我的简化代码,存在问题:

ControllerPane.java

import java.awt.*;
import javax.swing.*;
public class ControllerPane extends JPanel {
private static final long serialVersionUID = 1L;
public static final String PAGE_MAIN = "MAIN";
public static final String PAGE_LEVEL = "LEVEL";
private CardLayout layout;
public ControllerPane() {
setLayout(layout = new CardLayout());
add(new MainPane(), PAGE_MAIN);
add(new LevelPane(), PAGE_LEVEL);
}
public void setPage(String page) {
layout.show(this, page);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame();
f.add(new ControllerPane());
f.setSize(316, 338);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
});
}
}

MainPane.java

import java.awt.event.*;
import javax.swing.*;
public class MainPane extends JPanel {
private static final long serialVersionUID = 1L;
public MainPane() {
setLayout(null);
JButton btnStartGame = new JButton("Go In");
btnStartGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
((ControllerPane) getParent())
.setPage(ControllerPane.PAGE_LEVEL);
}
});
btnStartGame.setBounds(50, 50, 200, 200);
add(btnStartGame);
}
}

LevelPane.java

import java.awt.event.*;
import javax.swing.*;
// FIXME mouseWheelMoved
public class LevelPane extends JPanel {
private static final long serialVersionUID = 1L;
public LevelPane() {
addMouseWheelListener(new DrawListener());
setLayout(null);
JButton btnRetry = new JButton("Do nothing");
btnRetry.setBounds(50, 50, 200, 200);
add(btnRetry);
}
private class DrawListener extends MouseAdapter {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
System.out.println(e);
}
}
}

最佳答案

这是一个焦点问题。由于某种原因,面板需要具有焦点,以便能够处理鼠标事件。您可以通过单击“不执行任何操作”按钮并旋转鼠标滚轮来使用当前代码进行测试...

要修复此问题,您需要在新激活的面板上调用requestFocusInWindow。问题是 CardLayout 无法让您访问当前的卡片...

无论如何,将所有其他卡设置为不可见,这意味着如果我们查找可见卡,您应该能够对其调用requestFocusInWindow...

public void setPage(String page) {
layout.show(this, page);
for (Component comp : getComponents()) {
if (comp.isVisible()) {
System.out.println("Activate " + comp);
comp.requestFocusInWindow();
break;
}
}
}

关于java - 我的 MouseWheelListener 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16250245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com