Java:如何通过单击箭头键来删除特定的JPanel?

时间:2012-01-31 05:30:25

标签: java swing jpanel key-bindings keylistener

这是我创建图形文本的内部类。我希望能够按箭头键让它消失。我确定它以某种方式涉及删除方法,但我在我的脑海中。非常新的。

// 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);
    }

2 个答案:

答案 0 :(得分:4)

AFAIK您必须使用Key Bindings来回复箭头键然后删除面板(我想从框架中)使用面板的setVisible(false)或框架的remove(component)方法。

答案 1 :(得分: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);

        }

    }