Example #1
0
 public static void main(String[] args) throws Exception {
   try {
     Settings settings = Settings.init();
     new GalaxyViewer(settings, false);
   } catch (Exception ex) {
     ex.printStackTrace();
     System.err.println(ex.toString());
     JOptionPane.showMessageDialog(null, ex.toString());
     System.exit(0);
   }
 }
Example #2
0
  protected String gettitle(String strFreq) {
    StringBuffer sbufTitle = new StringBuffer().append("VnmrJ  ");
    String strPath = FileUtil.openPath(FileUtil.SYS_VNMR + "/vnmrrev");
    BufferedReader reader = WFileUtil.openReadFile(strPath);
    String strLine;
    String strtype = "";
    if (reader == null) return sbufTitle.toString();

    try {
      while ((strLine = reader.readLine()) != null) {
        strtype = strLine;
      }
      strtype = strtype.trim();
      if (strtype.equals("merc")) strtype = "Mercury";
      else if (strtype.equals("mercvx")) strtype = "Mercury-Vx";
      else if (strtype.equals("mercplus")) strtype = "MERCURY plus";
      else if (strtype.equals("inova")) strtype = "INOVA";
      String strHostName = m_strHostname;
      if (strHostName == null) strHostName = "";
      sbufTitle.append("    ").append(strHostName);
      sbufTitle.append("    ").append(strtype);
      sbufTitle.append(" - ").append(strFreq);
      reader.close();
    } catch (Exception e) {
      // e.printStackTrace();
      Messages.logError(e.toString());
    }

    return sbufTitle.toString();
  }
 private void ListValueChanged(
     javax.swing.event.ListSelectionEvent evt) { // GEN-FIRST:event_ListValueChanged
   // TODO add your handling code here:
   // String part=partno.getText();
   try {
     String sql =
         "SELECT  TYPE,ITEM_NAME,QUANTITY,MRP FROM MOTORS WHERE ITEM_NAME='"
             + List.getSelectedValue()
             + "'";
     Class.forName("com.mysql.jdbc.Driver");
     Connection con =
         (Connection)
             DriverManager.getConnection("jdbc:mysql://localhost:3306/bharatmotors", "root", "");
     Statement stmt = con.createStatement();
     ResultSet rs = stmt.executeQuery(sql);
     while (rs.next()) {
       partno.setText(rs.getString("TYPE"));
       name.setText(rs.getString("ITEM_NAME"));
       qty.setText(rs.getString("QUANTITY"));
       rate.setText(rs.getString("MRP"));
     }
   } catch (Exception e) {
     JOptionPane.showMessageDialog(null, e.toString());
   }
 } // GEN-LAST:event_ListValueChanged
Example #4
0
  /**
   * A convenient method for view the ASpace json records. It meant to be used for development
   * purposes only
   */
  private void viewRecordButtonActionPerformed() {
    String uri = recordURIComboBox.getSelectedItem().toString();
    String recordJSON = "";

    try {
      if (aspaceClient == null) {
        String host = hostTextField.getText().trim();
        String admin = adminTextField.getText();
        String adminPassword = adminPasswordTextField.getText();

        aspaceClient = new ASpaceClient(host, admin, adminPassword);
        aspaceClient.getSession();
      }

      recordJSON = aspaceClient.getRecordAsJSONString(uri, paramsTextField.getText());

      if (recordJSON == null || recordJSON.isEmpty()) {
        recordJSON = aspaceClient.getErrorMessages();
      }
    } catch (Exception e) {
      recordJSON = e.toString();
    }

    CodeViewerDialog codeViewerDialog =
        new CodeViewerDialog(this, SyntaxConstants.SYNTAX_STYLE_JAVASCRIPT, recordJSON, true, true);
    codeViewerDialog.setTitle("REST ENDPOINT URI: " + uri);
    codeViewerDialog.pack();
    codeViewerDialog.setVisible(true);
  }
