0

Quick simple question: I have a JPanel with JButtons. I've attached ActionListeners to the buttons and a KeyListener to the panel. Even if I try to set the focus on the panel, there's no response to the key presses.

So I experimented and attached the KeyListener to the buttons, too, and normal operation was restored.

Is this the design of Java, to attach the KeyListener to each component, or am I missing something elementary?

Quick example program, Escape exits, button clicks exchange button text.

// imports from javax.swing
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;

// imports from java.awt.event
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

public class Example implements ActionListener, KeyListener {

    // Frame variables
    private JFrame frame = new JFrame ();
    private JPanel mainPanel = new JPanel ();

    // Buttons
    private JButton thisButton = new JButton ("this"),
        thatButton = new JButton ("that");

    public static void main (String [] args) {

        new Example ();
    }

    public Example () {

        mainPanel.add (thisButton);
        mainPanel.add (thatButton);

        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.add (mainPanel);
        frame.pack ();
        frame.setLocationRelativeTo (null);
        frame.setVisible (true);

        // addition of Listeners
        frame.addKeyListener (this);
        thisButton.addActionListener (this);
        thatButton.addActionListener (this);
        thisButton.addKeyListener (this);
        thatButton.addKeyListener (this);

        frame.requestFocus ();
    }

// ActionListener override
    @Override
    public void actionPerformed (ActionEvent e) {
        String holdString;

        holdString = thisButton.getText ();
        thisButton.setText (thatButton.getText ());
        thatButton.setText (holdString);
    }

// KeyListener overrides
    @Override
    public void keyPressed (KeyEvent e) {}

    @Override
    public void keyReleased (KeyEvent e) {}

    @Override
    public void keyTyped (KeyEvent e) {

            if (e.getKeyChar () == KeyEvent.VK_ESCAPE) {
                System.exit (0);
            }
    }

}
failure
  • 215
  • 1
  • 3
  • 12

0 Answers0