简体   繁体   中英

I can't use ActionListener and KeyListener in the same time

I would like to create the simple window where one button will be. When I will press him is supposed to be printed out "test" and when I will press F5 "F5". I don't know what I am doing badly I apologize for my English I still studying

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class Okienko extends JFrame implements ActionListener , KeyListener
{
    static Okienko frame;

    JButton bTest;

    public Okienko() 
    {
        setLayout(null);
        frame = this;
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setTitle("test");
        frame.setLocation(150, 150);
        frame.setSize(200, 400);


        bTest = new JButton("Test");
        bTest.setBounds(20, 50, 120, 20);
        frame.add(bTest);

        bTest.addActionListener(this);

        frame.addKeyListener(this);
        //frame.setFocusable(false);
        //frame.requestFocus();
        requestFocusInWindow();
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        Object source = e.getSource();

        if (source == bTest)
        {
            System.out.println("Test");
        } 
    }

    @Override
    public void keyPressed(KeyEvent e)
    {
        int id = e.getKeyCode();

        if (id == KeyEvent.VK_ESCAPE)
        {
            this.dispose();
        }

        if (id == KeyEvent.VK_F5)
        {
            System.out.println("F5");
        }

    }

    @Override
    public void keyReleased(KeyEvent e)
    {

    }

    @Override
    public void keyTyped(KeyEvent e)
    {

    }
    public static void main(String[] args)
    {
        new Okienko();
    }

}

For example, you can enable keyboard focus for a component by calling the setFocusable(true) method on it. Add in constructor:

   setFocusable(true);

More info here: https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

add

btest.setFocusable(false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM