Example #1
1
 public void actionPerformed(ActionEvent ae) {
   // 响应用户点击
   if (ae.getActionCommand().equals("new_game")) {
     // 如果选择 “开始新游戏” 则跳转到游戏开始
     ae_panel = new GamePanel(false);
     Thread ae_thread = new Thread(ae_panel);
     ae_thread.start();
     // 先删除旧面板 -- 开始界面
     this.remove(start_panel);
     this.add(ae_panel);
     this.addKeyListener(ae_panel);
     this.setVisible(true); // 如果没有这句点击后不会出现新的游戏面板
   } else if (ae.getActionCommand().equals("qs_game")) {
     // 退出时保存游戏进度
     Recorder.set_enemies(ae_panel.enemies);
     Recorder.save_game_data();
     // 0 表示正常退出
     System.exit(0);
   } else if (ae.getActionCommand().equals("restart_old_game")) {
     // 恢复游戏数据 -- 如果曾经保存
     Recorder.recovery_position();
     ae_panel = new GamePanel(true);
     Thread ae_thread = new Thread(ae_panel);
     ae_thread.start();
     // 先删除旧面板 -- 开始界面
     this.remove(start_panel);
     this.add(ae_panel);
     this.addKeyListener(ae_panel);
     this.setVisible(true);
   } else if (ae.getActionCommand().equals("save_now")) {
     Recorder.set_enemies(ae_panel.enemies);
     Recorder.recovery_position();
   }
 }
Example #2
1
  // --------------------------------actionConnect------------------------------
  private void actionConnect() {
    if (oParty == null) {
      JOptionPane.showMessageDialog(frame, "Make a party before trying to connect.");
      return;
    }

    String[] oResults = (String[]) DialogManager.show(DialogManager.CONNECT, frame);

    if (oResults[DialogManager.RETURN_IP].equals("cancel")) return;

    lblStatus3.setText("Connecting...");
    try {
      oConn.connect(
          oResults[DialogManager.RETURN_IP], Integer.parseInt(oResults[DialogManager.RETURN_PORT]));
    } catch (UnknownHostException e) {
      JOptionPane.showMessageDialog(
          frame,
          "The IP of the host cannot be determined.",
          "Unknown Host Exception",
          JOptionPane.ERROR_MESSAGE);
      frame.repaint();
      return;
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          frame, e.getMessage(), "Input/Output Exception", JOptionPane.ERROR_MESSAGE);
      frame.repaint();
      return;
    }
    echo("Connected to opponent!");

    tConn = new Thread(oConn, "conn");
    tConn.start();
    tMain = new Thread(this, "main");
    tMain.start();
  }
Example #3
0
 /** Called by ImageJ when the user selects Quit. */
 public void quit() {
   quitMacro = IJ.macroRunning();
   Thread thread = new Thread(this, "Quit");
   thread.setPriority(Thread.NORM_PRIORITY);
   thread.start();
   IJ.wait(10);
 }
 public void findLocationForInstance(ArchDescriptionInstances newInstance) {
   if (newInstance instanceof ArchDescriptionAnalogInstances) {
     final Resources parentResource = (Resources) editorField.getModel();
     final ArchDescriptionAnalogInstances analogInstance =
         (ArchDescriptionAnalogInstances) newInstance;
     Thread performer =
         new Thread(
             new Runnable() {
               public void run() {
                 InfiniteProgressPanel monitor =
                     ATProgressUtil.createModalProgressMonitor(
                         ApplicationFrame.getInstance(), 1000);
                 monitor.start("Gathering Containers...");
                 try {
                   analogInstance.setLocation(
                       parentResource.findLocationForContainer(
                           analogInstance.getTopLevelLabel(), monitor));
                 } finally {
                   monitor.close();
                 }
               }
             },
             "Performer");
     performer.start();
   }
 }
    protected void openFromPath(final String path) {
      Thread t =
          new Thread(
              new Runnable() {
                public void run() {
                  final ArrayList<Airspace> airspaces = new ArrayList<Airspace>();
                  try {
                    loadAirspacesFromPath(path, airspaces);
                  } finally {
                    SwingUtilities.invokeLater(
                        new Runnable() {
                          public void run() {
                            setAirspaces(airspaces);
                            setEnabled(true);
                            getApp().setCursor(null);
                            getApp().getWwd().redraw();
                          }
                        });
                  }
                }
              });

      this.setEnabled(false);
      getApp().setCursor(new Cursor(Cursor.WAIT_CURSOR));
      t.start();
    }
