[英]Enable only mouse event over a jbutton - Disable keyboard event for jbutton
我有個問題。 我創造了一個游戲。 當我打開它時,我必須按Enter鍵才能開始游戲(只需輸入)。 現在,我用一個名為“退出游戲”的按鈕升級了游戲。 我不知道為什么我的Enter鍵由於這個按鈕而不再起作用。 如果我將其刪除,則可以再次按Enter鍵並玩游戲。
我必須將“僅單擊事件”設置為該按鈕或類似的東西? 請幫我。
public class LeftPanel extends JPanel implements ActionListener {
JButton ExitGame;
public LeftPanel(Tetris tetris) {
this.tetris = tetris;
setPreferredSize(new Dimension(400, 480));
setBackground(Color.getHSBColor(17f, 0.87f, 0.52f));
add(new JButton("Exit Game"));
{
ExitGame.addActionListener(this);
}
}
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
問題1- JButton
是UI中唯一可聚焦的組件。 因此,當您開始編程時,它將獲得默認焦點。 雖然具有默認焦點。 它將消耗Enter鍵。
問題2- JPanel
無法聚焦,這意味着它永遠無法獲得鍵盤聚焦。 根據您的描述,我假設您使用的是KeyListener
,這會導致
問題3-使用KeyListener
... KeyListener
僅在其注冊到的組件可聚焦並具有焦點時才響應鍵事件。 您可以使用Key Bindings克服這一點。
...解決方案...
JLabel
而不是JButton
。 這將需要您在標簽上注冊一個MouseListener
,以接收有關鼠標單擊的通知,但它不會響應按鍵事件。 你可以試試:
public class LeftPanel extends JPanel implements ActionListener {
public LeftPanel(Tetris tetris) {
this.tetris = tetris;
setPreferredSize(new Dimension(400, 480));
setBackground(Color.getHSBColor(17f, 0.87f, 0.52f));
JButton ExitGame = new JButton("Exit Game");
ExitGame.addActionListener(this);
ExitGame.setActionCommand("Exit");
add(ExitGame );
}
public void actionPerformed(ActionEvent e) {
if("Exit".equals(e.getActionCommand())
System.exit(0);
}
}
這行看起來像語法錯誤:
add(new JButton("Exit Game"));
{
ExitGame.addActionListener(this);
}
我認為應該是這樣的:
ExitGame= new JButton("Exit");
this.add(ExitGame);
ExitGame.addActionListener(this);
我沒有測試過,但是我認為通過一些調整,您應該能夠使它完成您想要的操作。 希望能成功!
-坦率
public void actionPerformed(ActionEvent e) {
if("Exit".equals(e.getActionCommand())
System.exit(0); }
由於ActionlListener既可以由鼠標也可以由鍵盤觸發,但是現在用戶只想響應鼠標事件,因此將動作偵聽器更改為mouselistener。 經過測試並通過。
public class LeftPanel extends JPanel implements ActionListener {
JButton ExitGame;
public LeftPanel(Tetris tetris) {
this.tetris = tetris;
setPreferredSize(new Dimension(400, 480));
setBackground(Color.getHSBColor(17f, 0.87f, 0.52f));
ExitGame= new JButton("Exit Game")
add(ExitGame);
ExitGame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.