在JFrame中进行关键事件 [英] Making a keyevent in a JFrame

查看:90
本文介绍了在JFrame中进行关键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个关键,使JFrame中发生某些事情.现在,我只是想在按左键时禁用一个按钮,但是什么也没发生.我以为我没事,但是什么也没做.

I'm trying to make a key make something happen in a JFrame. Right now I'm just trying to disable a button when you press the left key, but nothing is happening. I thought I have everything right, but it does nothing.

我注意到,当我不首先单击开始时,它就可以工作.但是按下开始键后,它将不会响应.

I noticed that when I don't click start first, it works. But after you press start, it won't respond.

到目前为止,这是我的代码:

Here's my code so far:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;



public class MyFrame extends JFrame implements ActionListener, KeyListener
{
private static final long serialVersionUID = 1L;
private JPanel p1;
private JButton b1, b2;
private JLabel lb1;
private int a;
private Font font = new Font("Arial", Font.BOLD, 20);


public MyFrame()
{
    setLayout(new FlowLayout());
    setSize(700,600);
    setVisible(true);
    setResizable(false);
    addKeyListener(this);
    setFocusable(true);

    p1 = new JPanel(); add(p1);
    p1.setBackground(Color.BLACK);
    p1.setPreferredSize(new Dimension(650,500));
    p1.setFocusable(true);
    b1 = new JButton("Start"); add(b1);
    b1.addActionListener(this);
    b2 = new JButton("Test"); add(b2);
    b2.setFocusable(true);

    setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent event)
{
    Graphics g = p1.getGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(30, 210, 10, 70);
    g.fillRect(620, 210, 10, 70);
    for(int i=0; i<7; i++)
    {
        g.fillRect(325, a, 10, 70);
        a += 90;
    }
    g.setFont(font);
    g.drawString("Player 1: ", 120, 20);
    g.drawString("Player 2: ", 450, 20);
}

public void keyPressed(KeyEvent e) 
{
    int d = e.getKeyCode();
    if(d==KeyEvent.VK_LEFT)
    {
        b2.setEnabled(false);
    }
}

public void keyReleased(KeyEvent e) 
{


}

public void keyTyped(KeyEvent e) 
{


}

}

这是我的Main.java文件:

And here's my Main.java file:

public class Main { 
public static void main(String[] arg)
{
    MyFrame mf = new MyFrame();
}

}

推荐答案

您忘记告诉JFrame它应该使用以下代码行来监听键:addKeyListener(this);

You forgot to tell the JFrame that it should be listening for keys with this line of code:addKeyListener(this);

这篇关于在JFrame中进行关键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