Example #6
0
    @Override
    public void actionPerformed(ActionEvent e) {
      Frame frame = getFrame();
      JFileChooser chooser = new JFileChooser();
      int ret = chooser.showOpenDialog(frame);

      if (ret != JFileChooser.APPROVE_OPTION) {
        return;
      }

      File f = chooser.getSelectedFile();
      if (f.isFile() && f.canRead()) {
        Document oldDoc = getEditor().getDocument();
        if (oldDoc != null) {
          oldDoc.removeUndoableEditListener(undoHandler);
        }
        if (elementTreePanel != null) {
          elementTreePanel.setEditor(null);
        }
        getEditor().setDocument(new PlainDocument());
        frame.setTitle(f.getName());
        Thread loader = new FileLoader(f, editor.getDocument());
        loader.start();
      } else {
        JOptionPane.showMessageDialog(
            getFrame(),
            "Could not open file: " + f,
            "Error opening file",
            JOptionPane.ERROR_MESSAGE);
      }
    }
Example #7
0
 public void run() {
   if (Thread.currentThread() != this.mt)
     throw (new RuntimeException("MainFrame is being run from an invalid context"));
   Thread ui = new HackThread(p, "Haven UI thread");
   ui.start();
   try {
     try {
       Session sess = null;
       while (true) {
         UI.Runner fun;
         if (sess == null) {
           Bootstrap bill = new Bootstrap(Config.defserv, Config.mainport);
           if ((Config.authuser != null) && (Config.authck != null)) {
             bill.setinitcookie(Config.authuser, Config.authck);
             Config.authck = null;
           }
           fun = bill;
           setTitle(String.format("Amish Paradise %s", version));
         } else {
           fun = new RemoteUI(sess);
           setTitle(String.format("Amish Paradise %s \u2013 %s", version, sess.username));
         }
         sess = fun.run(p.newui(sess));
       }
     } catch (InterruptedException e) {
     }
     savewndstate();
   } finally {
     ui.interrupt();
     dispose();
   }
 }
  /** Second part of debugger start procedure. */
  private void startDebugger() {
    threadManager = new ThreadManager(this);

    setBreakpoints();
    updateWatches();
    println(bundle.getString("CTL_Debugger_running"), STL_OUT);
    setDebuggerState(DEBUGGER_RUNNING);

    virtualMachine.resume();

    // start refresh thread .................................................
    if (debuggerThread != null) debuggerThread.stop();
    debuggerThread =
        new Thread(
            new Runnable() {
              public void run() {
                for (; ; ) {
                  try {
                    Thread.sleep(5000);
                  } catch (InterruptedException ex) {
                  }
                  if (getState() == DEBUGGER_RUNNING) threadGroup.refresh();
                }
              }
            },
            "Debugger refresh thread"); // NOI18N
    debuggerThread.setPriority(Thread.MIN_PRIORITY);
    debuggerThread.start();
  }
Example #9
0
 public void stopEvaluate() {
   // user requested run be stopped so tell
   // run thread to stop
   Thread tmp = runThread;
   runThread = null;
   tmp.interrupt();
 }