Example #5
0
  private void isEdit(Boolean isEdit) {
    if (isEdit) {
      try {
        Connection con = FrameLogin.getConnect();
        String sql = "SELECT * FROM Persons WHERE personId = " + Id;
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.first()) {
          String firstname = rs.getString("FirstName");
          String lastname = rs.getString("LastName");
          String cellphone = rs.getString("CellPhoneNo");
          String homephone = rs.getString("HomePhoneNo");
          String gradyear = rs.getString("Graduation Year");
          String Gender = rs.getString("Gender");

          firstName.setText(firstname);
          lastName.setText(lastname);
          cellPhone.setText(cellphone);
          homePhone.setText(homephone);
          gradYear.setText(gradyear);
          gender.setSelectedItem(Gender);
          jLabel7.setVisible(false);
          studentId.setVisible(false);

        } else {
          MessageBox.infoBox("Error: ID not found", "Error");
        }
      } catch (Exception e) {
        MessageBox.infoBox(e.toString(), "Error in isEdit");
      }
    }
    FrameLogin.closeConnect();
  }
 public void windowClosing(WindowEvent e) // write file on finish
     {
   FileOutputStream out = null;
   ObjectOutputStream data = null;
   try {
     // open file for output
     out = new FileOutputStream(DB);
     data = new ObjectOutputStream(out);
     // write Person objects to file using iterator class
     Iterator<Person> itr = persons.iterator();
     while (itr.hasNext()) {
       data.writeObject((Person) itr.next());
     }
     data.flush();
     data.close();
   } catch (Exception ex) {
     JOptionPane.showMessageDialog(
         objUpdate.this,
         "Error processing output file" + "\n" + ex.toString(),
         "Output Error",
         JOptionPane.ERROR_MESSAGE);
   } finally {
     System.exit(0);
   }
 }
    // Creates a new thread, runs the program in that thread, and reports any errors as needed.
    private void run(String clazz) {
      try {
        // Makes sure the JVM resets if it's already running.
        if (JVMrunning) kill();

        // Some String constants for java path and OS-specific separators.
        String separator = System.getProperty("file.separator");
        String path = System.getProperty("java.home") + separator + "bin" + separator + "java";

        // Tries to run compiled code.
        ProcessBuilder builder = new ProcessBuilder(path, clazz);

        // Should be good now! Everything past this is on you. Don't mess it up.
        println(
            "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr);
        println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr);

        JVM = builder.start();

        // Note that as of right now, there is no support for input. Only output.
        Reader errorReader = new InputStreamReader(JVM.getErrorStream());
        Reader outReader = new InputStreamReader(JVM.getInputStream());
        // Writer inReader = new OutputStreamWriter(JVM.getOutputStream());

        redirectErr = redirectIOStream(errorReader, err);
        redirectOut = redirectIOStream(outReader, out);
        // redirectIn = redirectIOStream(null, inReader);
      } catch (Exception e) {
        // This catches any other errors we might get.
        println("Some error thrown", progErr);
        logError(e.toString());
        displayLog();
        return;
      }
    }
    /** Displays the labels and the values for the panel. */
    protected void displayPnlFields(HashMap hmPnl) {
      if (hmPnl == null || hmPnl.isEmpty()) return;

      Iterator keySetItr = hmPnl.keySet().iterator();
      String strLabel = "";
      String strValue = "";

      // if the file is empty, then create an empty set of textfields.
      if (hmPnl == null || hmPnl.isEmpty()) {
        displayNewTxf("", "");
        return;
      }

      Container container = getParent();
      if (container != null) container.setVisible(false);
      try {
        // Get each set of label and value, and display them.
        while (keySetItr.hasNext()) {
          strLabel = (String) keySetItr.next();
          strValue = (String) hmPnl.get(strLabel);

          displayNewTxf(strLabel, strValue);
        }

        if (container != null) container.setVisible(true);
        revalidate();
        repaint();
      } catch (Exception e) {
        Messages.writeStackTrace(e);
        // e.printStackTrace();
        Messages.postDebug(e.toString());
      }
    }
  /**
   * Provides an implementation of the <code>readProductNodes</code> interface method. Clients
   * implementing this method can be sure that the input object and eventually the subset
   * information has already been set.
   *
   * <p>
   *
   * <p>This method is called as a last step in the <code>readProductNodes(input, subsetInfo)</code>
   * method.
   *
   * @throws java.io.IOException if an I/O error occurs
   */
  @Override
  protected Product readProductNodesImpl() throws IOException {

    Product product;
    try {
      final File fileFromInput = ReaderUtils.getFileFromInput(getInput());
      dataDir = createDirectory(fileFromInput);
      dataDir.readProductDirectory();
      product = dataDir.createProduct();
      addCalibrationLUT(product, fileFromInput.getParentFile());
      product.getGcpGroup();
      product.setFileLocation(fileFromInput);
      product.setProductReader(this);
      product.setModified(false);

      final MetadataElement absRoot = AbstractMetadata.getAbstractedMetadata(product);
      isAscending = absRoot.getAttributeString(AbstractMetadata.PASS).equals("ASCENDING");
      isAntennaPointingRight =
          absRoot.getAttributeString(AbstractMetadata.antenna_pointing).equals("right");
    } catch (Exception e) {
      Debug.trace(e.toString());
      final IOException ioException = new IOException(e.getMessage());
      ioException.initCause(e);
      throw ioException;
    }

    return product;
  }
  public SponserImage(String FileName) {

    File temp = new File(filePath);

    if (!(temp.exists())) {

      temp.mkdir();
    }

    File imageFile = new File(filePath + FileName);

    try {

      // images.add(ImageIO.read(imageFile));

      image = ImageIO.read(imageFile);

    } catch (Exception e) {

      System.out.println(e.toString());
    }

    // changeImage(0);

  }
  /**
   * Actions-handling method.
   *
   * @param e The event.
   */
  public void actionPerformed(ActionEvent e) {
    // Prepares the file chooser
    JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(new File(idata.getInstallPath()));
    fc.setMultiSelectionEnabled(false);
    fc.addChoosableFileFilter(fc.getAcceptAllFileFilter());
    // fc.setCurrentDirectory(new File("."));

    // Shows it
    try {
      if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        // We handle the xml data writing
        File file = fc.getSelectedFile();
        FileOutputStream out = new FileOutputStream(file);
        BufferedOutputStream outBuff = new BufferedOutputStream(out, 5120);
        parent.writeXMLTree(idata.xmlData, outBuff);
        outBuff.flush();
        outBuff.close();

        autoButton.setEnabled(false);
      }
    } catch (Exception err) {
      err.printStackTrace();
      JOptionPane.showMessageDialog(
          this,
          err.toString(),
          parent.langpack.getString("installer.error"),
          JOptionPane.ERROR_MESSAGE);
    }
  }
  public void run() {
    try {

      setStatus("Gathering chunks...");
      gatherChunks();
      createCompositeCanvas();
      setStatus("Sorting chunks...");
      sortChunks();
      java.util.List<BufferedImage> batchImages = new ArrayList<BufferedImage>();
      java.util.List<Chunk> nextBatch = new ArrayList<Chunk>();
      int totalChunks = getTotalChunks();
      int chunksRendered = 0;
      while (hasChunks()) {
        getNextBatch(nextBatch);
        setStatus("Rendering... " + chunksRendered + "/" + totalChunks);
        renderChunkBatch(nextBatch, batchImages);
        chunksRendered += nextBatch.size();
        renderBatchResult(nextBatch, batchImages);
      }
      setStatus("Writing image...");
      writeAndDisplayImage();
    } catch (final Exception e) {
      e.printStackTrace();
      if (frame != null) {
        setStatus("Exception: " + e.toString());
      }
    }
  }
