我在一个窗口中添加了一个面板,上面有一个文本框,我得目的是当鼠标在面板上移动时在文本框中显示当前鼠标的x,y坐标,我的代码是这样的:(请注意注释的地方!)import java.awt.*;
import java.awt.event.*;
class KeyPress extends Frame
{
Panel p1=new Panel();
TextField txt1=new TextField(20);
KeyPress(String title)
{
super(title);
add(p1);
p1.setLayout(new FlowLayout());
p1.addKeyListener(new kEvent());
p1.add(txt1);
p1.addMouseMotionListener(new mMotion());
}
class kEvent extends KeyAdapter
{
public void keyTyped(KeyEvent e)
{
if(e.getKeyChar()=='x' || e.getKeyChar()=='X')
System.exit(0);
}
public void keyPressed(KeyEvent e)
{
p1.setBackground( Color.gray);
repaint();
}
public void keyReleased(KeyEvent e)
{
p1.setBackground( Color.yellow);
repaint();
}
}
class mMotion extends MouseMotionAdapter
{
public void mouseDragged(MouseEvent e)
{
p1.setBackground( Color.red);
repaint();
}
public void mouseMoved(MouseEvent e)
{
txt1.setText((String)e.getX()+','+(String)e.getY());//这里编译的时候报错,说不能这样转换,那应该怎么办呢?
}
}
public static void main(String args[])
{
KeyPress KP1=new KeyPress("www.it315.org");
KP1.setSize(300,200);
KP1.setVisible(true);
}
}
import java.awt.event.*;
class KeyPress extends Frame
{
Panel p1=new Panel();
TextField txt1=new TextField(20);
KeyPress(String title)
{
super(title);
add(p1);
p1.setLayout(new FlowLayout());
p1.addKeyListener(new kEvent());
p1.add(txt1);
p1.addMouseMotionListener(new mMotion());
}
class kEvent extends KeyAdapter
{
public void keyTyped(KeyEvent e)
{
if(e.getKeyChar()=='x' || e.getKeyChar()=='X')
System.exit(0);
}
public void keyPressed(KeyEvent e)
{
p1.setBackground( Color.gray);
repaint();
}
public void keyReleased(KeyEvent e)
{
p1.setBackground( Color.yellow);
repaint();
}
}
class mMotion extends MouseMotionAdapter
{
public void mouseDragged(MouseEvent e)
{
p1.setBackground( Color.red);
repaint();
}
public void mouseMoved(MouseEvent e)
{
txt1.setText((String)e.getX()+','+(String)e.getY());//这里编译的时候报错,说不能这样转换,那应该怎么办呢?
}
}
public static void main(String args[])
{
KeyPress KP1=new KeyPress("www.it315.org");
KP1.setSize(300,200);
KP1.setVisible(true);
}
}
(String)(e.getX()),多加一个括号。
(String)(e.getX()),谁教你这么写的