请大家帮忙看看这个键盘的问题,谢谢。
大家好:
我想问一下,如果我在一个Frame中,添加了两个panel,其中一个panel被命名为controlpanel,在其中放置一个按钮,并将其放入
到Frame的South位置。而另外一个按钮被命名为canvaspanel,专门用来画图使用,放置在Frame的Center处,并且该canvaspanel也
实现了KeyListener接口,其中的keypressed办法是当按键为VK_RIGHT时就在canvaspanel中draw一个字符串,如
drawString("hello",20,20)。
那么,如果我点击了controlpanel中的按钮之后,是否有方法让canvaspanel接受键盘消息呢?请大家看一看。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CanvasPanel extends JPanel implements KeyListener{
public CanvasPanel()
{
setBackground(Color.WHITE);
addKeyListener(this);
}
public void keyPressed(KeyEvent e)
{
Graphics g=getGraphics();
int keycode=e.getKeyCode();
if(keycode==KeyEvent.VK_RIGHT){
g.drawString("hello,yes",20,20);
}
}
class ControlPanel extends JPanel implements ActionListener{
private int button;
public ControlPanel()
{
button=new JButton("Start");
button.addActionListener(this);
this.add(button);
}
public void actionPerformed(ActionEvent e){
Object source;
source=e.getSource();
if(source==button){
//此处该填什么,才能使CanvasPanel接受键盘消息?
}
}
}
class MyFrame extends JFrame{
public MyFrame()
{
setTitle("Hello Title");
setSize(300,200);
Container contentpane = this.getContentPane();
contentpane.add(new ControlPanel(),"South");
contentpane.add(new CanvasPanel();,"Center");
}
}
public class KeyTest{
public static void main(String[] args)
{
JFrame frame=new MyFrame();
frame.show();
}
}