Example #13
0
  void enableLionFS() {
    try {
      String version = System.getProperty("os.version");
      String[] tokens = version.split("\\.");
      int major = Integer.parseInt(tokens[0]), minor = 0;
      if (tokens.length > 1) minor = Integer.parseInt(tokens[1]);
      if (major < 10 || (major == 10 && minor < 7))
        throw new Exception("Operating system version is " + version);

      Class fsuClass = Class.forName("com.apple.eawt.FullScreenUtilities");
      Class argClasses[] = new Class[] {Window.class, Boolean.TYPE};
      Method setWindowCanFullScreen = fsuClass.getMethod("setWindowCanFullScreen", argClasses);
      setWindowCanFullScreen.invoke(fsuClass, this, true);

      Class fsListenerClass = Class.forName("com.apple.eawt.FullScreenListener");
      InvocationHandler fsHandler = new MyInvocationHandler(cc);
      Object proxy =
          Proxy.newProxyInstance(
              fsListenerClass.getClassLoader(), new Class[] {fsListenerClass}, fsHandler);
      argClasses = new Class[] {Window.class, fsListenerClass};
      Method addFullScreenListenerTo = fsuClass.getMethod("addFullScreenListenerTo", argClasses);
      addFullScreenListenerTo.invoke(fsuClass, this, proxy);

      canDoLionFS = true;
    } catch (Exception e) {
      vlog.debug("Could not enable OS X 10.7+ full-screen mode:");
      vlog.debug("  " + e.toString());
    }
  }
Example #14
0
 // run the job
 public void run() {
   try {
     runX();
   } catch (Exception e) {
     System.err.println(e.toString());
   }
 }
Example #15
0
  @Override
  public Result printReceiptMoneyOut(Path receiptsFile) {
    try {
      PosReceipt posReceipt = PosReceipt.getFromJSON(receiptsFile);

      List<String> lines =
          Files.readAllLines(
              rootPath.resolve(Paths.get("templates", "receipt_money_out.txt")),
              Charset.defaultCharset());

      String receipt = "";
      for (String line : lines) {
        line = line.replaceAll("\\{cash\\}", "" + posReceipt.getCash());
        line = line.replaceAll("\\{fiscal\\}", getFiscalString(posReceipt));

        receipt += line + "\r\n";
      }

      printStringList = Arrays.asList(receipt.split("\r\n"));
      printDoc();
      return Result.newEmptySuccess();

    } catch (Exception e) {
      Logger.getGlobal().log(Level.WARNING, null, e);
      return Result.newResultError(e.toString());
    }
  }
 /** Start talking to the server */
 public void start() {
   String codehost = getCodeBase().getHost();
   if (socket == null) {
     try {
       // Open the socket to the server
       socket = new Socket(codehost, port);
       // Create output stream
       out = new ObjectOutputStream(socket.getOutputStream());
       out.flush();
       // Create input stream and start background
       // thread to read data from the server
       in = new ObjectInputStream(socket.getInputStream());
       new Thread(this).start();
     } catch (Exception e) {
       // Exceptions here are unexpected, but we can't
       // really do anything (so just write it to stdout
       // in case someone cares and then ignore it)
       System.out.println("Exception! " + e.toString());
       e.printStackTrace();
       setErrorStatus(STATUS_NOCONNECT);
       socket = null;
     }
   } else {
     // Already started
   }
   if (socket != null) {
     // Make sure the right buttons are enabled
     start_button.setEnabled(false);
     stop_button.setEnabled(true);
     setStatus(STATUS_ACTIVE);
   }
 }
Example #17
0
    /**
     * @return String from the page
     * @throws Exception
     */
    private static String GetPHRAZE() throws Exception {
      String PHRAZE = "";
      try {
        URLConnection connection =
            new java.net.URL(Settings.GET_PANEL_URL() + "?key=" + Settings.GET_PANEL_KEYPHRAZE())
                .openConnection();
        InputStream ist = connection.getInputStream();
        InputStreamReader reader = new InputStreamReader(ist);
        char[] buffer = new char[256];
        int rc;
        StringBuilder sb = new StringBuilder();
        while ((rc = reader.read(buffer)) != -1) sb.append(buffer, 0, rc);
        reader.close();
        PHRAZE = String.valueOf(sb);
      } catch (Exception e) {

        PRINT("ERROR: " + e.toString() + " [Methods::OpenURL]", 1);
        // Thread.currentThread().stop();
        Thread.currentThread().interrupt();
        return "";
      }

      if (Settings.GET_DO_ONLY_ONCE()) {
        if (Objects.equals(PHRAZE, PREVIOUS_PHRAZE)) {
          Thread.currentThread().interrupt();
          return "";
        } else {
          PREVIOUS_PHRAZE = PHRAZE;
        }
      }
      return PHRAZE;
    }
