Esempio n. 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();
   }
 }
Esempio n. 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();
  }
  /** Start the background thread. */
  public void start() {
    // create a random list of cities

    cities = new City[TravelingSalesman.CITY_COUNT];
    for (int i = 0; i < TravelingSalesman.CITY_COUNT; i++) {
      cities[i] =
          new City(
              (int) (Math.random() * (getBounds().width - 10)),
              (int) (Math.random() * (getBounds().height - 60)));
    }

    // create the initial chromosomes

    chromosomes = new Chromosome[TravelingSalesman.POPULATION_SIZE];
    for (int i = 0; i < TravelingSalesman.POPULATION_SIZE; i++) {
      chromosomes[i] = new Chromosome(cities);
      chromosomes[i].setCut(cutLength);
      chromosomes[i].setMutation(TravelingSalesman.MUTATION_PERCENT);
    }
    Chromosome.sortChromosomes(chromosomes, TravelingSalesman.POPULATION_SIZE);

    // start up the background thread
    started = true;
    map.update(map.getGraphics());

    generation = 0;

    if (worker != null) worker = null;
    worker = new Thread(this);
    // worker.setPriority(Thread.MIN_PRIORITY);
    worker.start();
  }
 public synchronized void scanLibrary() {
   if (scanner == null) {
     scanner = new Thread(this, "Library Scanner");
     scanner.start();
   } else if (scanner.isAlive()) {
     LOGGER.info("Scanner is already running !");
   } else {
     scanner = new Thread(this, "Library Scanner");
     scanner.start();
   }
 }
Esempio n. 5
0
 public void start() {
   if (!running) {
     running = true;
     animator = new Thread(this, "Game Thread");
     animator.start();
   }
 }
Esempio n. 6
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();
    }
  }
Esempio n. 7
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();
  }
Esempio n. 8
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();
   }
 }
Esempio n. 9
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();
  }
Esempio n. 11
0
  private void doRun(final Test testSuite) {
    setButtonLabel(fRun, "Stop");
    fRunner =
        new Thread("TestRunner-Thread") {
          public void run() {
            UnitTestRunner.this.start(testSuite);
            postInfo("Running...");

            long startTime = System.currentTimeMillis();
            testSuite.run(fTestResult);

            if (fTestResult.shouldStop()) {
              postInfo("Stopped");
            } else {
              long endTime = System.currentTimeMillis();
              long runTime = endTime - startTime;
              postInfo("Finished: " + elapsedTimeAsString(runTime) + " seconds");
            }
            runFinished(testSuite);
            setButtonLabel(fRun, "Run");
            showIDE(true);
            fRunner = null;
            System.gc();
          }
        };
    // make sure that the test result is created before we start the
    // test runner thread so that listeners can register for it.
    fTestResult = createTestResult();
    fTestResult.addListener(UnitTestRunner.this);
    aboutToStart(testSuite);

    fRunner.start();
  }
Esempio n. 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();
  }
Esempio n. 13
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);
  }
Esempio n. 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();
 }
Esempio n. 15
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();
    }
Esempio n. 16
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();
  }
Esempio n. 17
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();
  }
Esempio n. 18
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);
      }
    }
Esempio n. 19
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.
    }
  }
Esempio n. 20
0
 public void actionPerformed(ActionEvent ae) {
   String action = ae.getActionCommand();
   if (action.equals("refresh")) {
     routerThread = new Thread(this);
     routerThread.start();
   }
 }
  /** 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();
  }
 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();
  }
Esempio n. 24
0
  public void actionPerformed(ActionEvent ae) {

    if (ae.getSource() == this.buttonStart && !animate) {
      animate = true;
      animatorThread = new Thread(animator);
      animatorThread.start();
    }

    if (ae.getSource() == this.buttonStop && animate) {
      animate = false;
      animatorThread = null;
    }

    if (ae.getSource() == this.buttonNextRound && !animate) {
      board.nextRound();
      numOfGenerations++;
      grid.setBoard(board.getCurrentRound());
      grid.repaint();
      generationsLabel.setText("Generation " + numOfGenerations);
    }

    if (ae.getSource() == this.buttonClearBoard && !animate) {
      board.clear();
      this.numOfGenerations = 0;
      grid.repaint();
      generationsLabel.setText("Generation " + numOfGenerations);
    }

    if (ae.getSource() == this.drawingCheckBox) {
      draw = drawingCheckBox.isSelected();
    }
  }
Esempio n. 25
0
 private void startGame()
       // initialise and start the thread
     {
   if (animator == null || !running) {
     animator = new Thread(this);
     animator.start();
   }
 } // end of startGame()
Esempio n. 26
0
  public BeatBar() {

    thread = new Thread(this);

    setMaximum(100);

    thread.start();
  }
Esempio n. 27
0
  public void startGame() {
    thread = new Thread(this);
    thread.start();

    // play song and loop
    ObjectWaitingForSongToEnd waiter = new ObjectWaitingForSongToEnd();
    SongPlayer.playFile(waiter, baseDir + "space_clips.mp3");
  }
  public void start() { // when user enters applet

    if (runner == null) {

      runner = new Thread(this);
      runner.start();
    }
  }
Esempio n. 29
0
  public PanelForSquare() {
    setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
    setBackground(Color.white);

    Thread thread = new Thread(this);
    initTimer();
    thread.start();
  }
Esempio n. 30
0
 public void start(Game.Spiel senso) {
   this.setVisible(true);
   // new Senso();
   s = senso;
   neustarten(true);
   läuft = true;
   spiel = new Thread(this);
   spiel.start();
 }