Пример #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();
   }
 }
Пример #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();
  }
Пример #3
0
 /** Generate the XML for a tool and add it to the toolbox */
 public void compile() {
   final Tool[] ts = GUIEnv.getApplicationFrame().getSelectedTools();
   if (ts == null || ts.length == 0) {
     JOptionPane.showMessageDialog(
         GUIEnv.getApplicationFrame(),
         "Please Select a Tool from the workspace",
         "Select",
         JOptionPane.INFORMATION_MESSAGE,
         GUIEnv.getTrianaIcon());
   } else {
     final CompileHandler compiler = new CompileHandler(true, tools);
     Thread thread =
         new Thread() {
           public void run() {
             for (int i = 0; i < ts.length; i++) {
               Tool selectedTool = ts[i];
               if ((selectedTool != null) && (!(selectedTool instanceof TaskGraph))) {
                 compiler.compileTargetTool(selectedTool);
               }
             }
           }
         };
     thread.setName("Build Tools Thread");
     thread.setPriority(Thread.MIN_PRIORITY);
     thread.start();
   }
 }
Пример #4
0
  @Override
  public void openDoor() {

    DoorThread1 doorThread = new DoorThread1(this, "Open");
    Thread thread = new Thread(doorThread);
    thread.start();
  }
  /**
   * Starts the print operation. This is quite expensive, and is kicked off in a separate thread.
   */
  public void print() {
    final PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(this);

    // make a local copy of the object to be printed, for use by the print thread
    // below...

    final Component printMe = getPrintComponent();

    Thread worker =
        new Thread() {
          public void run() {
            if (job.printDialog()) {
              try {
                // need to make sure that no other thread tries to
                // run a print job and set printCompnent at the same
                // time...
                synchronized (this) {
                  printComponent = printMe;
                  job.print();
                  printComponent = null;
                }
              } catch (Exception ex) {
                log.warning("error printing: " + ex);
              }
            }
          }
        };
    worker.start();
  }
Пример #6
0
  protected void flushSerialBuffer() throws RunnerException, SerialException {
    // Cleanup the serial buffer
    try {
      Serial serialPort = new Serial();
      byte[] readBuffer;
      while (serialPort.available() > 0) {
        readBuffer = serialPort.readBytes();
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
        }
      }

      serialPort.setDTR(false);
      serialPort.setRTS(false);

      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
      }

      serialPort.setDTR(true);
      serialPort.setRTS(true);

      serialPort.dispose();
    } catch (SerialNotFoundException e) {
      throw e;
    } catch (Exception e) {
      e.printStackTrace();
      throw new RunnerException(e.getMessage());
    }
  }
Пример #7
0
 /**
  * Standard sleeping function used to give the effect of scrolling
  *
  * @param time The duration of the sleep period (1000= 1 second)
  */
 public static void pauseMatrix(int time) {
   try {
     Thread.sleep(time);
   } catch (InterruptedException ex) {
     Thread.currentThread().interrupt();
   }
 }
Пример #8
0
  private static void externalExecute(final File prog, final File tclWishFile) {

    final Thread worker =
        new Thread() {

          @Override
          public void run() {
            try {

              if (tclWishFile.exists()) {
                if (prog.exists()) {
                  String command =
                      tclWishFile.getAbsolutePath() + " " + "\"" + prog.getAbsolutePath() + "\"";
                  System.out.println("Launching PolSARPro: " + command);
                  final Process proc =
                      Runtime.getRuntime().exec(command, null, new File(prog.getParent()));

                  outputTextBuffers(
                      new BufferedReader(new InputStreamReader(proc.getInputStream())));
                  outputTextBuffers(
                      new BufferedReader(new InputStreamReader(proc.getErrorStream())));
                } else {
                  SnapDialogs.showError("The file: " + prog.getAbsolutePath() + " does not exist.");
                }
              } else {
                SnapDialogs.showError("Cannot find TCL wish.exe to launch PolSARPro");
              }
            } catch (Exception e) {
              SnapDialogs.showError("Unable to launch PolSARPro:" + e.getMessage());
            }
          }
        };
    worker.start();
  }
Пример #9
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);
  }
Пример #10
0
 /**
  * A new method that interrupts the worker thread. Call this method to force the worker to stop
  * what it's doing.
  */
 public void interrupt() {
   Thread t = threadVar.get();
   if (t != null) {
     t.interrupt();
   }
   threadVar.clear();
 }