Example #18
0
    protected void buildPanel(String strPath) {
      BufferedReader reader = WFileUtil.openReadFile(strPath);
      String strLine;

      if (reader == null) return;

      try {
        while ((strLine = reader.readLine()) != null) {
          if (strLine.startsWith("#") || strLine.startsWith("%") || strLine.startsWith("@"))
            continue;

          StringTokenizer sTokLine = new StringTokenizer(strLine, ":");

          // first token is the label e.g. Password Length
          if (sTokLine.hasMoreTokens()) {
            createLabel(sTokLine.nextToken(), this);
          }

          // second token is the value
          String strValue = sTokLine.hasMoreTokens() ? sTokLine.nextToken() : "";
          if (strValue.equalsIgnoreCase("yes") || strValue.equalsIgnoreCase("no"))
            createChkBox(strValue, this);
          else createTxf(strValue, this);
        }
      } catch (Exception e) {
        Messages.writeStackTrace(e);
        // e.printStackTrace();
        Messages.postDebug(e.toString());
      }
    }
Example #19
0
  public BranchGroup createSceneGraph(URL url) {

    try {
      Loader loader = new com.sun.j3d.loaders.objectfile.ObjectFile();
      Scene scene = loader.load(url);
      BranchGroup bg = scene.getSceneGroup();
      System.out.println(bg);
      TransformGroup[] views = scene.getViewGroups();
      if (views != null) {
        for (int i = 0; i < views.length; i++) {
          System.out.print(views[i]);
        }
        if (views.length > 0) viewStart = views[0];
      }
      return bg;
    } catch (Exception ex) {
      // in case there was a problem, print the stack out
      ex.printStackTrace();
      // System.out.println(ex);
      add("South", new Label(ex.toString()));
      System.out.println("URL: " + url);
      BranchGroup bg = new BranchGroup();
      bg.addChild(new ColorCube());
      System.out.println(bg);
      return bg;
    }
  }
Example #20
0
 public void exceptionThrown(Exception e) {
   boolean hadRenderException = renderException != null;
   renderException = e;
   if (!hadRenderException) {
     repaint();
   }
   setToolTipText(e.toString());
 }
 public void SendString(String s) {
   try {
     socketOutput.write(s.getBytes());
     System.out.println("Sent:" + s);
   } catch (Exception e) {
     System.out.println(e.toString());
   }
 }
Example #22
0
  public boolean load(File file) {

    this.file = file;

    if (file != null && file.isFile()) {
      try {
        errStr = null;
        audioInputStream = AudioSystem.getAudioInputStream(file);

        fileName = file.getName();

        format = audioInputStream.getFormat();

      } catch (Exception ex) {
        reportStatus(ex.toString());
        return false;
      }
    } else {
      reportStatus("Audio file required.");
      return false;
    }

    numChannels = format.getChannels();
    sampleRate = (double) format.getSampleRate();
    sampleBitSize = format.getSampleSizeInBits();
    long frameLength = audioInputStream.getFrameLength();
    long milliseconds = (long) ((frameLength * 1000) / audioInputStream.getFormat().getFrameRate());
    double audioFileDuration = milliseconds / 1000.0;

    if (audioFileDuration > MAX_AUDIO_DURATION) duration = MAX_AUDIO_DURATION;
    else duration = audioFileDuration;

    frameLength = (int) Math.floor((duration / audioFileDuration) * (double) frameLength);

    try {
      audioBytes = new byte[(int) frameLength * format.getFrameSize()];
      audioInputStream.read(audioBytes);
    } catch (Exception ex) {
      reportStatus(ex.toString());
      return false;
    }

    getAudioData();

    return true;
  }
