TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
程序中用到了java.awt.Robot类,这个类通常用来在自动化测试或程序演示中模拟系统事件,在某些需要控制鼠标或键盘的应用程序中这个类也是很有用,这个类主要的目的就是为方便的实现java的GUI自动化测试平台。
有两段程序,第一个是普通的按钮点击程序,第二个模拟点击。 一、Frame1.java- import java.awt.*;
- import javax.swing.*;
- import java.awt.event.*;
- public class Frame1 extends JFrame {
- private JButton jButton1 = new JButton();
- public Frame1() {
- try {
- jbInit();
- }catch(Exception e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) {
- Frame1 frame1 = new Frame1();
- frame1.setVisible(true) ;
- }
- private void jbInit() throws Exception {
- jButton1.setText("jButton1");
- jButton1.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(ActionEvent e) {
- jButton1_actionPerformed(e);
- }
- });
- this.setTitle("Test");
- this.getContentPane().add(jButton1, BorderLayout.CENTER);
- this.setSize(400,400);
- }
- void jButton1_actionPerformed(ActionEvent e) {
- System.out.println("click me") ;
- }
- }
复制代码
二、TestReplay.java- import java.awt.*;
- import javax.swing.*;
- import java.awt.event.*;
- public class TestReplay extends Thread{
- public static void main(String[] args) {
- try{
- //启动应用程序
- Frame1.main(new String[]{null}) ;
- //等应用程序启动后延迟3秒
- Thread.currentThread().sleep(3000) ;
- Robot robottest=new Robot();
- robottest.waitForIdle();
- //根据标题名获取当前应用的主窗体,在本例中为"test"
- Frame jframe=getFrame("test");
- //根据给定的窗体和窗体中要find的控件的名称来获取控件的引用
- JButton jbtn=getButton(jframe,"jButton1");
- //将鼠标移到控件所在的位置
- robottest.mouseMove(jbtn.getLocationOnScreen().x+jbtn.getWidth()/2,jbtn.getLocationOnScreen().y+jbtn.getHeight()/2) ;
- //在控件所在位置,生成鼠标点击事件
- robottest.mousePress(InputEvent.BUTTON1_MASK ) ;
- robottest.mouseRelease(InputEvent.BUTTON1_MASK ) ;
- }catch(Exception ee){
- ee.printStackTrace() ;
- }
- }
- //获得标题为title的frame
- private static Frame getFrame(String title){
- Frame[] jframes=(Frame[])JFrame.getFrames();
- for(int i=0;i< jframes.length ;i++){
- if(jframes[i].getTitle().equalsIgnoreCase(title))return jframes[i];
- }
- return null;
- }
- //获取某一个frame下的某个名为jButton1的控件
- private static JButton getButton(Frame jf,String text){
- /*注意下面这行代码,因为实例比较简单只有ContentPane一个Container类型的控件,
- *如果在JFrame中有多个Container控件//的话,必须进行递归处理,
- *搜索出所有的控件*/
- Component[] coms=((JFrame)jf).getContentPane().getComponents();
- for(int i=0;i< coms.length ;i++){
- if(!(coms[i] instanceof JButton)) continue;
- if(((JButton)coms[i]).getText().equalsIgnoreCase(text))return (JButton)coms[i];
- }
- return null;
- }
- public void run(){ }
- }
复制代码
源码下载:http://file.javaxxz.com/2014/10/2/021135578.zip |
|