¿Cómo puedo cambiar el color de fondo de una trama en Java desde otra clase?
Pregunta
Tengo el siguiente:
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();
}
}
segunda clase:
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
}
}
}
¿Por qué el marco de color rojo cuando llegué a la flecha hacia la izquierda? También tuve que sin pensar código clave de prueba que no importa la clave que iba a funcionar pero no fue así. Gracias.
Solución
public DirectionPanel(){
addKeyListener(new DirectionListener());
setFocusable(true);// INSERT THIS
setBackground(Color.yellow);
}
JPanel
necesita ser enfocable para recibir KeyEvents
Otros consejos
Los componentes Swing deben usar Key Bindings (no KeyListeners) para invocar una acción cuando se utiliza el teclado. Un beneficio adicional de esta manera es que usted no tiene que preocuparse por focusability.
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);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow