3

This is my inner class that creates the graphic text. I want to be able to press an arrow key and have it disappear. I'm sure it involves the remove method somehow, but I'm in over my head. Very new at this.

// STARTUP TEXT

class TextPanel extends JPanel implements KeyListener{

    // CONSTRUCTOR
    public TextPanel(){
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
    }

    // PAINT METHOD
    public void paintComponent(Graphics g2){
        super.paintComponent(g2);
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, this.getWidth(), this.getHeight());
        g2.setColor(Color.BLACK);
        g2.setFont(new Font("TimesRoman", Font.PLAIN, 14));
        g2.drawString("Press an arrow key to start", this.getWidth()/4, this.getHeight()/2);
    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Jazzertron
  • 63
  • 6

2 Answers2

4

AFAIK You have to use Key Bindings to respond to arrow key then to remove panel (I think from frame) use either setVisible(false) of panel or remove(component) method of frame.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
2
/** Handle the key typed event  */
    public void keyTyped(KeyEvent e) {

    }

    /** Handle the key-pressed event  */
    public void keyPressed(KeyEvent e) {

    }

    /** Handle the key-released event  */
    public void keyReleased(KeyEvent e) {
    int key=e.getKeyCode();
        if(key==KeyEvent.VK_LEFT)
        {

            this.setVisible(false);

        }
        if(key==KeyEvent.VK_RIGHT)
        {

            this.setVisible(true);

        }

    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Prateek Sharma
  • 346
  • 3
  • 12
  • +1, though normally with Swing we don't use KeyEvent, they are meant to be used with AWT, but since it's a valuable information you had given, that's why :-) Regards – nIcE cOw Jan 31 '12 at 07:40