用java编写程序,读取键盘输入的字符并将其显示到鼠标所指的位置。
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Demo1 extends JFrame implements
MouseMotionListener,KeyListener,MouseListener {
private JPanel content;
private JPanel bottom;
private JLabel show;
static String keyCode="";
public Demo1(){
content=new JPanel();
content.setLayout(null);
show=new JLabel();
show.setForeground(Color.white);
bottom=new JPanel();
content.setBounds(0, 0, 800, 600);
content.setBackground(Color.black);
content.add(show);
content.setFocusable(true);
content.addKeyListener(this);
content.addMouseMotionListener(this);
content.addMouseListener(this);
setTitle
("读取键盘输入的字符并将其显示到鼠标所指的位置");
setSize(800, 600);
setLocationRelativeTo(getOwner());
add(content);
add(bottom);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
keyCode+=String.valueOf((char)e.getKeyCode());
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
new Demo1();
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
if(keyCode!=""){
show.setText(keyCode);
show.setBounds(e.getX()+20, e.getY(), 800, 30);
}
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
keyCode="";
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}