Key Interaction (with Swing and AWT UI)

Define the Panel

public class MyKeyInteractionPanel extends JPanel { private int x = 0; public MyKeyInteractionPanel( ) { this.setBackground(Color.blue); // Map the space bar key press event to the action object PressSpaceAction pressSpaceAction = new PressSpaceAction(); this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false), "pressSpace"); this.getActionMap().put("pressSpace", pressSpaceAction ); } public void paint (Graphics gra) { Graphics2D g = (Graphics2D) gra; super.paint(g); g.setPaint(Color.black); g.setFont(new Font("Serif",Font.PLAIN,40)); // Example to display our variable x which will be changed with the key press g.drawString("Press Space Bar: " + x, 20,50); } // Define the action to be performed when key is pressed public class PressSpaceAction extends AbstractAction { @Override public void actionPerformed (ActionEvent ae) { x += 1; // Change variable x repaint(); // Update the display } } }

- This panel should display the text "Press Space Bar: " followed by the number of times it has been pressed

- Import these from java.awt: event.ActionEvent, event.KeyEvent, Color, Font, Graphics, Graphics2D

- Import these from javax.swing: AbstractAction, KeyStroke, JPanel

- When assigning the KeyStroke in the InputMap, you can change 'false' to 'true' for activation on key release

- When assigning the KeyStroke in the InputMap, you can change 0 to InputEvent.SHIFT_DOWN_MASK for shift+key

Set up the display window

MyKeyInteractionPanel myPanel = new MyKeyInteractionPanel (); myPanel.setPreferredSize( new Dimension(400,400) ); JFrame myFrame = new JFrame(); myFrame.add(myPanel); myFrame.pack(); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setVisible(true); myFrame.setLocationRelativeTo(null);

- The same as in the graphics lessons, just using the new panel

Completed