程序填空题:GUI鼠标事件处理
本题通过MouseAdapter适配器,实现鼠标单击、鼠标按下、鼠标进入窗口、鼠标离开窗口和鼠标松开等方法,并通过MouseMotionListener实现鼠标的移动和拖动鼠标的操作。程序运行结果如下:
![QQ图片20211125105920.png](~/369ce72e-6437-472d-aaeb-bbdf978d6a4b.png)
c++
程序如下,请按照提示完善程序。
public class Main extends JApplet
{ int x,y;
JLabel lb1=new JLabel("X:"), lb2=new JLabel("Y:"), lb3=new JLabel("");
JTextField tf1=new JTextField(5), tf2=new JTextField(5);
Container cp=getContentPane( );
FlowLayout flow=new FlowLayout(FlowLayout.CENTER,5,5);
public void init( )
{ ;//设置容器的布局样式为流式布局
cp.add(lb1);
cp.add(tf1);
cp.add(lb2);
cp.add(tf2);
cp.add(lb3);
addMouseListener(new mouseListener( ));//通过MouseAdapter增加监听
addMouseMotionListener(new koLis( ));
}
class mouseListener extends //继承父类
{
public void mouseClicked(MouseEvent e)
{ lb3.setText("点击鼠标"); }
public void mousePressed(MouseEvent e)
{ lb3.setText("鼠标按钮按下"); }
public void mouseEntered(MouseEvent e)
{ lb3.setText("鼠标进入窗口"); }
public void mouseExited(MouseEvent e)
{ lb3.setText("鼠标不在窗口"); }
public void mouseReleased(MouseEvent e)
{ lb3.setText("鼠标按钮松开"); }
}
class koLis implements //继承接口
{
public void mouseMoved(MouseEvent e)
{ x=e.getX( );
y=e.getY( );
tf1.setText(String.valueOf(x));
tf2.setText(String.valueOf(y));
}
//实现鼠标拖动的方法
{ lb3.setText("拖动鼠标"); }
}
}
答案:
第1空:cp.setLayout(flow)
第2空: MouseAdapter
第3空:MouseMotionListener
第4空:public void mouseDragged(MouseEvent e)
![QQ图片20211125105920.png](~/369ce72e-6437-472d-aaeb-bbdf978d6a4b.png)
c++
程序如下,请按照提示完善程序。
public class Main extends JApplet
{ int x,y;
JLabel lb1=new JLabel("X:"), lb2=new JLabel("Y:"), lb3=new JLabel("");
JTextField tf1=new JTextField(5), tf2=new JTextField(5);
Container cp=getContentPane( );
FlowLayout flow=new FlowLayout(FlowLayout.CENTER,5,5);
public void init( )
{ ;//设置容器的布局样式为流式布局
cp.add(lb1);
cp.add(tf1);
cp.add(lb2);
cp.add(tf2);
cp.add(lb3);
addMouseListener(new mouseListener( ));//通过MouseAdapter增加监听
addMouseMotionListener(new koLis( ));
}
class mouseListener extends //继承父类
{
public void mouseClicked(MouseEvent e)
{ lb3.setText("点击鼠标"); }
public void mousePressed(MouseEvent e)
{ lb3.setText("鼠标按钮按下"); }
public void mouseEntered(MouseEvent e)
{ lb3.setText("鼠标进入窗口"); }
public void mouseExited(MouseEvent e)
{ lb3.setText("鼠标不在窗口"); }
public void mouseReleased(MouseEvent e)
{ lb3.setText("鼠标按钮松开"); }
}
class koLis implements //继承接口
{
public void mouseMoved(MouseEvent e)
{ x=e.getX( );
y=e.getY( );
tf1.setText(String.valueOf(x));
tf2.setText(String.valueOf(y));
}
//实现鼠标拖动的方法
{ lb3.setText("拖动鼠标"); }
}
}
答案:
第1空:cp.setLayout(flow)
第2空: MouseAdapter
第3空:MouseMotionListener
第4空:public void mouseDragged(MouseEvent e)