【发布时间】:2015-07-30 05:56:24
【问题描述】:
编辑: 我有一个应用程序,它使用摇摆定时器来控制动作监听器接口何时触发。鼠标逻辑有效,但偶尔不会检测到点击。下面是我的注释代码。
public class Board extends JPanel implements MouseListener, MouseMotionListener, ActionListener
{
private MainMenu mainMenu = new MainMenu();
private static String State; /*Makes the control flow simpler, just checking
strings that describe the state. All the states are contained in GameState class.*/
public Board()
{
this.addMouseListener(this);
this.addMouseMotionListener(this);
setVisible(true);
mainMenu.initLogIn(); /*This just loads the button images*/
Timer timer = new Timer(12, this); /*(millisecond delay, tells this class
to update any actionlistener (mouselistener etc)*/
timer.start();
}
public void paint(Graphics G)
{
super.paint(G);
Graphics G2d = (Graphics2D)G;
/*Main menu paint logic*/
// This paints buttons from mainMenu class on screen
G.drawImage(mainMenu.getTopic1().getspriteImage(),
mainMenu.getTopic1().getxCoord(),
mainMenu.getTopic1().getyCoord(),this);
G.drawImage(mainMenu.getTopic2().getspriteImage(),
mainMenu.getTopic2().getxCoord(),
mainMenu.getTopic2().getyCoord(), this);
G.drawImage(mainMenu.getTopic3().getspriteImage(),
mainMenu.getTopic3().getxCoord(),
mainMenu.getTopic3().getyCoord(),this);
/*Shows mouse input worked by changing the background color*/
if (State == GameState.MAINMENU_TOPIC1)
{
setBackground(Color.BLACK);
}
if (State == GameState.MAINMENU_TOPIC2)
{
setBackground(Color.BLUE);
}
if (State == GameState.MAINMENU_TOPIC3)
{
setBackground(Color.GRAY);
}
repaint(); //tells paint to repaint, which allows gui to update
}
@Override
public void mouseClicked(MouseEvent e)
{
Point point = e.getPoint();
/*This contains the logic to change State based on mouse clicks*/
if(mainMenu.getTopic1().getRectangle().contains(point))
{
State = GameState.MAINMENU_TOPIC1;
}
if(mainMenu.getTopic2().getRectangle().contains(point))
{
State = GameState.MAINMENU_TOPIC2;
}
if(mainMenu.getTopic3().getRectangle().contains(point))
{
State = GameState.MAINMENU_TOPIC3;
}
}
所以,我不确定为什么不会始终检测到鼠标点击。我知道分配给更新动作侦听器的时间可能太短了。但是,机器循环的代码并不多,所以我认为这不是问题。关于什么可能导致鼠标以这种方式表现的任何想法?
另外,我稍后肯定会使用 JButtons 来实现它。我相信这将有助于清理我在更大项目中的代码
感谢 cmets,我希望这能解决大部分问题。
【问题讨论】:
-
"This loops between my mouse logic, actionPerformed, and paint methods (if I understand this correctly)."-- 这让我感到奇怪和困惑。如果你没有很快得到答案,或者即使你得到了答案,请更详细地解释你的程序正在做什么以及你的问题是什么。 -
你能定义“跳过点击”吗?你的意思是不响应每次点击?计时器非常快(每毫秒?),并且发布的代码甚至无法真正尝试重现,更不用说猜测问题了。建议发MCVE
-
另外,你巨大的总机 MouseListener 看起来像噩梦一样(对不起,我直言不讳,但我必须按照我的看法来称呼它)。为什么不简单地在 JButtons 上使用单独的 ActionListener?
-
@HovercraftFullOfEels 我肯定会扩展程序正在做什么,可能通过 copeg 建议的 MVCE。也无需道歉,我总是欣赏建设性的批评。我是编程新手,所以我会尽我所能!
-
顺便说一句,我想知道您是否最好将 JPanel 与 CardLayout 交换,每个 JPanel 绘制不同的背景并具有不同的行为,而不是像您那样交换图像。如果您正在显示具有截然不同的行为的视图,例如菜单 JPanel 和游戏 JPanel,我当然建议您采用这条路线。