如何从另一个类更改Java中框架的背景颜色?

时间:2010-02-05 18:08:52

标签: java swing jpanel keyevent

我有以下内容:

import javax.swing.JFrame;

public class Directions {

    public Directions(){
        JFrame frame = new JFrame("Direction");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new DirectionPanel());
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        Directions myTest = new Directions();
    }
}

第二课:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DirectionPanel extends JPanel{
    public DirectionPanel(){
        addKeyListener(new DirectionListener());
        setBackground(Color.yellow);
    }

    private class DirectionListener implements KeyListener{

        @Override
        public void keyPressed(KeyEvent e) {
            //JOptionPane.showMessageDialog(null, "Hello Johnny");
            int keyCode = e.getKeyCode();
            if (keyCode == KeyEvent.VK_LEFT){
                setBackground(Color.red);
            }
            repaint();
        }

        @Override
        public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void keyTyped(KeyEvent e) {
            // TODO Auto-generated method stub
        }
    }
}

为什么当我按下左箭头时框架没有变红?我也没有密钥代码测试,认为无论密钥是什么,它都没有。谢谢。

2 个答案:

答案 0 :(得分:6)

public DirectionPanel(){
   addKeyListener(new DirectionListener());
   setFocusable(true);// INSERT THIS
   setBackground(Color.yellow);
}

JPanel需要专注于接收KeyEvents

答案 1 :(得分:3)

Swing组件应该使用Key Bindings(而不是KeyListeners)来在使用键盘时调用Action。这样做的另一个好处就是您不必担心可聚焦性。

Action left = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        System.out.println( "Left" );
    }
};

Object key1 = "left";
KeyStroke ks1 = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
panel.getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks1, key1);
panel.getActionMap().put(key1, left);