Exemplo n.º 1
0
  /** Initializes the core phone objects. */
  private void initializePhone() {
    // Load Preferences
    loadPreferences();

    if (preferences == null) {
      return;
    }

    guiManager = new GuiManager();
    guiManager.addUserActionListener(this);
    logManager = new LogManagerImpl(this);

    this.getLogManager().setRemoteLogging(true);

    try {
      EventQueue.invokeAndWait(
          new Runnable() {
            @Override
            public void run() {
              registerMenu = new JCheckBoxMenuItem(PhoneRes.getIString("phone.enabled"));
            }
          });
    } catch (Exception e) {
      Log.error(e);
    }

    registerMenu.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
            if (getStatus() == SipRegisterStatus.Unregistered
                || getStatus() == SipRegisterStatus.RegistrationFailed) {

              register();
            } else {
              handleUnregisterRequest();
            }
          }
        });

    SIPConfig.setPreferredNetworkAddress(preferences.getPreferredAddress());
    NetworkAddressManager.start();

    try {
      EventQueue.invokeAndWait(
          new Runnable() {
            @Override
            public void run() {
              // Initialize Missed calls
              missedCalls = new MissedCalls();
            }
          });
    } catch (Exception e) {
      Log.error(e);
    }

    final JMenu actionsMenu =
        SparkManager.getMainWindow().getMenuByName(Res.getString("menuitem.actions"));
    actionsMenu.add(registerMenu);
  }