Example #10
0
  Ccard() {
    OData.GenRnd(data, min, max, rnd_no); // 產生0~8亂數
    // 9個圖形物件
    for (i = 0; i <= 8; i++) {
      icon[i] = new ImageIcon("fig/p_" + i + ".jpg");
    }
    // 9個標籤亂數放圖
    k = 0;
    for (i = 0; i <= 2; i++) {
      for (j = 0; j <= 2; j++) {
        lbl[k] = new JLabel(icon[data[k]]);
        lbl[k].setBounds(10 + j * 160, 10 + i * 120, 160, 120);
        add(lbl[k]);
        lbl[k].addMouseListener(mouseObj); // 註冊傾聽者
        k++;
      }
    }

    lblCar.setSize(65, 43);
    add(lblCar);
    int width = 510, c_y = 375, c_time = 25;
    Thread ThCar = new Thread(new movePic(lblCar, width, c_y, c_time));
    ThCar.start();

    setTitle("3x3拼圖遊戲");
    setLayout(null);
    setBounds(100, 100, 510, 460);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
    public void run() {
      try {
        if (myPreviousThread != null) myPreviousThread.join();
        Thread.sleep(delay);
        log("> run MouseMoveThread " + x + ", " + y);
        while (!hasFocus()) {
          Thread.sleep(1000);
        }
        int x1 = lastMouseX;
        int x2 = x;
        int y1 = lastMouseY;
        int y2 = y;
        // shrink range by 1 px on both ends
        // manually move this 1px to trip DND code
        if (x1 != x2) {
          int dx = x - lastMouseX;
          if (dx > 0) {
            x1 += 1;
            x2 -= 1;
          } else {
            x1 -= 1;
            x2 += 1;
          }
        }
        if (y1 != y2) {
          int dy = y - lastMouseY;
          if (dy > 0) {
            y1 += 1;
            y2 -= 1;
          } else {
            y1 -= 1;
            y2 += 1;
          }
        }
        robot.setAutoDelay(Math.max(duration / 100, 1));
        robot.mouseMove(x1, y1);
        int d = 100;
        for (int t = 0; t <= d; t++) {
          x1 =
              (int)
                  easeInOutQuad(
                      (double) t, (double) lastMouseX, (double) x2 - lastMouseX, (double) d);
          y1 =
              (int)
                  easeInOutQuad(
                      (double) t, (double) lastMouseY, (double) y2 - lastMouseY, (double) d);
          robot.mouseMove(x1, y1);
        }
        robot.mouseMove(x, y);
        lastMouseX = x;
        lastMouseY = y;
        robot.waitForIdle();
        robot.setAutoDelay(1);
      } catch (Exception e) {
        log("Bad parameters passed to mouseMove");
        e.printStackTrace();
      }

      log("< run MouseMoveThread");
    }
Example #12
0
  public AnimationFrame() {
    ArrayComponent comp = new ArrayComponent();
    add(comp, BorderLayout.CENTER);

    final Sorter sorter = new Sorter(comp);

    JButton runButton = new JButton("Run");
    runButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            sorter.setRun();
          }
        });

    JButton stepButton = new JButton("Step");
    stepButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            sorter.setStep();
          }
        });

    JPanel buttons = new JPanel();
    buttons.add(runButton);
    buttons.add(stepButton);
    add(buttons, BorderLayout.NORTH);
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    Thread t = new Thread(sorter);
    t.start();
  }
Example #13
0
  //    public static final String showElementTreeAction = "showElementTree";
  // -------------------------------------------------------------
  public void openFile(String currDirStr, String currFileStr) {

    if (fileDialog == null) {
      fileDialog = new FileDialog(this);
    }
    fileDialog.setMode(FileDialog.LOAD);
    if (!(currDirStr.equals(""))) {
      fileDialog.setDirectory(currDirStr);
    }
    if (!(currFileStr.equals(""))) {
      fileDialog.setFile(currFileStr);
    }
    fileDialog.show();

    String file = fileDialog.getFile(); // cancel pushed
    if (file == null) {
      return;
    }
    String directory = fileDialog.getDirectory();
    File f = new File(directory, file);
    if (f.exists()) {
      Document oldDoc = getEditor().getDocument();
      if (oldDoc != null)
        // oldDoc.removeUndoableEditListener(undoHandler);
        /*
          if (elementTreePanel != null) {
          elementTreePanel.setEditor(null);
          }
        */
        getEditor().setDocument(new PlainDocument());
      fileDialog.setTitle(file);
      Thread loader = new FileLoader(f, editor1.getDocument());
      loader.start();
    }
  }