Пример #11
0
    public void run() {
      while (_connected) {
        try {
          Thread.sleep(25);
          if (_specialRequest != null) {
            for (final char c : _specialRequest.toCharArray()) {
              final StringBuffer buf = new StringBuffer();
              buf.append(c);
              sendMessage(buf.toString());
              Thread.sleep(2000);
            }
            _specialRequest = null;

          } else if (_transmitterValue != null) {
            _lastRequest =
                _lastRequest.equals(FLIGHT_DATA_REQUEST)
                    ? SENSORS_DATA_REQUEST
                    : FLIGHT_DATA_REQUEST;
            _transmitterValue += _lastRequest;
            sendMessage(_transmitterValue);
            _transmitterValue = null;
          }

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
Пример #12
0
  @Override
  public void connect(final String commPort, final String commSpeed) {
    try {
      synchronized (_mutex) {
        _comPortId = CommPortIdentifier.getPortIdentifier(commPort);
        _serialPort = (SerialPort) _comPortId.open("ComPort", 2000);
        _inputStream = _serialPort.getInputStream();
        _outputStream = _serialPort.getOutputStream();
        _serialPort.addEventListener(new MySerialCommPortEventListener());
        _serialPort.notifyOnDataAvailable(true);
        final int speed = Integer.parseInt(commSpeed);
        _serialPort.setSerialPortParams(
            speed, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        _connected = true;
        Thread.sleep(3000);
        notifyConnectionStatus(true);

        _connectionThread.start();
      }
    } catch (Exception e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
Пример #13
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();
  }
    public synchronized void run() {
      while (!m_quit) {
        // System.out.println("Sending statuspoller W!! ");
        try {
          if (m_cryoPanel != null && !m_paused) {
            if (initialDelay > 0) {
              Thread.sleep(initialDelay);
              initialDelay = 0;
            }
            if (dataCount == 0) {
              dataCount++;
              sendCommand(CMD_CLOCK);
              sendCommand(CMD_PARAMS);
            } else {
              dataCount++;
              sendCommand(CMD_CLOCK);
            }
            if (dataCount == dataUpdate) dataCount = 0;

            Thread.sleep(m_rate_ms);
          }
        } catch (InterruptedException ie) {
        }
      }
    }
 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();
   }
 }
  /**
   * Attempts to search the mod website for the mod and pull the recent versions of the mod.
   *
   * @param mod The Mod to search for on the website.
   * @param modInfoList The JList to populate/alter.
   */
  public void getRecentVersionsOfModAsync(Profile.Mod mod, JList modInfoList) {
    // Here we set a thread task to get the version numbers for the mod. This will look at the site
    // and search for the mod, then pull all versions from it.
    Runnable task = () -> Crawler.readVersionInfoOfMod(mod.nameWithoutVersion);
    Thread thread = new Thread(task);
    thread.start();

    // Our timer that checks every 200ms if the thread has finished.
    Timer timer = new Timer(200, null);
    timer.addActionListener(
        ev -> {
          if (thread.getState() != Thread.State.TERMINATED) timer.restart();
          else {
            timer.stop();
            DefaultListModel listModel = (DefaultListModel) modInfoList.getModel();
            // Get the modVersionInfo from the crawler. If not null, add to the list.
            String[][] modVersionInfo = Crawler.getModVersionInfo();
            if (modVersionInfo != null) {
              listModel.addElement("Recent Versions:");
              for (String[] info : modVersionInfo) {
                listModel.addElement("    v" + info[0] + " for " + info[1]);
              }
            } else {
              listModel.addElement("Couldn't find the mod on the website.");
            }
            modInfoList.setModel(listModel);
          }
        });
    timer.start();
  }
Пример #17
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();
 }
Пример #18
0
 public void stopEvaluate() {
   // user requested run be stopped so tell
   // run thread to stop
   Thread tmp = runThread;
   runThread = null;
   tmp.interrupt();
 }
Пример #19
0
    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();
    }
Пример #20
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();
    }
  }
Пример #21
0
  public RoxSplash(Frame f, String initString) {
    super(f);

    jt.setFont(new Font("Verdana", Font.PLAIN, 9));
    jt.setText(initString);

    getContentPane().add(painel, BorderLayout.CENTER);
    getContentPane().add(jt, BorderLayout.SOUTH);

    pack();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    this.setSize(500, 310);

    setLocation(screenSize.width / 2 - 250, screenSize.height / 2 - 150);

    Runnable waitRunner =
        new Runnable() {
          public void run() {
            try {
              Thread.sleep(10);
            } catch (Exception e) {
            }
          }
        };
    setVisible(true);
    Thread splashThread = new Thread(waitRunner, "RoxSplash");
    splashThread.start();
  }
Пример #22
0
  public void onRemovePressed(final ContributedLibrary lib) {
    boolean managedByIndex = indexer.getIndex().getLibraries().contains(lib);

    if (!managedByIndex) {
      int chosenOption = JOptionPane.showConfirmDialog(this, _("This library is not listed on Library Manager. You won't be able to resinstall it from here.\nAre you sure you want to delete it?"), _("Please confirm library deletion"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
      if (chosenOption != JOptionPane.YES_OPTION) {
        return;
      }
    }

    clearErrorMessage();
    installerThread = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          setProgressVisible(true, _("Removing..."));
          installer.remove(lib);
          onIndexesUpdated(); // TODO: Do a better job in refreshing only the needed element
          //getContribModel().updateLibrary(lib);
        } catch (Exception e) {
          throw new RuntimeException(e);
        } finally {
          setProgressVisible(false, "");
        }
      }
    });
    installerThread.setUncaughtExceptionHandler(new InstallerJDialogUncaughtExceptionHandler(this, noConnectionErrorMessage));
    installerThread.start();
  }
Пример #23
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);
      }
    }
Пример #24
0
  /** 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();
  }
Пример #25
0
  public PanelForSquare() {
    setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
    setBackground(Color.white);

    Thread thread = new Thread(this);
    initTimer();
    thread.start();
  }
Пример #26
0
 public synchronized void stop() {
   running = false;
   try {
     thread.join();
   } catch (InterruptedException e) {
     thread.interrupt();
   }
 }
Пример #27
0
  private static BibEntry downloadEntryBibTeX(String id, boolean downloadAbstract) {
    try {
      URL url =
          new URL(
              ACMPortalFetcher.START_URL
                  + ACMPortalFetcher.BIBTEX_URL
                  + id
                  + ACMPortalFetcher.BIBTEX_URL_END);
      URLConnection connection = url.openConnection();

      // set user-agent to avoid being blocked as a crawler
      connection.addRequestProperty(
          "User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0");
      Collection<BibEntry> items = null;
      try (BufferedReader in =
          new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        items = BibtexParser.parse(in).getDatabase().getEntries();
      } catch (IOException e) {
        LOGGER.info("Download of BibTeX information from ACM Portal failed.", e);
      }
      if ((items == null) || items.isEmpty()) {
        return null;
      }
      BibEntry entry = items.iterator().next();
      Thread.sleep(
          ACMPortalFetcher.WAIT_TIME); // wait between requests or you will be blocked by ACM

      // get abstract
      if (downloadAbstract) {
        url = new URL(ACMPortalFetcher.START_URL + ACMPortalFetcher.ABSTRACT_URL + id);
        String page = Util.getResults(url);
        Matcher absM = ACMPortalFetcher.ABSTRACT_PATTERN.matcher(page);
        if (absM.find()) {
          entry.setField("abstract", absM.group(1).trim());
        }
        Thread.sleep(
            ACMPortalFetcher.WAIT_TIME); // wait between requests or you will be blocked by ACM
      }

      return entry;
    } catch (NoSuchElementException e) {
      LOGGER.info(
          "Bad BibTeX record read at: "
              + ACMPortalFetcher.BIBTEX_URL
              + id
              + ACMPortalFetcher.BIBTEX_URL_END,
          e);
      return null;
    } catch (MalformedURLException e) {
      LOGGER.info("Malformed URL.", e);
      return null;
    } catch (IOException e) {
      LOGGER.info("Cannot connect.", e);
      return null;
    } catch (InterruptedException ignored) {
      return null;
    }
  }
Пример #28
0
  // --------------------------------actionDisconnect---------------------------
  private void actionDisconnect() {

    try {
      oConn.disconnect();
      tConn.join(2000);
      tMain.join(2000);
    } catch (Exception e) {
    }
  }
Пример #29
0
  /** 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();
    }
  }
Пример #30
0
 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) {
   }
 }