Example #23
0
  public boolean dbOpenList(Connection connection, String sql) {
    dbClearList();
    this.oldSql = sql;
    this.oldConnection = connection;
    // apre il resultset da abbinare
    ResultSet resu = null;
    ResultSetMetaData meta;
    try {
      stat = connection.createStatement();
      resu = stat.executeQuery(sql);
      meta = resu.getMetaData();

      if (meta.getColumnCount() > 1) {
        this.contieneChiavi = true;
      }

      // righe
      while (resu.next()) {
        for (int i = 1; i <= meta.getColumnCount(); ++i) {
          if (i == 1) {
            dbItems.add((Object) resu.getString(i));
            lm.addElement((Object) resu.getString(i));
          } else if (i == 2) {
            dbItemsK.add((Object) resu.getString(i));

            // debug
            // System.out.println("list:" + String.valueOf(i) + ":" + resu.getString(i));
          } else if (i == 3) {
            dbItemsK2.add((Object) resu.getString(i));
          }
        }
      }
      this.setModel(lm);

      // vado al primo
      if (dbTextAbbinato != null) {
        // debug
        // javax.swing.JOptionPane.showMessageDialog(null,this.getKey(0).toString());
        dbTextAbbinato.setText(this.getKey(0).toString());
      }

      return (true);
    } catch (Exception e) {
      javax.swing.JOptionPane.showMessageDialog(null, e.toString());
      e.printStackTrace();
      return (false);
    } finally {
      try {
        stat.close();
      } catch (Exception e) {
      }
      try {
        resu.close();
      } catch (Exception e) {
      }
      meta = null;
    }
  }
  public void connectItems(String query)
        // PRE:  query must be initialized
        // POST: Updates the list of Items based on the query.
      {
    String driver = "org.apache.derby.jdbc.ClientDriver"; // Driver for DB
    String url = "jdbc:derby://localhost:1527/ShopDataBase"; // Url for DB
    String user = "******"; // Username for db
    String pass = "******"; // Password for db
    Connection myConnection; // Connection obj to db
    Statement stmt; // Statement to execute a result appon
    ResultSet results; // A set containing the returned results
    int rowcount; // Num objects in the resultSet
    int i; // Index for the array

    try { // Try connection to db

      Class.forName(driver).newInstance(); // Create our db driver

      myConnection = DriverManager.getConnection(url, user, pass); // Initalize our connection

      stmt =
          myConnection.createStatement(
              ResultSet.TYPE_SCROLL_INSENSITIVE,
              ResultSet.CONCUR_UPDATABLE); // Create a new statement
      results = stmt.executeQuery(query); // Store the results of our query

      rowcount = 0;
      if (results.last()) // Go to the last result
      {
        rowcount = results.getRow();
        results.beforeFirst();
      }
      itemsArray = new Item[rowcount];

      i = 0;
      while (results.next()) // Itterate through the results set
      {
        itemsArray[i] =
            new Item(
                results.getInt("item_id"),
                results.getString("item_name"),
                results.getString("item_type"),
                results.getInt("price"),
                results.getInt("owner_id"),
                results.getString("item_path")); // Creat new Item
        i++;
      }

      results.close(); // Close the ResultSet
      stmt.close(); // Close the statement
      myConnection.close(); // Close the connection to db

    } catch (Exception e) // Cannot connect to db
    {
      System.err.println(e.toString());
      System.err.println("Error, something went horribly wrong in connectItems!");
    }
  }
 public static void main(String[] args) {
   try {
     @SuppressWarnings("unused")
     MainWindow window = new MainWindow();
   } catch (Exception e) {
     e.printStackTrace();
     System.out.println(e.toString());
   }
 }
 private void openContentDirectory() {
   try {
     if (Desktop.isDesktopSupported()) {
       Desktop.getDesktop().open(new File(ForgeConstants.CACHE_DIR));
     }
   } catch (final Exception e) {
     System.out.println("Unable to open Directory: " + e.toString());
   }
 }
Example #27
0
  public void run() {
    int i = -1, tx = -1, ty = -1, alive_cnt;
    int[] dx = {0, 1, 0, -1};
    int[] dy = {-1, 0, 1, 0};
    Graphics g = getGraphics();

    while (true) {
      try {
        alive_cnt = 0;
        for (i = 0; i < NUM_PLAYERS; i++) {
          if (palive[i] == 1) {
            if (i > 0) DoAI(i);
            tx = px[i] + dx[pdir[i]];
            ty = py[i] + dy[pdir[i]];
            if ((tx < 0)
                || (tx >= SIZE_X)
                || (ty < 0)
                || (ty >= SIZE_Y)
                || (map[tx + ty * SIZE_X] != 0)) {
              palive[i] = 0;
            } else {
              px[i] = tx;
              py[i] = ty;
              map[tx + ty * SIZE_X] = (byte) (i + 1);
            }
          }
          if (palive[i] == 1) {
            alive_cnt++;
            g.setColor(new Color(pcolor[i]));
            g.drawLine(px[i], py[i], px[i], py[i]);
          }
        }
        if (palive[0] == 0) {
          g.setColor(new Color(0xff7070));
          g.drawString("You Lose!", 50, 120);
          repaint();
          stop();
        } else if (alive_cnt == 1) {
          g.setColor(new Color(0x7070ff));
          g.drawString("You Win!", 50, 120);
          repaint();
          stop();
        }

        repaint();
        Thread.sleep(25);
      } catch (InterruptedException e) {

        g.drawString("IException!", 50, 100);
        repaint();
        stop();
      } catch (Exception e) {
        g.drawString("Exception:" + e.toString() + "\n", 50, 100);
        repaint();
      }
    }
  }
  public String generatePieChart(
      String hitOrdNum, HttpSession session, PrintWriter pw, String courseId, int studentId) {
    /* int groupId=0;
                if (groupName.equals("All")){
                    groupId=0;
                }else{
                     groupId = studStatisticBean.getGroupIdByName(groupName);
    }*/
    String filename = null;
    try {
      //  Retrieve list of WebHits
      StudentsConceptChartDataSet whDataSet =
          new StudentsConceptChartDataSet(studStatisticBean, courseId, studentId);
      ArrayList list = whDataSet.getDataBySection(hitOrdNum);

      //  Throw a custom NoDataException if there is no data
      if (list.size() == 0) {
        System.out.println("No data has been found");
        throw new NoDataException();
      }

      //  Create and populate a PieDataSet
      DefaultPieDataset data = new DefaultPieDataset();
      Iterator iter = list.listIterator();
      while (iter.hasNext()) {
        StudentsConceptHit wh = (StudentsConceptHit) iter.next();
        data.setValue(wh.getSection(), wh.getHitDegree());
      }

      //  Create the chart object
      PiePlot plot = new PiePlot(data);
      plot.setInsets(new Insets(0, 5, 5, 5));
      plot.setURLGenerator(new StandardPieURLGenerator("xy_chart.jsp", "section"));
      plot.setToolTipGenerator(new StandardPieItemLabelGenerator());
      JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
      chart.setBackgroundPaint(java.awt.Color.white);

      //  Write the chart image to the temporary directory
      ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
      filename = ServletUtilities.saveChartAsPNG(chart, 600, 400, info, session);

      //  Write the image map to the PrintWriter
      ChartUtilities.writeImageMap(pw, filename, info);
      pw.flush();

    } catch (NoDataException e) {
      System.out.println(e.toString());
      filename = "public_nodata_500x300.png";
    } catch (Exception e) {
      System.out.println("Exception - " + e.toString());
      e.printStackTrace(System.out);
      filename = "public_error_500x300.png";
    }

    return filename;
  }
Example #29
0
 private void formWindowClosing(
     java.awt.event.WindowEvent evt) { // GEN-FIRST:event_formWindowClosing
   // TODO add your handling code here:
   Connection con = getConnect();
   try {
     // con.close();
   } catch (Exception err) {
     MessageBox.infoBox(err.toString(), "Error closing connection in formWindowClosed");
   }
 } // GEN-LAST:event_formWindowClosing
Example #30
0
  /**
   * Shows an alert dialog for when an exception occurs.
   *
   * @param e the exception to show
   * @param title the title of the dialog
   */
  public static void debug(Exception e, String title) {
    e.printStackTrace();
    String text = "<i>" + e.toString() + "</i><br>";
    // add stack trace
    for (StackTraceElement ste : e.getStackTrace()) {
      text += ste.toString() + "<br>";
    }
    text += "<br><b>Please take a screenshot and email it to <u>[email protected]</u>.</b>";

    showDialog(null, "<html>Sorry! Cabra has encountered an error. Details:<br><br>" + text, title);
  }