如何从另一个类更改 Java 中框架的背景颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2209315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I change the background color of a frame in Java from another class?
提问by johnny
I have the following:
我有以下几点:
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();
}
}
second class:
第二类:
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
}
}
}
Why doesn't the frame turn red when I hit the left arrow? I also had it with no keycode test thinking that no matter the key it would work but it did not. Thank you.
为什么我点击左箭头时框架没有变红?我也有它,没有键码测试,认为不管它是什么键它都可以工作,但它没有。谢谢你。
回答by Erkan Haspulat
public DirectionPanel(){
addKeyListener(new DirectionListener());
setFocusable(true);// INSERT THIS
setBackground(Color.yellow);
}
JPanelneeds to be focusable to receive KeyEvents
JPanel需要可聚焦才能接收 KeyEvents
回答by camickr
Swing components should use Key Bindings(not KeyListeners) for invoking an Action when the keyboard is used. A side benefit of this is that way you don't have to worry about focusability.
当使用键盘时,Swing 组件应该使用键绑定(而不是 KeyListener)来调用操作。这样做的一个附带好处是您不必担心可聚焦性。
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);