Example #14
0
 /** Adds a bouncing ball to the canvas and starts a thread to make it bounce */
 public void addBall() {
   Ball b = new Ball();
   comp.add(b);
   Runnable r = new BallRunnable(b, comp);
   Thread t = new Thread(r);
   t.start();
 }
  // Not sure about what happens if multiple of this test are
  //  instantiated in the same VM.  Being static (and using
  //  static vars), it aint gonna work.  Not worrying about
  //  it for now.
  public static void main(String args[]) throws InterruptedException {
    mainThread = Thread.currentThread();
    try {
      init();
    } catch (TestPassedException e) {
      // The test passed, so just return from main and harness will
      // interepret this return as a pass
      return;
    }
    // At this point, neither test pass nor test fail has been
    // called -- either would have thrown an exception and ended the
    // test, so we know we have multiple threads.

    // Test involves other threads, so sleep and wait for them to
    // called pass() or fail()
    try {
      Thread.sleep(sleepTime);
      // Timed out, so fail the test
      throw new RuntimeException("Timed out after " + sleepTime / 1000 + " seconds");
    } catch (InterruptedException e) {
      // The test harness may have interrupted the test.  If so, rethrow the exception
      // so that the harness gets it and deals with it.
      if (!testGeneratedInterrupt) throw e;

      // reset flag in case hit this code more than once for some reason (just safety)
      testGeneratedInterrupt = false;

      if (theTestPassed == false) {
        throw new RuntimeException(failureMessage);
      }
    }
  } // main
 public synchronized void stop() {
   running = false;
   try {
     thread.join();
   } catch (InterruptedException e) {
     thread.interrupt();
   }
 }
Example #17
0
  public PanelForSquare() {
    setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
    setBackground(Color.white);

    Thread thread = new Thread(this);
    initTimer();
    thread.start();
  }
 public void _notified(double sec, final String chars) {
   if (!isSecure(sec)) return;
   // decouple from JavaScript; thread join could hang it
   Thread thread =
       new Thread("_notified") {
         public void run() {
           AccessController.doPrivileged(
               new PrivilegedAction() {
                 public Object run() {
                   try {
                     // wait for release shift/altgraph to resolve
                     if (previousThread != null) {
                       previousThread.join();
                     }
                   } catch (Exception e) {
                   }
                   keystring += chars;
                   if (altgraph && !shift) {
                     shift = false;
                     // Set robot auto delay now that FF/Mac inited all of the keys.
                     // Good for DND.
                     robot.setAutoDelay(1);
                     try {
                       log(keystring);
                       int index = 0;
                       for (int i = 0; (i < vkKeys.size()) && (index < keystring.length()); i++) {
                         char c = keystring.charAt(index++);
                         _mapKey(c, i, false, false);
                       }
                       for (int i = 0; (i < vkKeys.size()) && (index < keystring.length()); i++) {
                         char c = keystring.charAt(index++);
                         _mapKey(c, i, true, false);
                       }
                       for (int i = 0; (i < vkKeys.size()) && (index < keystring.length()); i++) {
                         char c = keystring.charAt(index++);
                         _mapKey(c, i, false, true);
                       }
                       // notify DOH that the applet finished init
                       dohrobot.call("_onKeyboard", new Object[] {});
                     } catch (Exception e) {
                       e.printStackTrace();
                     }
                     return null;
                   } else if (!shift) {
                     shift = true;
                   } else {
                     shift = false;
                     altgraph = true;
                   }
                   pressNext();
                   // }
                   return null;
                 }
               });
         }
       };
   thread.start();
 }
  /** Mutes or unmutes the associated <tt>Call</tt> upon clicking this button. */
  public void toggleMute() {
    if (muteRunner == null) {
      muteRunner = new Thread(this, getToolTipText());
      muteRunner.setDaemon(true);

      setEnabled(false);
      muteRunner.start();
    }
  }
Example #20
0
  // --------------------------------actionDisconnect---------------------------
  private void actionDisconnect() {

    try {
      oConn.disconnect();
      tConn.join(2000);
      tMain.join(2000);
    } catch (Exception e) {
    }
  }
 private void messageStresser() throws HeadlessException {
   String res = JOptionPane.showInputDialog(this, "Number of messages to send");
   try {
     int count = Integer.parseInt(res);
     Thread t = new Thread(new Stresser(count));
     t.start();
   } catch (NumberFormatException nfe) {
   }
 }
Example #22
0
 public void go() {
   while (true) {
     try {
       Thread.currentThread();
       Thread.sleep(100);
     } catch (InterruptedException e) {
     }
     if (runFlag) t.setText(Integer.toString(count++));
   }
 }
  public void run() {
    Thread thisThread = Thread.currentThread();

    while (timerThread == thisThread) {
      getTvPanel().repaint();
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
      }
    }
  }
Example #24
0
 /**
  * Listener method called when a button has been clicked.
  *
  * @ae The action event.
  */
 public void actionPerformed(ActionEvent ae) {
   if (!running) {
     startButton.setText("Complete simulation");
     // The simulation must be run in a separate thread,
     // we can't "hijack" the GUI's event handling thread.
     Thread t = new Thread(this);
     t.start();
   } else {
     sleep = false;
   }
 }
Example #25
0
 public void startDrawingPanelThread() {
   // System.out.println("Starting Drawing Panel Thread");
   try {
     Thread chatThread = new Thread(new DrawingPanel());
     chatThread.start();
   } catch (Exception ex) {
     System.err.println("making the thread catch");
     ex.printStackTrace();
   }
   // world.startDrawingPanelThread();
 }
Example #26
0
 public void run() {
   System.out.println("start");
   while (Thread.currentThread() == thd) {
     try {
       setDate();
       Thread.sleep(10 * 1000);
     } catch (InterruptedException e) {
     }
   }
   System.out.println("Stop");
 }
Example #27
0
 public TankBattle() {
   // 2. 创建游戏面板等组件
   start_panel = new StartPanel();
   menu_bar = new JMenuBar();
   menu_option = new JMenu("游戏选项(G)");
   menu_help = new JMenu("帮助(H)");
   menu_pause = new JMenu("【暂停游戏(P)】");
   menu_continue = new JMenu("【继续游戏(C)】");
   menu_option.setMnemonic('G');
   menu_help.setMnemonic('H');
   mi_new = new JMenuItem("开始新游戏(N)");
   mi_quit = new JMenuItem("存盘退出(Q)");
   mi_save = new JMenuItem("保存游戏进度(S)");
   mi_old_start = new JMenuItem("读取游戏进度(R)");
   mi_about = new JMenuItem("关于(A)");
   // 4. 响应菜单 -- 为 KeyListener 注册监听
   mi_new.addActionListener(this);
   mi_new.setActionCommand("new_game");
   mi_quit.addActionListener(this);
   mi_quit.setActionCommand("qs_game");
   mi_old_start.addActionListener(this);
   mi_old_start.setActionCommand("restart_old_game");
   mi_save.addActionListener(this);
   mi_save.setActionCommand("save_now");
   menu_option.add(mi_new);
   menu_option.add(mi_quit);
   menu_option.add(mi_save);
   menu_option.add(mi_old_start);
   menu_help.add(mi_about);
   menu_bar.add(menu_option);
   menu_bar.add(menu_help);
   menu_bar.add(menu_pause);
   menu_bar.add(menu_continue);
   Thread start_p = new Thread(start_panel);
   start_p.start();
   this.setJMenuBar(menu_bar);
   this.add(start_panel);
   // 3. 添加游戏面板组件到窗体
   this.add(start_panel);
   // 设置窗体标题
   this.setTitle("坦克大战");
   // 设置窗体图标 -- D:/workspace/TankBattle/src/com/tank_battle
   this.setIconImage((new ImageIcon("src/images/tank_battle.gif")).getImage());
   // 设置窗体大小
   this.setSize(800, 700);
   // 设置窗体可见
   this.setVisible(true);
   // 禁止用户修改窗体大小
   this.setResizable(false);
   // 设置窗体初始位置(像素)
   this.setLocation(250, 50);
   // 设置当窗体退出时, JVM 也退出,否则就算关闭了窗体,JVM 仍然有进程在运行
   this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
Example #28
0
 public TankGame3() {
   // 坦克游戏的构造函数
   mp = new MyPanel();
   Thread t = new Thread(mp);
   t.start();
   this.add(mp);
   this.addKeyListener(mp);
   this.setSize(800, 600);
   this.setDefaultCloseOperation(EXIT_ON_CLOSE);
   this.setVisible(true);
 }
  private void createArchive() {

    System.out.println("Creating archive..");
    swapContainers(exportingProgressContainer);

    attachListenersForArchiveOutputUtil();
    archiveOutputUtil.setOutputLocation(outputFileLocation.getSelectedFilePath());
    archiveOutputUtil.setCompressionLevel(getCompressionLevel());
    final Thread archiveCreation = new Thread(archiveOutputUtil);
    archiveCreation.start();
  }
 public void shutdown() {
   setVisible(false);
   Thread shutdownThread =
       new Thread(
           new CatchingRunnable() {
             public void doRun() throws Exception {
               control.shutdown();
               System.exit(0);
             }
           });
   shutdownThread.start();
 }