“我的偵聽器”已添加到“J 框架/”小面板“中。問題是,當我按下按鈕時,什么也沒發生。這里可能有什么問題?以下是使用的代碼:public class GAMEGAMEHA extends JPanel{ public static JFrame PacmanMainFrame = new JFrame(); TheJGame newGame; GAMEGAMEHA() { setSize(new Dimension(1200, 700)); JLabel BG = new JLabel(); JButton start = new JButton(); JButton howTo = new JButton(); JButton credit = new JButton(); JButton exit = new JButton(); setLayout(null); start.setIcon(new ImageIcon(getClass().getResource("/data/SB.png"))); start.setContentAreaFilled(false); start.addActionListener((ActionEvent e) -> { newGame = new TheJGame(); GAMEGAMEHA.PacmanMainFrame.getContentPane().removeAll(); System.out.println("Removed Components"); GAMEGAMEHA.PacmanMainFrame.add(newGame); System.out.println("Added Game"); GAMEGAMEHA.PacmanMainFrame.addKeyListener(newGame); System.out.println("Added KeyListeners"); GAMEGAMEHA.PacmanMainFrame.setVisible(true); System.out.println("Set Visiblity to True"); }); start.setBorderPainted(false); add(start); start.setBounds(440, 140, 300, 70); howTo.setIcon(new ImageIcon(getClass().getResource("/data/HowToButton.jpg"))); howTo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e ) { HowTo HowToScreen = new HowTo(); GAMEGAMEHA.PacmanMainFrame.getContentPane().removeAll(); GAMEGAMEHA.PacmanMainFrame.add(HowToScreen); GAMEGAMEHA.PacmanMainFrame.setVisible(true); } });這是游戲開始的:問題就在這里。主菜單很好,但去這里時,它不接受也不讀取任何密鑰。
2 回答

犯罪嫌疑人X
TA貢獻2080條經驗 獲得超4個贊
主要問題
“主要”問題是,對于在Swing中監視鍵盤輸入是一個糟糕的選擇,它存在焦點問題,其中它注冊的組件必須是可聚焦的并且具有鍵盤焦點,并且由于您要向UI添加按鈕,因此它們將從組件中竊取焦點。KeyListener
一個更好的整體解決方案是使用鍵綁定 API,它為您提供了控制,以確定應在哪個焦點級別觸發綁定
其他問題...
null
眾所周知,布局難以管理和維護。有很多因素可以確定組件在屏幕上的最佳顯示方式。您應該盡可能避免布局,并使用一個或多個布局管理器,它們將節省大量頭發null
你已經覆蓋了,但你未能尊重油漆鏈(通過不調用)。繪畫是一個復雜的過程,由許多步驟組成。paint
super.paint
作為一般規則,您應該覆蓋(并在進行任何自定義繪制之前調用)。paintComponent
super.paintComponent
閱讀AWT中的繪畫和搖擺和執行自定義繪畫,以獲取有關在搖擺中繪畫的更多詳細信息

UYOU
TA貢獻1878條經驗 獲得超4個贊
您沒有將鍵偵聽器添加到JPnael中,僅僅實現接口是不夠的,您必須將其添加到面板中。
addKeyListner(this);
將此行代碼添加到構造函數中。
添加回答
舉報
0/150
提交
取消