如何从另一个类更改 Java 中框架的背景颜色?
我有以下内容:
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
}
}
}
为什么当我点击向左箭头时框架不会变成红色?我也没有进行键码测试,认为无论使用什么键它都可以工作,但事实并非如此。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JPanel
需要可聚焦才能接收 KeyEventsJPanel
needs to be focusable to receive KeyEventsSwing 组件应使用 按键绑定(而不是 KeyListeners)来调用使用键盘时的操作。这样做的一个附带好处是您不必担心对焦能力。
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.