Exemplo n.º 2
0
  /**
   * Konstruktøren. Initierer rammen og canvaset som det skal tegnes i.
   *
   * @param gameName : String - Tittel på JFrame
   */
  public DisplayManager(String gameName) {
    frame = new JFrame(gameName);
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.setIgnoreRepaint(true);
    frame.setSize(WIDTH, HEIGHT);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.setCursor(getInvisibleCursor());
    frame.setIconImage(new ImageIcon("images/ico.ico").getImage());

    // Oppretter en buffer for å hindre "tearing" i grafikken.
    try {
      EventQueue.invokeAndWait(
          new Runnable() {
            @Override
            public void run() {
              frame.createBufferStrategy(2);
            }
          });
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 3
0
 @Override
 public Node.PropertySet[] getPropertySets() {
   final Node.PropertySet[][] props = new Node.PropertySet[1][];
   Runnable runnable =
       new Runnable() {
         @Override
         public void run() {
           FormLAF.executeWithLAFLocks(
               new Runnable() {
                 @Override
                 public void run() {
                   props[0] = component.getProperties();
                 }
               });
         }
       };
   if (EventQueue.isDispatchThread()) {
     runnable.run();
   } else {
     try {
       // We have made some attempts to keep initialization
       // of properties outside AWT thread, but it always
       // deadlocked with AWT thread for various reasons.
       EventQueue.invokeAndWait(runnable);
     } catch (InterruptedException iex) {
       FormUtils.LOGGER.log(Level.INFO, iex.getMessage(), iex);
     } catch (InvocationTargetException itex) {
       FormUtils.LOGGER.log(Level.INFO, itex.getMessage(), itex);
     }
   }
   return props[0];
 }
Exemplo n.º 4
0
  private void initUI() throws InitializationException {
    // Settings Dialog
    try {
      EventQueue.invokeAndWait(
          new Runnable() {
            @Override
            public void run() {
              settingsDialog = new SettingsDialog();

              for (Profile p : config.getProfiles().list()) {
                settingsDialog.addProfileToTree(p, false);
              }
            }
          });
    } catch (InterruptedException ex) {
      logger.log(Level.SEVERE, "Unable to init SettingsDialog.", ex);
      throw new InitializationException(ex);
    } catch (InvocationTargetException ex) {
      logger.log(Level.SEVERE, "Unable to init SettingsDialog.", ex);
      throw new InitializationException(ex);
    }

    // Tray
    tray.init("Everything is up to date.");
    tray.addTrayEventListener(new TrayEventListenerImpl());
    tray.updateUI();

    // Desktop integration
    if (config.isServiceEnabled()) {
      desktop.start(); // must be started before indexer!
    }
  }
Exemplo n.º 5
0
  public void run() {
    do {
      try {
        Thread.sleep(time);
      } catch (InterruptedException e) {
        // Auto-generated catch block
        throw new RuntimeException(e);
      }

      if (run != this.runtime.runNumber) {
        break;
      }

      if (EventQueue.isDispatchThread()) {
        runner.run(Context.enter());
      } else {
        try {
          EventQueue.invokeAndWait(runner);
        } catch (Exception e) {

          e.printStackTrace();
        }
      }
    } while (loop);
  }
Exemplo n.º 6
0
  public void doTest() throws Exception {

    try {

      robot.waitForIdle(delay);

      for (DialogOwner owner : DialogOwner.values()) {

        EventQueue.invokeLater(
            () -> {
              createGUI(owner);
            });

        robot.waitForIdle(delay);

        dialog.activated.waitForFlagTriggered();
        assertTrue(
            dialog.activated.flag(),
            "Dialog did not trigger " + "Window Activated event when it became visible");

        dialog.closeGained.waitForFlagTriggered();
        assertTrue(
            dialog.closeGained.flag(),
            "The 1st button did not " + "gain focus when the dialog became visible");

        dialog.checkUnblockedDialog(robot, "");
        robot.waitForIdle(delay);
      }

    } finally {
      EventQueue.invokeAndWait(this::closeAll);
    }
  }
Exemplo n.º 7
0
  public synchronized void expand() {
    if (EventQueue.isDispatchThread()) {
      EventQueue.invokeLater(
          new Runnable() {

            @Override
            public void run() {
              _expand();
            }
          });
    } else {
      try {
        EventQueue.invokeAndWait(
            new Runnable() {

              @Override
              public void run() {
                _expand();
              }
            });
      } catch (InterruptedException | InvocationTargetException e) {
        System.err.println(e);
      }
    }
  }
Exemplo n.º 8
0
 /** Repaints immediately the component. */
 public void immediateRepaint() {
   if (EventQueue.isDispatchThread()) {
     Rectangle visRect = getRenderRect();
     if (doubleBufferedRendering)
       repaint(
           visRect.x, visRect.y,
           visRect.width, visRect.height);
     else
       paintImmediately(
           visRect.x, visRect.y,
           visRect.width, visRect.height);
   } else {
     try {
       EventQueue.invokeAndWait(
           new Runnable() {
             public void run() {
               Rectangle visRect = getRenderRect();
               if (doubleBufferedRendering)
                 repaint(
                     visRect.x, visRect.y,
                     visRect.width, visRect.height);
               else
                 paintImmediately(
                     visRect.x, visRect.y,
                     visRect.width, visRect.height);
             }
           });
     } catch (Exception e) {
     }
   }
 }
Exemplo n.º 9
0
 /**
  * Displays a JFileChooser and then opens the tiff, dicom, fits, pgm, jpeg, bmp, gif, lut, roi, or
  * text files selected by the user. Displays error messages if one or more of the selected files
  * is not in one of the supported formats. This is the method that ImageJ's File/Open command uses
  * to open files if "Open/Save Using JFileChooser" is checked in EditOptions/Misc.
  */
 public void openMultiple() {
   Java2.setSystemLookAndFeel();
   // run JFileChooser in a separate thread to avoid possible thread deadlocks
   try {
     EventQueue.invokeAndWait(
         new Runnable() {
           public void run() {
             JFileChooser fc = new JFileChooser();
             fc.setMultiSelectionEnabled(true);
             File dir = null;
             String sdir = OpenDialog.getDefaultDirectory();
             if (sdir != null) dir = new File(sdir);
             if (dir != null) fc.setCurrentDirectory(dir);
             int returnVal = fc.showOpenDialog(IJ.getInstance());
             if (returnVal != JFileChooser.APPROVE_OPTION) return;
             omFiles = fc.getSelectedFiles();
             if (omFiles.length == 0) { // getSelectedFiles does not work on some JVMs
               omFiles = new File[1];
               omFiles[0] = fc.getSelectedFile();
             }
             omDirectory = fc.getCurrentDirectory().getPath() + File.separator;
           }
         });
   } catch (Exception e) {
   }
   if (omDirectory == null) return;
   OpenDialog.setDefaultDirectory(omDirectory);
   for (int i = 0; i < omFiles.length; i++) {
     String path = omDirectory + omFiles[i].getName();
     open(path);
     if (i == 0 && Recorder.record) Recorder.recordPath("open", path);
     if (i == 0 && !error) Menus.addOpenRecentItem(path);
   }
 }
Exemplo n.º 10
0
  public void doTest() throws Exception {

    try {
      dialog.activated.waitForFlagTriggered();
      assertTrue(
          dialog.activated.flag(),
          "Dialog did not trigger " + "Window Activated event when it became visible");

      dialog.closeGained.waitForFlagTriggered();
      assertTrue(
          dialog.closeGained.flag(),
          "the 1st Dialog button " + "did not gain focus when it became visible");

      assertTrue(
          dialog.closeButton.hasFocus(),
          "the 1st Dialog button " + "gained the focus but lost it afterwards");

      dialog.checkUnblockedDialog(robot, "Modal Dialog shouldn't be blocked.");

      if ((modalityType == Dialog.ModalityType.APPLICATION_MODAL)
          || (modalityType == Dialog.ModalityType.DOCUMENT_MODAL)
          || (modalityType == Dialog.ModalityType.TOOLKIT_MODAL)
          || dialog.isModal()) {
        parent.checkBlockedDialog(
            robot, "Dialog is the parent of a visible " + modalityType + " Dialog.");
      } else {
        parent.checkUnblockedDialog(
            robot, "Dialog is the parent of a visible " + modalityType + " Dialog.");
      }

      robot.waitForIdle(delay);
    } finally {
      EventQueue.invokeAndWait(this::closeAll);
    }
  }
Exemplo n.º 11
0
  private void createGUI() throws Exception {

    EventQueue.invokeAndWait(this::showParent);
    robot.waitForIdle(delay);
    EventQueue.invokeLater(this::showChild);
    robot.waitForIdle(delay);
  }
Exemplo n.º 12
0
 /**
  * ** Queues the invocation of the specified Runnable on the EventQueue, and waits for the
  * EventQueue ** thread to complete execution of the specified Runnable. ** @param r The Runnable
  * to execute
  */
 public static void invokeAndWait(Runnable r)
     throws InterruptedException, InvocationTargetException {
   if (r != null) {
     // call from a child thread only! (will block otherwise)
     // Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(r);
     EventQueue.invokeAndWait(r);
   }
 }
 /** This method switches execution to the GUI thread. */
 private void runOnEventQueue() {
   try {
     EventQueue.invokeAndWait(this);
   } catch (InterruptedException ie) {
   } catch (InvocationTargetException ite) {
     throw new RuntimeException(ite);
   }
 }
Exemplo n.º 14
0
 public static void main(String[] args) throws InterruptedException, InvocationTargetException {
   Examples.initializeLogging();
   EventQueue.invokeAndWait(
       new Runnable() {
         public void run() {
           new BoundJListExample();
         }
       });
 }
Exemplo n.º 15
0
  public RoarPreference() {

    _props = RoarProperties.getInstance();

    try {
      if (EventQueue.isDispatchThread()) {
        _prefPanel = new RoarPreferencePanel();
      } else {
        EventQueue.invokeAndWait(() -> _prefPanel = new RoarPreferencePanel());
      }
    } catch (Exception e) {
      Log.error(e);
    }
  }
Exemplo n.º 16
0
 /** Initializes the applet JavaPlayer */
 @Override
 public void init() {
   try {
     java.awt.EventQueue.invokeAndWait(
         new Runnable() {
           @Override
           public void run() {
             initComponents();
             initJMF();
           }
         });
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
  public NumericalInputPanelInteger(ElphelVision parent) {
    this.Parent = parent;

    try {
      java.awt.EventQueue.invokeAndWait(
          new Runnable() {

            public void run() {
              initComponents();
            }
          });
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Exemplo n.º 18
0
  /** Initializes the applet Consulta */
  @Override
  public void init() {
    /* Set the Nimbus look and feel */
    // <editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */

    try {
      for (javax.swing.UIManager.LookAndFeelInfo info :
          javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(Consulta.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(Consulta.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(Consulta.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(Consulta.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    }
    // </editor-fold>

    /* Create and display the applet */
    try {
      java.awt.EventQueue.invokeAndWait(
          new Runnable() {
            public void run() {
              initComponents();
              setImagen(RESOURCES_URL + "Background.jpg");
            }
          });
    } catch (NullPointerException ne) {
      mensajeErrorlb.setVisible(true);
      jScrollPane1.setVisible(false);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  public void doTest() throws Exception {

    robot.waitForIdle(delay);

    parent.clickOpenButton(robot);
    robot.waitForIdle(delay);

    dialog.activated.waitForFlagTriggered();
    assertTrue(
        dialog.activated.flag(),
        "Dialog did not trigger " + "Window Activated event when it became visible");

    dialog.closeGained.waitForFlagTriggered();
    assertTrue(
        dialog.closeGained.flag(),
        "the 1st button did not gain focus " + "when the Dialog became visible");

    assertTrue(
        dialog.closeButton.hasFocus(),
        "the 1st button in the Dialog " + "gained focus but lost it afterwards");

    dialog.openGained.reset();

    robot.type(KeyEvent.VK_TAB);

    dialog.openGained.waitForFlagTriggered();
    assertTrue(
        dialog.openGained.flag(),
        "Tab navigation did not happen properly on Dialog. Open button "
            + "did not gain focus on tab press when parent frame is visible");

    dialog.clickOpenButton(robot);
    robot.waitForIdle(delay);

    frame.activated.waitForFlagTriggered();
    assertTrue(
        frame.activated.flag(),
        "Frame did not trigger activated when "
            + "made visible. Dialog and its parent frame are visible");

    frame.checkUnblockedFrame(robot, "Frame is the parent of a visible Dialog.");
    window.checkUnblockedWindow(robot, "Frame and its child Dialog are visible.");

    robot.waitForIdle(delay);

    EventQueue.invokeAndWait(this::closeAll);
  }
Exemplo n.º 20
0
 public void scanFinshed(final int id, final String host) {
   if (EventQueue.isDispatchThread()) {
     scanFinshedEventHandler(id, host);
   } else {
     try {
       EventQueue.invokeAndWait(
           new Runnable() {
             @Override
             public void run() {
               scanFinshedEventHandler(id, host);
             }
           });
     } catch (Exception e) {
       log.error(e.getMessage(), e);
     }
   }
 }
Exemplo n.º 21
0
 public void write(final char[] cbuf, final int off, final int len) {
   try {
     // We use invokeAndWait so that terminal output is limited to
     // the processing speed of the event queue. This means the UI
     // will still respond to user input even if the output is really
     // gushing.
     EventQueue.invokeAndWait(
         new Runnable() {
           public void run() {
             initialise();
             writeToPane(!isErrorOut, new String(cbuf, off, len));
           }
         });
   } catch (InvocationTargetException ite) {
     ite.printStackTrace();
   } catch (InterruptedException ie) {
   }
 }
Exemplo n.º 22
0
 public void scanProgress(final int id, final String host, final int progress, final int maximum) {
   if (EventQueue.isDispatchThread()) {
     scanProgressEventHandler(id, host, progress, maximum);
   } else {
     try {
       EventQueue.invokeAndWait(
           new Runnable() {
             @Override
             public void run() {
               scanProgressEventHandler(id, host, progress, maximum);
             }
           });
     } catch (InterruptedException e) {
       log.info("Interrupt scan progress update on GUI.");
     } catch (Exception e) {
       log.error(e.getMessage(), e);
     }
   }
 }
Exemplo n.º 23
0
  @Override
  public void run() {
    OpenDLXSimulator openDLXSim = mf.getOpenDLXSim();
    // start running
    mf.setOpenDLXSimState(OpenDLXSimState.RUNNING);
    // check if running was paused/quit or if openDLXSim has finished
    while (!openDLXSim.isFinished() && mf.isRunning()) {
      // loop through openDLX, do a cycle
      try {
        openDLXSim.step();
      } catch (PipelineException e) {
        mf.getPipelineExceptionHandler().handlePipelineExceptions(e);
      }
    }
    // when running stops or openDLX has finished, set state back to executing, as executing means a
    // openDLX is loaded but not running through
    mf.setOpenDLXSimState(OpenDLXSimState.EXECUTING);

    try {
      EventQueue.invokeAndWait(
          new Runnable() {
            @Override
            public void run() {
              // update frames when loop is finished or paused (isRunning is set to false by event
              // dispatch thread/user)
              new CommandUpdateFrames(mf).execute();
            }
          });
    } catch (Exception e) {
      System.err.println(e.toString());
      e.printStackTrace();
    }

    if (openDLXSim
        .isFinished()) { // if the current openDLX has finished, dont allow any gui updates any more
      mf.setUpdateAllowed(false);
      new CommandSimulatorFinishedInfo().execute();
    }
  }
Exemplo n.º 24
0
  private static void updateSplash(final SplashScreen splash, final String string) {
    if (splash == null) {
      return;
    }
    try {
      EventQueue.invokeAndWait(
          new Runnable() {
            public void run() {
              Graphics2D g = splash.createGraphics();
              if (g != null) {
                // Splash is 320x120
                FontMetrics fm = g.getFontMetrics();

                // paint startup status
                g.setColor(Color.darkGray);
                int h = fm.getHeight() + fm.getMaxDescent();
                int x = 5;
                int y = 115;
                int w = 320 - 2 * x;
                g.fillRect(x, y - h, w, h);
                g.setColor(Color.lightGray);
                g.drawRect(x, y - h, w, h);
                g.setColor(Color.WHITE);
                int xw = fm.stringWidth(string);
                g.drawString(string, x + ((w - xw) / 2), y - 5);

                // paint version
                String ver = "v" + Constants.getVersion();
                int vw = g.getFontMetrics().stringWidth(ver);
                g.drawString(ver, 320 - vw - 5, 34);
                g.dispose();
                splash.update();
              }
            }
          });
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }
Exemplo n.º 25
0
  public void waitForRequests() {
    if (threads == null) return;

    synchronized (waitForAllLock) {
      while (requestCount != 0) {
        try {
          waitForAllLock.wait();
        } catch (InterruptedException ie) {
          Log.log(Log.ERROR, this, ie);
        }
      }
    }

    if (EventQueue.isDispatchThread()) {

      doAWTRequests();
    } else {
      try {
        EventQueue.invokeAndWait(new RunRequestsInAWTThread());
      } catch (Exception e) {
        Log.log(Log.ERROR, this, e);
      }
    }
  }
Exemplo n.º 26
0
  /**
   * Constructor for the singleton Boot object.
   *
   * @param args the arguments with which main() was invoked
   * @param props the properties (created from the args)
   */
  private Boot(String[] args, Properties props, final SplashLabel image) {
    // Display the splash window, and wait until it's been painted before
    // proceeding. Otherwise, the event thread may be occupied by BlueJ
    // starting up and the window might *never* be painted.

    try {
      EventQueue.invokeAndWait(
          new Runnable() {
            @Override
            public void run() {
              splashWindow = new SplashWindow(image);
              splashWindow.repaint(); // avoid delay before painting
            }
          });
      splashWindow.waitUntilPainted();
    } catch (InvocationTargetException ite) {
      ite.printStackTrace();
    } catch (InterruptedException ie) {
      ie.printStackTrace();
    }

    this.args = args;
    this.commandLineProps = props;
  }
Exemplo n.º 27
0
 KeyMaskTest() throws Exception {
   lock = new Object();
   robot = new ExtendedRobot();
   EventQueue.invokeAndWait(this::createGUI);
 }
Exemplo n.º 28
0
 public static void invokeAndWait(final Runnable r)
     throws InterruptedException, InvocationTargetException {
   EventQueue.invokeAndWait(r);
 }
Exemplo n.º 29
0
  /**
   * Finds the extents of the map, then takes a 'screenshot' of that area. If the user is the GM,
   * the extents include every object and everything that has any area, such as 'fog' and
   * 'visibility' objects.
   *
   * <p>If a background tiling texture is used, the image is aligned to it, so that it can be used
   * on re-import as a new base map image.
   *
   * <p>If the user is a player (or GM posing as a player), the extents only go as far as the
   * revealed fog-of-war.
   *
   * @return the image to be saved
   */
  private static BufferedImage takeEntireMapScreenShot() throws Exception, OutOfMemoryError {
    final ZoneRenderer renderer = TabletopTool.getFrame().getCurrentZoneRenderer();
    if (renderer == null) {
      throw (new Exception("renderer = NULL"));
    }

    boolean viewAsPlayer = ExportRadioButtons.VIEW_PLAYER.isChecked();

    //
    // First, figure out the 'extents' of the canvas
    //   This will be later modified by the fog (for players),
    //   and by the tiling texture (for re-importing)
    //
    final PlayerView view = new PlayerView(viewAsPlayer ? Player.Role.PLAYER : Player.Role.GM);
    Rectangle extents = renderer.zoneExtents(view);
    try {
      // Clip to what the players know about (if applicable).
      // This keeps the player from exporting the map to learn which
      // direction has more 'stuff' in it.

      if (viewAsPlayer) {
        Rectangle fogE = renderer.fogExtents();
        // TabletopTool.showError(fogE.x + " " + fogE.y + " " + fogE.width + " " + fogE.height);
        if ((fogE.width < 0) || (fogE.height < 0)) {
          TabletopTool.showError(
              I18N.getString(
                  "dialog.screenshot.error.negativeFogExtents")); // Image is not clipped to show
          // only fog-revealed areas!"));
        } else {
          extents = extents.intersection(fogE);
        }
      }
    } catch (Exception ex) {
      throw (new Exception(I18N.getString("dialog.screenshot.error.noArea"), ex));
    }
    if ((extents == null) || (extents.width == 0) || (extents.height == 0)) {
      throw (new Exception(I18N.getString("dialog.screenshot.error.noArea")));
    }

    // If output includes the tiling 'board' texture, move the upper-left corner
    // to an integer multiple of the background tile (so it matches up on import).
    // We don't need to move the lower-right corner because it doesn't matter for
    // aligning on importing.

    boolean drawBoard = ExportLayers.LAYER_BOARD.isChecked();
    if (drawBoard) {
      DrawablePaint paint = renderer.getZone().getBackgroundPaint();
      DrawableTexturePaint dummy = new DrawableTexturePaint();
      Integer tileX = 0, tileY = 0;

      if (paint.getClass() == dummy.getClass()) {
        Image bgTexture = ImageManager.getImage(((DrawableTexturePaint) paint).getAsset().getId());
        tileX = bgTexture.getWidth(null);
        tileY = bgTexture.getHeight(null);
        Integer x = ((int) Math.floor((float) extents.x / tileX)) * tileX;
        Integer y = ((int) Math.floor((float) extents.y / tileY)) * tileY;
        extents.width = extents.width + (extents.x - x);
        extents.height = extents.height + (extents.y - y);
        extents.x = x;
        extents.y = y;
      }
    }

    // Save the original state of the renderer to restore later.
    // Create a place to put the image, and
    // set up the renderer to encompass the whole extents of the map.

    Rectangle origBounds = renderer.getBounds();
    Scale origScale = renderer.getZoneScale();
    Dimension origSize = renderer.getSize();

    BufferedImage image = null;
    try {
      image = new BufferedImage(extents.width, extents.height, Transparency.OPAQUE);
    } catch (OutOfMemoryError me) {
      throw new OutOfMemoryError("image size = " + extents.width + " x " + extents.height);
    } catch (Exception e) {
      throw new Exception("image size = " + extents.width + " x " + extents.height, e);
    }

    final Graphics2D g = image.createGraphics();
    g.setClip(0, 0, extents.width, extents.height);
    Scale s = new Scale();
    s.setOffset(-extents.x, -extents.y);

    // Finally, draw the image.
    // Copied this thread concept from the original screenshot code in TabletopTool.
    //  Have to do this on the EDT so that there aren't any odd side effects
    //  of rendering using a renderer that's on screen.

    try {
      renderer.setZoneScale(s);
      renderer.setBounds(extents);
      renderer.setSize(extents.getSize());
      if (!EventQueue.isDispatchThread()) {
        EventQueue.invokeAndWait(
            new Runnable() {
              @Override
              public void run() {
                renderer.renderZone(g, view);
              }
            });
      } else {
        renderer.renderZone(g, view);
      }
      return image;
    } catch (OutOfMemoryError me) {
      throw new OutOfMemoryError("image size = " + extents.width + " x " + extents.height);
    } catch (InterruptedException ie) {
      TabletopTool.showError("While creating snapshot", ie);
    } catch (InvocationTargetException ite) {
      TabletopTool.showError("While creating snapshot", ite);
    } catch (Exception e) {
      throw new Exception("image size = " + extents.width + " x " + extents.height, e);
    } finally {
      g.dispose();
      // Restore original state
      renderer.setBounds(origBounds);
      renderer.setZoneScale(origScale);
      renderer.setSize(origSize);
    }
    // This is just to avoid the compiler error: it should be unreachable
    return null;
  }
Exemplo n.º 30
0
  public void run() {
    System.out.print("Your name is :");
    try {
      synchronized (Main.gigi) {
        Main.gigi.wait();
      }

    } catch (InterruptedException e1) {
      // TODO Auto-generated catch block

    }

    hero.setName(GUI.getStdin());
    hero.setGold(300);
    System.out.println(hero.getName());
    // SimplePlayer music = new SimplePlayer();
    int mapLevel = 1;
    m = new Map(9, mapLevel);
    try {
      EventQueue.invokeAndWait(
          new Runnable() {
            public void run() {
              try {
                mapGUI = new MapGUI(m, hero);
              } catch (Exception e) {
                e.printStackTrace();
              }
            }
          });
    } catch (InvocationTargetException | InterruptedException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    while (hero.getCurrentHitPoints() > 0) {
      mapGUI.update();
      mapGUI.repaint();

      // System.out
      //	.println("You are at :  X " + hero.getVerticalLocation() + "  Y  " +
      // hero.getHorizontalLocation());
      try {
        m.movePlayer(hero);
        if (m.getRoom(hero.getVerticalLocation(), hero.getHorizontalLocation())
            instanceof EmptyRoom) {
          System.out.println("This room is empty as f**k.");
        }
        if (m.getRoom(hero.getVerticalLocation(), hero.getHorizontalLocation())
            instanceof MonsterRoom) {
          MonsterRoom temp =
              (MonsterRoom) (m.getRoom(hero.getVerticalLocation(), hero.getHorizontalLocation()));
          if (temp.getMonster().isAlive() == false) {
            System.out.println("Monster is dead.");
          } else {
            Battle b = new Battle(hero, temp.getMonster());
            System.out.println("Current Gold : " + hero.getGold());
          }
        }
        if (m.getRoom(hero.getVerticalLocation(), hero.getHorizontalLocation())
            instanceof BossRoom) {
          BossRoom temp =
              (BossRoom) (m.getRoom(hero.getVerticalLocation(), hero.getHorizontalLocation()));
          Battle b = new Battle(hero, temp.getMonster());
          if (!temp.getMonster().isAlive()) {

            System.out.println("Current Gold : " + hero.getGold());
            System.out.println(
                temp.getMonster().getName() + " is dead,you delve deeper into the dungeon.");
            mapLevel++;
            m = new Map(9, mapLevel);
            mapGUI.hide();
            mapGUI = new MapGUI(m, hero);
            hero.setCurrentHitPoints(hero.getMaxHitPoints());
          }
        }
        if (m.getRoom(hero.getVerticalLocation(), hero.getHorizontalLocation())
            instanceof CityRoom) {
          Trader t = new Trader();
          Trade trade = new Trade(hero, t);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    // SQL.recordHighScore(hero.getName(), hero.getGold());
    System.out.println("YOU LOST!");
    // SQL.getHighScores();
  }