簡體   English   中英

Java Swing JFrame突然停止響應鼠標輸入,但仍然需要鍵盤輸入

[英]Java Swing JFrame suddenly stops responding to mouse input, but still takes keyboard inputs

我有一個游戲,它使用一個顯示游戲信息的JFrame。 只要玩家將移動對象發送到服務器,窗口就會更新。 它適用於任何數量的移動對象。 然而,一旦第3次轉彎開始它撞到一堵牆,這就是發生的事情:

  • Jframe完全停止響應鼠標左鍵和右鍵(當您嘗試單擊時,它會發出窗口響聲)
  • JFrame仍然響應鼠標滾動和鍵盤輸入
  • JFrame從alt-tab程序列表中消失。
  • 沒有錯誤消息或堆棧跟蹤。
  • 使用souts似乎代碼正確地到達了所有必要代碼點
  • 我甚至無法單擊“X”窗口按鈕或右鍵單擊任務欄上的關閉
  • 第3轉彎對象在結構上與先前的轉彎對象相同

究竟是什么導致程序這樣做?

事件派發線程拋出異常。 它會自動重新啟動,但您的程序仍處於您描述的狀態。 另請參見如何捕獲事件調度線程(EDT)異常和此答案

附錄: 如何處理 未捕獲的異常,GUI應用程序中的未捕獲異常可能會有所幫助。 還要檢查空的異常處理程序。

附錄:這是一個例子。

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

/** @see https://stackoverflow.com/a/9935287/230513 */
public class Fail extends JPanel {

    private static final JLabel label = new JLabel(
        "12345678901234567890", JLabel.CENTER);

    public Fail() {
        this.setLayout(new GridLayout(0, 1));
        this.add(label);
        this.add(new JButton(new AbstractAction("Kill me, now!") {

            @Override
            public void actionPerformed(ActionEvent e) {
                JButton b = (JButton) e.getSource();
                b.setText(String.valueOf(1 / 0));
            }
        }));
        new Timer(100, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                label.setText(String.valueOf(System.nanoTime()));
            }
        }).start();
    }

    private void display() {
        JFrame f = new JFrame("Example");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Fail().display();
            }
        });
    }
}

檢查您的幀類是否不重寫isEnabled()方法。 我花了幾個小時搜索異常,但響應非常簡單:我用這種方法實現了接口。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM