解决方案 »

  1.   


    public class TT extends JFrame { private int title = 0; private int times; final JFrame jf; Button jb; JPanel panel; Label tx_lab; final TextField tx; static int command = 0; public TT() {
    jf = new JFrame(String.valueOf(title));
    panel = new JPanel();
    tx_lab = new Label("次数");
    tx = new TextField();
    jb = new Button("点我");
    Label resolution_lab = new Label("坐标");
    final TextField resolutionX = new TextField();
    final TextField resolutionY = new TextField();
    resolutionX.setText("1000");
    resolutionY.setText("1000");
    tx.setSize(50, 50);
    tx.setText("5"); jb.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    new Thread(new Runnable() { public void run() {
    Robot robot;
    try {
    robot = new Robot();
    times = Integer.valueOf(tx.getText());
    for (int i = 0; i < times; i++) {
    robot.mouseMove(Integer.valueOf(resolutionY
    .getText()), Integer
    .valueOf(resolutionY.getText()));
    // robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(500);
    // robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(500);
    title++;
    jf.setTitle(String.valueOf(title));
    listener();
    }
    } catch (AWTException e1) {
    e1.printStackTrace();
    }
    }
    }).start();
    }
    });
    jf.add(panel);
    panel.add(resolution_lab);
    panel.add(resolutionX);
    panel.add(resolutionY);
    panel.add(tx_lab);
    panel.add(tx);
    panel.add(jb);
    jf.pack();
    jf.setSize(300, 300);
    jf.setVisible(true);
    } public void listener() {
    jb.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == 27) {
    System.exit(-1);
    }
    command = e.getKeyCode();
    System.out.println(command);
    }
    });
    } public static void main(String[] args) throws Exception {
    TT tt = new TT();
    }}
      

  2.   

    terry21 谢谢你。明白了,原来是要多起一个线程
      

  3.   

    不过追问一下哦,我之前也有用过线程试过
    @Override
    public void run() {
    listener();

    }
    public static void main(String[] args) throws Exception {
    T t = new T();
    Thread t1 = new Thread(t);
    t1.start();


    }
    大概代码是这样的。。但是没有达到你的效果能告知一下原理吗~谢谢。
      

  4.   

    单线程规则:Swing线程在同一时刻仅能被一个线程所访问。一般来说,这个线程是事件派发线程(event-dispatching thread)。
    规则的例外:有些操作保证是线程安全的。
    事件分发:如果你需要从事件处理(event-handling)或绘制代码以外的地方访问UI,那么你可以使用SwingUtilities类的invokeLater()或invokeAndWait()方法。
    创建线程:如果你需要创建一个线程??比如用来处理一些耗费大量计算能力或受I/O能力限制的工作??你可以使用一个线程工具类如SwingWorker或Timer。
    ========================================================================
    你这样写线程根本就没有意义的,你创建一个线程来跑TT,然后主线程马上就结束了,跟没有创建线程,直接主线程来跑TT是一样效果的。建议每一个耗时的swing事件操作都启动一条线程来跑,最好使用ExecutorService来管理所有线程,它会重复利用线程资源。