Exemplo n.º 1
0
 public void actionPerformed(ActionEvent event) {
   if (typePanel.getSelection().equals("Confirm"))
     JOptionPane.showConfirmDialog(
         OptionDialogFrame.this,
         getMessage(),
         "Title",
         getType(optionTypePanel),
         getType(messageTypePanel));
   else if (typePanel.getSelection().equals("Input")) {
     if (inputPanel.getSelection().equals("Text field"))
       JOptionPane.showInputDialog(
           OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
     else
       JOptionPane.showInputDialog(
           OptionDialogFrame.this,
           getMessage(),
           "Title",
           getType(messageTypePanel),
           null,
           new String[] {"Yellow", "Blue", "Red"},
           "Blue");
   } else if (typePanel.getSelection().equals("Message"))
     JOptionPane.showMessageDialog(
         OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
   else if (typePanel.getSelection().equals("Option"))
     JOptionPane.showOptionDialog(
         OptionDialogFrame.this,
         getMessage(),
         "Title",
         getType(optionTypePanel),
         getType(messageTypePanel),
         null,
         getOptions(),
         getOptions()[0]);
 }
 public void actionPerformed(ActionEvent e) {
   String name = null;
   name =
       JOptionPane.showInputDialog(
           objUpdate.this,
           "Enter a name (eg. John Russell)",
           "Input Person",
           JOptionPane.QUESTION_MESSAGE);
   if (!(name == null)) {
     // prompt the user for a date
     String date = null;
     date =
         JOptionPane.showInputDialog(
             objUpdate.this,
             "Enter Date (eg. 06/17/1946)",
             "Input Person",
             JOptionPane.QUESTION_MESSAGE);
     if (!(date == null)) {
       // convert String to Date
       try {
         Date d = f.parse(date);
         p = new Person(name, d);
         persons.add(p);
         index = persons.lastIndexOf(p);
         displayRecord();
       } catch (ParseException ex) {
         JOptionPane.showMessageDialog(
             objUpdate.this, "Invalid date format!", "Input Error", JOptionPane.ERROR_MESSAGE);
       }
     }
   }
 }
 @Override
 public void actionPerformed(ActionEvent e) {
   String chosen;
   chosen = JOptionPane.showInputDialog(Localization.lang("Choose the URL to download."), "");
   if (chosen == null) {
     return;
   }
   File toFile;
   try {
     String toName =
         FileDialogs.getNewFile(
             frame,
             new File(System.getProperty("user.home")),
             null,
             JFileChooser.SAVE_DIALOG,
             false);
     if (toName == null) {
       return;
     } else {
       toFile = new File(toName);
     }
     URL url = new URL(chosen);
     MonitoredURLDownload.buildMonitoredDownload(comp, url).downloadToFile(toFile);
     comp.setText(toFile.getPath());
   } catch (Exception ex) {
     JOptionPane.showMessageDialog(
         null,
         Localization.lang("Error downloading file '%0'", chosen),
         Localization.lang("Download failed"),
         JOptionPane.ERROR_MESSAGE);
   }
 }
Exemplo n.º 4
0
  public String generateDatabaseName() { // prompts user for database name
    String dbNameDefault = "MySQLDB";
    // String databaseName = "";

    do {
      databaseName =
          (String)
              JOptionPane.showInputDialog(
                  null,
                  "Enter the database name:",
                  "Database Name",
                  JOptionPane.PLAIN_MESSAGE,
                  null,
                  null,
                  dbNameDefault);
      if (databaseName == null) {
        DatabaseConvertGUI.setReadSuccess(false);
        return "";
      }
      if (databaseName.equals("")) {
        JOptionPane.showMessageDialog(null, "You must select a name for your database.");
      }
    } while (databaseName.equals(""));
    return databaseName;
  }
Exemplo n.º 5
0
  public String check(String s) {
    String error = machine.check();
    if (error != null) {
      JOptionPane.showMessageDialog(
          null,
          Localized.getString("faCannotStart") + "\n" + error,
          Localized.getString("error"),
          JOptionPane.INFORMATION_MESSAGE,
          null);
      return null;
    }

    if (s == null)
      s =
          (String)
              JOptionPane.showInputDialog(
                  null,
                  Localized.getString("faParseString"),
                  Localized.getString("faStartTitle"),
                  JOptionPane.QUESTION_MESSAGE,
                  null,
                  null,
                  null);

    return s;
  }
Exemplo n.º 6
0
  /**
   * AI personalities 1. Sarcastic Human 2. beep be be beep 3. General 4. Short Answers 5. Human (T)
   * 6. Random
   */
  public int AIreset() {
    String[] s = {
      "Sarcastic Robot",
      "Robot",
      "General Answers",
      "Short answers",
      "Boring robot",
      "Random Answers"
    };
    JFrame frame = new JFrame("Choose the AI");

    String personality =
        (String)
            JOptionPane.showInputDialog(
                frame,
                "Please Select the AI personality :",
                "Choices",
                JOptionPane.PLAIN_MESSAGE,
                null,
                s,
                "Sarcastic Robot");

    for (int i = 0; i < s.length; i++) {
      if (personality.equals(s[i])) {
        AIpersonality = i;
      }
    }
    return AIpersonality;
  }
Exemplo n.º 7
0
  private static int GetInteger(String message) {
    // Forward declarations
    int ret;
    String temp;
    // Infinite loop
    while (true) {
      try {
        // Show the input dialog
        temp = JOptionPane.showInputDialog(message);

        // Attempt to parse the integer
        ret = Integer.parseInt(temp);

        if (ret <= 0) {
          // If some non-exception happened, force one
          throw new NumberFormatException();
        }

        // If everything looks okay, return the integer
        return ret;
      }
      // Tell the user not to do bad things
      catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Please enter a valid integer.");
      } catch (NullPointerException e) {
        JOptionPane.showMessageDialog(null, "Please enter a valid integer.");
      }
    }
  }
Exemplo n.º 8
0
  // Sucecion de Fibonacci
  static void suce() {
    int numero, a = 1, b = 0, c;
    StringBuffer sb = new StringBuffer();
    String s1 =
        JOptionPane.showInputDialog("Ingrese el numero hasta el que desea ver la sucesion : ");
    numero = Integer.parseInt(s1);
    while (a < numero) {
      a += b;
      sb.append(a + " , ");
      b += a;
      sb.append(b + " , ");
    }

    JOptionPane.showMessageDialog(null, "Fibonacci = " + sb);

    int numero2 =
        JOptionPane.showOptionDialog(
            null,
            "Seleccione",
            "Escoja",
            JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            new Object[] {"Opcion 1", "Opcion 2", "Opcion 3"},
            "Opcion 3");
  }
Exemplo n.º 9
0
  public boolean createLink(
      GElementFAState source,
      String sourceAnchorKey,
      GElementFAState target,
      String targetAnchorKey,
      int shape,
      Point mouse) {
    String pattern =
        (String)
            JOptionPane.showInputDialog(
                null,
                Localized.getString("faNewLinkMessage"),
                Localized.getString("faNewLinkTitle"),
                JOptionPane.QUESTION_MESSAGE,
                null,
                null,
                null);
    if (pattern != null) {
      machine.addTransitionPattern(source.state.name, pattern, target.state.name);
      addElement(
          new GLink(
              source,
              sourceAnchorKey,
              target,
              targetAnchorKey,
              shape,
              pattern,
              mouse,
              GView.DEFAULT_LINK_FLATENESS));
    }

    return pattern != null;
  }
Exemplo n.º 10
0
  private void realizarVenta() {
    boolean cantidadCorrecta = false;
    String str = "",
        strError =
            "Debes introducir una cantidad válida. Recuerda : \n 1) Sólo debes introducir números enteros; positivos \n 2) Debes dejar a lo más cero artículos en 'stock'";
    String strExistencia = tfExistencia.getText(), clave = "";
    int cantidad = 0;
    int existencia = Integer.parseInt(strExistencia);

    while (cantidadCorrecta == false) {
      str = JOptionPane.showInputDialog(null, "Cantidad a Vender = ");
      try {
        cantidad = Integer.parseInt(str);
        if ((cantidad < 0) || (cantidad > existencia))
          JOptionPane.showMessageDialog(null, strError);
        else {
          cantidadCorrecta = true;
          clave = tfClave.getText();
          resultado = lista.venderArticulos(cantidad, existencia);
          habilitarCampos(true);
          habilitarBotones(true);
          print(resultado);
        }
      } catch (NumberFormatException nfe) {
        System.out.println("Error: " + nfe);
        JOptionPane.showMessageDialog(null, strError);
      }
    }
  }
 private void metricSelectorActionPerformed(
     java.awt.event.ActionEvent evt) { // GEN-FIRST:event_metricSelectorActionPerformed
   setSubstance();
   String selected = (String) metricSelector.getSelectedItem();
   if (selected.equalsIgnoreCase("Final Value")) {
     metric = new FinalValue(substance);
   } else if (selected.equalsIgnoreCase("Maximum Value")) {
     metric = new MaximumValue(substance);
   } else if (selected.equalsIgnoreCase("Minimum Value")) {
     metric = new MinimumValue(substance);
   } else if (selected.equalsIgnoreCase("Range")) {
     metric = new dynetica.objective.Range(substance);
   } else if (selected.equalsIgnoreCase("Maximum Rate")) {
     metric = new MaximumRate(substance);
   } else if (selected.equalsIgnoreCase("Area Under Curve")) {
     metric = new AreaUnderCurve(substance);
   } else if (selected.equalsIgnoreCase("Time to Steady State")) {
     double fraction = -1;
     while ((fraction < 0) || (fraction > 1)) {
       String fractionInput =
           JOptionPane.showInputDialog(
               this, "Fraction of steady state reached? (Between 0 and 1) ");
       fraction = Double.parseDouble(fractionInput);
     }
     metric = new TimeToSteadyState(substance, fraction);
   }
 } // GEN-LAST:event_metricSelectorActionPerformed
Exemplo n.º 12
0
 public void nameFocusLost(java.awt.event.FocusEvent evt) {
   ctxt.saveState = true;
   String newName = name.getText(), msg;
   while (!Library.validateFileName(newName, false)) {
     msg = "The name '" + newName + "' violates the rules for names:";
     msg += "\nIt must have 2 to 28 characters.";
     msg += "\nYou may not use BackSlash, ForwardSlash, Colon, DoubleQuote";
     msg += "\nAsterisk, QuestionMark, LeftAngleBracket, RightAngleBracket,";
     msg += "\nor the VerticalBar in a name. TRY AGAIN.";
     newName = JOptionPane.showInputDialog(msg);
   } //  end of harrass-em-until-they-give-a-good-name
   name.setText(newName);
   if (!newName.equals(ctxt.languageName)) { // Made a change
     msg = "Change this context's language name\nto" + newName + "?";
     String[] options = {newName, ctxt.languageName};
     int choice =
         JOptionPane.showOptionDialog(
             this,
             msg,
             "Confirm Changed Language Name",
             JOptionPane.YES_NO_OPTION,
             JOptionPane.QUESTION_MESSAGE,
             null,
             options,
             options[0]);
     if (choice == 0) { //  Change is confirmed
       ctxt.languageName = newName;
       msg =
           "Normally, the file name for a context is the same as the language name "
               + "\nfor that context.  Change this context's file name\n"
               + "to "
               + newName
               + "?";
       options[0] = "Change File Name";
       options[1] = "Do Not Change";
       choice =
           JOptionPane.showOptionDialog(
               this,
               msg,
               "Confirm Correct File Name",
               JOptionPane.YES_NO_OPTION,
               JOptionPane.QUESTION_MESSAGE,
               null,
               options,
               options[0]);
       if (choice == 0) {
         Library.userContextName = newName;
         if (SIL_Edit.edWin != null && ctxt == Library.contextUnderConstruction) {
           SIL_Edit.edWin.chart.changeFileName(newName);
         }
       }
     } //  end of Change-is-confirmed
   } //  end of change-was-made
 }
  public static void main(String s[]) {

    // Getting save directory
    String saveDir;
    if (s.length > 0) {
      saveDir = s[0];
    } else {
      saveDir =
          JOptionPane.showInputDialog(
              null,
              "Please enter directory where "
                  + "the images is/will be saved\n\n"
                  + "Also possible to specifiy as argument 1 when "
                  + "running this program.",
              "l:\\webcamtest");
    }

    String layout = "";
    if (s.length > 1) {
      layout = s[1];
    }

    // Move mouse to the point 5000,5000 px (out of the screen)
    Robot rob;
    try {
      rob = new Robot();
      rob.setAutoDelay(500); // 0,5 s
      rob.mouseMove(5000, 5000);
    } catch (AWTException e) {
      e.printStackTrace();
    }

    // Make the main window
    JFrame frame = new JFrame();
    frame.setAlwaysOnTop(true);
    frame.setTitle(
        "Webcam capture and imagefading - "
            + "Vitenfabrikken Jærmuseet - "
            + "made by Hallvard Nygård - "
            + "Vitenfabrikken.no / Jaermuseet.no");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setUndecorated(true);

    WebcamCaptureAndFadePanel panel = new WebcamCaptureAndFadePanel(saveDir, layout);
    frame.getContentPane().add(panel);
    frame.addKeyListener(panel);
    frame.pack();

    frame.setVisible(true);
  }
 public void actionPerformed(ActionEvent _evt) {
   String aCmd = _evt.getActionCommand();
   if (aCmd.equals("addPage")) {
     Object obj =
         JOptionPane.showInputDialog(
             getComponent(),
             res.getString("TabbedEditor.NewName"),
             res.getString("TabbedEditor.Rename"),
             JOptionPane.QUESTION_MESSAGE,
             null,
             null,
             getUniqueName(defaultString));
     if (obj == null) return;
     String txt = obj.toString().trim();
     if (txt.length() > 0) addPage(defaultType, txt, null, true);
     else addPage(defaultType, defaultString, null, true);
   } else if (aCmd.equals("upPage")) moveUpAndDownPage(true);
   else if (aCmd.equals("dnPage")) moveUpAndDownPage(false);
   else if (aCmd.equals("copyPage")) copyPage();
   else if (aCmd.equals("renamePage")) {
     Object obj =
         JOptionPane.showInputDialog(
             getComponent(),
             res.getString("TabbedEditor.NewName"),
             res.getString("TabbedEditor.Rename"),
             JOptionPane.QUESTION_MESSAGE,
             null,
             null,
             getCurrentPageName());
     if (obj == null) return;
     String txt = obj.toString().trim();
     if (txt.length() > 0) renameCurrentPage(txt);
   } else if (aCmd.equals("togglePage")) toggleCurrentPage();
   else if (aCmd.equals("removePage")) removeCurrentPage();
   // Update ODE list in Experiments
   if (defaultType.equals(Editor.EVOLUTION_EDITOR))
     ejs.getExperimentEditor().updateAllOdeList(aCmd);
 }
Exemplo n.º 15
0
 public void actionPerformed(ActionEvent evt) {
   Component parent = extensionButton.getParent();
   while ((parent != null) && !(parent instanceof Frame)) parent = parent.getParent();
   String newExtensions =
       JOptionPane.showInputDialog(
           parent,
           "Edit the extension list.\nSeparate extensions by commas.\n\n",
           filter.getExtensionString());
   if ((newExtensions != null) && !newExtensions.trim().equals("")) {
     newExtensions = newExtensions.replaceAll("\\s", "");
     filter.setExtensions(newExtensions);
     extensionButton.setText(filter.getDescription());
     properties.setProperty("extensions", filter.getExtensionString());
     directoryPane.reloadTree();
   }
 }
Exemplo n.º 16
0
  public PhoneBookGUI(PhoneBook pb) {
    super("PhoneBook");
    phoneBook = pb;

    setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

    Locale.setDefault(new Locale("en"));
    /* To avoid hardcoded Swedish text on OptionPane dialogs */
    UIManager.put("OptionPane.cancelButtonText", "Cancel");

    setLayout(new BorderLayout());
    JMenuBar menubar = new JMenuBar();
    setJMenuBar(menubar);

    JMenu editMenu = new JMenu("Edit");
    menubar.add(editMenu);
    editMenu.add(new AddMenu(phoneBook, this));
    editMenu.add(new RemoveMenu(phoneBook, this));
    JMenu findMenu = new JMenu("Find");
    menubar.add(findMenu);
    findMenu.add(new FindNumbersMenu(phoneBook, this));
    findMenu.add(new FindNamesMenu(phoneBook, this));
    JMenu viewMenu = new JMenu("View");
    menubar.add(viewMenu);
    viewMenu.add(new ShowAllMenu(phoneBook, this));

    JPanel southPanel = new JPanel();
    messageArea = new JTextArea(4, 25);
    messageArea.setEditable(false);
    southPanel.add(new JScrollPane(messageArea));
    southPanel.add(new QuitButton(phoneBook));
    add(southPanel, BorderLayout.CENTER);

    pack();
    setVisible(true);

    String fileName = JOptionPane.showInputDialog("Enter file name");
    if (fileName != null) {
      try {
        phoneBook.readFromFile(fileName);
      } catch (Exception e) {
        setText("No such file was found");
      }
    }
  }
Exemplo n.º 17
0
  // crear una sucesion de cuadrados
  static void cuadrado() {
    // 1, 4, 9, 16, 25, 36, 49, 64, 81,
    try {
      String s1 =
          JOptionPane.showInputDialog(
              "Ingrese un numero hasta la que desea ver la sucesion de cuadrados :");
      int limite = Integer.parseInt(s1);
      StringBuffer sb = new StringBuffer();
      for (int numero = 1, sqrt = 1; numero < limite; sqrt = ++numero * numero) {
        sb.append(sqrt + " , ");
      }

      int largo = sb.length();
      JOptionPane.showMessageDialog(null, "Sucesion sqrt = " + sb.delete(largo - 2, largo));
    } catch (NumberFormatException e) {
      JOptionPane.showMessageDialog(null, "No ha ingresado un numero !");
    }
  }
  private void jMenuItemNewProjectActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jMenuItemNewProjectActionPerformed
    String projectName = JOptionPane.showInputDialog(null, "Please enter a project name");

    if (projectName != null) {
      theProject = new Project(projectName);

      // now we've got a project we need to enalbe the save and close buttons
      jMenuItemSaveProject.setEnabled(true);
      jMenuItemCloseProject.setEnabled(true);
      jMenuItemViewDocuments.setEnabled(true);
      jMenuItemImport.setEnabled(true);

      // set title
      setTitle("LSAT - " + projectName);

      jMenuItemViewDocumentsActionPerformed(null);
    }
  } // GEN-LAST:event_jMenuItemNewProjectActionPerformed
Exemplo n.º 19
0
    protected void addNode() {

      String s =
          (String)
              JOptionPane.showInputDialog(
                  null, "Enter the node object:\n", "Add Node", JOptionPane.PLAIN_MESSAGE);

      // If a string was returned, say so.
      if ((s != null) && (s.length() > 0)) {
        try {
          graph.addObject(s);

        } catch (AlreadyMemberException e) {

          // custom title, custom icon
          JOptionPane.showMessageDialog(
              null, "Node for " + s + " already exists!", "Warning", JOptionPane.WARNING_MESSAGE);
        }
      }
    }
Exemplo n.º 20
0
 public void genSeed(ActionEvent e) {
   long seed = 0;
   boolean redo = false;
   do {
     redo = false;
     String seedString =
         JOptionPane.showInputDialog(
             this, "Enter a number:", Long.toString(rand.nextLong(), 36)
             // "Random Seed", JOptionPane.QUESTION_MESSAGE
             );
     if (seedString == null) return;
     try {
       seed = Long.parseLong(seedString, 36);
     } catch (NumberFormatException ex) {
       JOptionPane.showMessageDialog(this, "Use only letters and numbers, max 12 characters.");
       redo = true;
     }
   } while (redo);
   genSeed(seed);
 }
Exemplo n.º 21
0
 public void actionPerformed(ActionEvent e) {
   if (e.getSource() instanceof JMenuItem) {
     JMenuItem item = (JMenuItem) e.getSource();
     String name = item.getText();
     if (name.equals("New...")) {
       name = JOptionPane.showInputDialog(selectorPanel, "Enter a name for the new profile.");
     }
     if ((name == null) || name.trim().equals("")) return;
     Profile profile = new Profile(name);
     Component[] components = selectorPanel.getComponents();
     for (int i = 0; i < components.length; i++) {
       Component comp = components[i];
       if (comp instanceof CPCheckBox) {
         CPCheckBox scb = (CPCheckBox) comp;
         String id = scb.element.id;
         if (scb.isSelected()) profile.add(id);
       }
     }
     profiles.add(profile);
   }
 }
Exemplo n.º 22
0
  public boolean editLink(GLink link) {
    String pattern =
        (String)
            JOptionPane.showInputDialog(
                null,
                Localized.getString("faEditLinkMessage"),
                Localized.getString("faEditLinkTitle"),
                JOptionPane.QUESTION_MESSAGE,
                null,
                null,
                link.pattern);
    if (pattern != null) {
      removeLink(link);
      link.pattern = pattern;
      machine.addTransitionPattern(
          getState1(link).state.name, link.pattern, getState2(link).state.name);
      addElement(link);
    }

    return pattern != null;
  }
Exemplo n.º 23
0
 // If this is a new installation, ask the user for a
 // port for the server; otherwise, return the negative
 // of the configured port. If the user selects an illegal
 // port, return zero.
 private int getPort() {
   // Note: directory points to the parent of the CTP directory.
   File ctp = new File(directory, "CTP");
   if (suppressFirstPathElement) ctp = ctp.getParentFile();
   File config = new File(ctp, "config.xml");
   if (!config.exists()) {
     // No config file - must be a new installation.
     // Figure out whether this is Windows or something else.
     String os = System.getProperty("os.name").toLowerCase();
     int defPort = ((os.contains("windows") && !programName.equals("ISN")) ? 80 : 1080);
     int userPort = 0;
     while (userPort == 0) {
       String port =
           JOptionPane.showInputDialog(
               null,
               "This is a new "
                   + programName
                   + " installation.\n\n"
                   + "Select a port number for the web server.\n\n",
               Integer.toString(defPort));
       try {
         userPort = Integer.parseInt(port.trim());
       } catch (Exception ex) {
         userPort = -1;
       }
       if ((userPort < 80) || (userPort > 32767)) userPort = 0;
     }
     return userPort;
   } else {
     try {
       Document doc = getDocument(config);
       Element root = doc.getDocumentElement();
       Element server = getFirstNamedChild(root, "Server");
       String port = server.getAttribute("port");
       return -Integer.parseInt(port);
     } catch (Exception ex) {
     }
   }
   return 0;
 }
Exemplo n.º 24
0
    protected void openFromURL() {
      Object input =
          JOptionPane.showInputDialog(
              this.getApp(),
              "Enter a URL: ",
              "Open Shapes from URL",
              JOptionPane.QUESTION_MESSAGE,
              null,
              null,
              null);
      if (input == null) return;

      URL url = null;
      try {
        url = new URL(input.toString());
      } catch (IOException e) {
        e.printStackTrace();
      }

      if (url != null) {
        this.openFromPath(url.toExternalForm());
      }
    }
Exemplo n.º 25
0
 void insertMatchButton_actionPerformed(ActionEvent e) {
   String key = (String) matchComboBox.getSelectedItem();
   String format = (String) matchesKeys.get(key);
   if (key.equals(STRING_LITERAL)) {
     format =
         escapeReservedChars(
             (String)
                 JOptionPane.showInputDialog(
                     this,
                     "Enter the string you wish to match",
                     "String Literal Input",
                     JOptionPane.OK_CANCEL_OPTION));
     if (StringUtil.isNullString(format)) {
       return;
     }
   }
   if (selectedPane == 0) {
     insertText(format, PLAIN_ATTR, editorPane.getSelectionStart());
   } else {
     // add the combobox data value to the edit box
     int pos = formatTextArea.getCaretPosition();
     formatTextArea.insert(format, pos);
   }
 }
Exemplo n.º 26
0
  /** @param args the command line arguments */
  public static void main(String[] args) {

    readFile.randomList();
    // FOR TEST FILE
    // readFile.load();

    // User Input Options (Opening Menu)
    int select1;
    int select2;
    do {
      select1 =
          Integer.parseInt(
              JOptionPane.showInputDialog(
                  "Select An Option:" + "\n1. Uniprocessor\n2. Multiprocessor\n3. Exit"));

      switch (select1) {

          // Uniprocessor
        case 1:
          select2 =
              Integer.parseInt(
                  JOptionPane.showInputDialog(
                      "Select An Option:"
                          + "\n1. FCFS\n2. RR1\n3. RR10"
                          + "\n4. SPN\n5. Return to Menu"));
          switch (select2) {

              // FCFS
            case 1:
              System.out.println("FCFS (Uni)");
              System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
              readFile.setPCB();
              Queue<ProcessControlBlock> TimeQueue =
                  ProcessSchedules.firstcomefirstserve(readFile.theTable);
              String Name = "First Come First Serve";
              ExcelExport.exceltest(Name, TimeQueue);

              break;

              // RR1
            case 2:
              System.out.println("RR1 (Uni)");
              System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
              readFile.setPCB();
              Queue<ProcessControlBlock> TimeQueueRR1 = ProcessSchedules.rr1(readFile.theTable);
              String NameRR1 = "Round Robin (Q=1)";
              ExcelExport.exceltest(NameRR1, TimeQueueRR1);

              break;

              // RR10
            case 3:
              System.out.println("RR10 (Uni)");
              System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
              readFile.setPCB();
              Queue<ProcessControlBlock> TimeQueueRR10 = ProcessSchedules.rr10(readFile.theTable);
              String NameRR10 = "Round Robin (Q=10)";
              ExcelExport.exceltest(NameRR10, TimeQueueRR10);

              break;

              // SPN
            case 4:
              System.out.println("SPN (Uni)");
              System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
              readFile.setPCB();
              Queue<ProcessControlBlock> TimeQueueSPN =
                  ProcessSchedules.shortestnext(readFile.theTable);
              String NameSPN = "SPN";
              ExcelExport.exceltest(NameSPN, TimeQueueSPN);

              break;

              // Return to Menu
            case 5:
              break;
          }

          break;

          // Multiprocessor
        case 2:

          // read text file and create Process Objects containing attributes from file
          readFile.setPCB();

          // moves processes from process table into multiple queues
          MultiProcessor.movepintoqueue(readFile.theTable);

          break;

          // EXIT PROGRAM
        case 3:
          break;
      }
    } while (select1 <= 2); // Loops until user decides to exit program
  }
Exemplo n.º 27
0
 public void actionPerformed(ActionEvent aEvent) {
   try {
     if (aEvent.getActionCommand() == "Show Static Values") {
       // Show Static Values
       staticWindow.setVisible(true);
     } else if (aEvent.getActionCommand() == "Select Train") {
       // Select Train
       try {
         int intId = 1;
         String tempId =
             (String)
                 JOptionPane.showInputDialog(
                     null,
                     "",
                     "Train Model - Select Train",
                     JOptionPane.QUESTION_MESSAGE,
                     null,
                     idArray,
                     null);
         if (tempId != null) {
           int i;
           for (i = 0; i < trainList.size(); i++) {
             if (trainList.get(i).stringId.equals(tempId)) {
               break;
             }
           }
           setSelectedId(i + 1);
         }
       } catch (Exception e) {
         e.printStackTrace(System.err);
         JOptionPane.showMessageDialog(
             null, "Invalid input.", "Train Model - Warning", JOptionPane.WARNING_MESSAGE);
       }
     } else if ((aEvent.getActionCommand() == "Pause")
         || (aEvent.getActionCommand() == "Resume")) {
       // Pause / Resume
       setIsPaused(!isPaused);
     } else if (aEvent.getActionCommand() == "Set Manual Received Power") {
       // Set Manual Received Power
       try {
         String tempManRecPower =
             (String)
                 JOptionPane.showInputDialog(
                     null,
                     "Enter the received power (W) (number only):",
                     "Train Model - Set Received Power",
                     JOptionPane.QUESTION_MESSAGE);
         if (tempManRecPower != null) {
           trainList.get(selectedId - 1).manualPower = Double.parseDouble(tempManRecPower);
           jlManRecPower.setText("" + trainList.get(selectedId - 1).manualPower);
         }
       } catch (Exception e) {
         e.printStackTrace(System.err);
         JOptionPane.showMessageDialog(
             null,
             "Invalid received power value entered.",
             "Train Model - Warning",
             JOptionPane.WARNING_MESSAGE);
       }
     } else if (aEvent.getActionCommand() == "Toggle Manual Received Power") {
       // Toggle Manual Received Power
       trainList.get(selectedId - 1).issetManualPower =
           !trainList.get(selectedId - 1).issetManualPower;
       jlToggleManRecPower.setText("" + trainList.get(selectedId - 1).issetManualPower);
     } else if (aEvent.getActionCommand() == "Set Manual Desired Speed Limit") {
       // Set Manual Desired Speed Limit
       try {
         String tempManDesSpdLmt =
             (String)
                 JOptionPane.showInputDialog(
                     null,
                     "Enter the desired speed limit (m/s) (number only):",
                     "Train Model - Set Desired Speed Limit",
                     JOptionPane.QUESTION_MESSAGE);
         if (tempManDesSpdLmt != null) {
           trainList.get(selectedId - 1).manualSpeedLimit = Double.parseDouble(tempManDesSpdLmt);
           jlManDesSpdLmt.setText("" + trainList.get(selectedId - 1).manualSpeedLimit);
         }
       } catch (Exception e) {
         e.printStackTrace(System.err);
         JOptionPane.showMessageDialog(
             null,
             "Invalid desired speed limit entered.",
             "Train Model - Warning",
             JOptionPane.WARNING_MESSAGE);
       }
     } else if (aEvent.getActionCommand() == "Toggle Manual Desired Speed Limit") {
       // Toggle Manual Desired Speed Limit
       trainList.get(selectedId - 1).issetManualSpeedLimit =
           !trainList.get(selectedId - 1).issetManualSpeedLimit;
       jlToggleManDesSpdLmt.setText("" + trainList.get(selectedId - 1).issetManualSpeedLimit);
     } else if (aEvent.getActionCommand() == "Toggle Signal Pickup Failure") {
       // Toggle Signal Pickup Failure
       trainList.get(selectedId - 1).issetSignalPickupFailure =
           !trainList.get(selectedId - 1).issetSignalPickupFailure;
       jlToggleSignalPickupFailure.setText(
           "" + trainList.get(selectedId - 1).issetSignalPickupFailure);
       jlPosition.setText(
           ""
               + ((trainList.get(selectedId - 1).issetSignalPickupFailure)
                   ? "???????"
                   : ("[ "
                       + trainList.get(selectedId - 1).positionBlock.id
                       + " , "
                       + trainList.get(selectedId - 1).positionMeters
                       + " ]")));
     } else if (aEvent.getActionCommand() == "Toggle Engine Failure") {
       // Toggle Engine Failure
       trainList.get(selectedId - 1).issetEngineFailure =
           !trainList.get(selectedId - 1).issetEngineFailure;
       jlToggleEngineFailure.setText("" + trainList.get(selectedId - 1).issetEngineFailure);
     } else if (aEvent.getActionCommand() == "Toggle Brake Failure") {
       // Toggle Brake Failure
       trainList.get(selectedId - 1).issetBrakeFailure =
           !trainList.get(selectedId - 1).issetBrakeFailure;
       jlToggleBrakeFailure.setText("" + trainList.get(selectedId - 1).issetBrakeFailure);
     } else if (aEvent.getActionCommand() == "Toggle Service Brake") {
       // Toggle Service Brake
       trainList.get(selectedId - 1).issetServiceBrake =
           !trainList.get(selectedId - 1).issetServiceBrake;
       jlToggleServiceBrake.setText("" + trainList.get(selectedId - 1).issetServiceBrake);
     } else if (aEvent.getActionCommand() == "Toggle Emergency Brake") {
       // Toggle Emergency Brake
       trainList.get(selectedId - 1).issetEmerBrake =
           !trainList.get(selectedId - 1).issetEmerBrake;
       jlToggleEmergencyBrake.setText("" + trainList.get(selectedId - 1).issetEmerBrake);
     } else if (aEvent.getActionCommand() == "Set Manual Lights Status") {
       // Set Manual Lights Status
       try {
         String[] optionsManLights = new String[2];
         optionsManLights[0] = "On";
         optionsManLights[1] = "Off";
         String tempManLights =
             (String)
                 JOptionPane.showInputDialog(
                     null,
                     "",
                     "Train Model - Set Lights Status",
                     JOptionPane.QUESTION_MESSAGE,
                     null,
                     optionsManLights,
                     null);
         if (tempManLights != null) {
           trainList.get(selectedId - 1).issetLightsOnManual =
               tempManLights.equals(optionsManLights[0]);
           jlManLights.setText(
               "" + ((trainList.get(selectedId - 1).issetLightsOnManual) ? "On" : "Off"));
         }
       } catch (Exception e) {
         e.printStackTrace(System.err);
         JOptionPane.showMessageDialog(
             null, "Invalid input.", "Train Model - Warning", JOptionPane.WARNING_MESSAGE);
       }
     } else if (aEvent.getActionCommand() == "Toggle Manual Lights Status") {
       // Toggle Manual Lights Status
       trainList.get(selectedId - 1).issetLightsOnUseManual =
           !trainList.get(selectedId - 1).issetLightsOnUseManual;
       jlToggleManLights.setText("" + trainList.get(selectedId - 1).issetLightsOnUseManual);
     } else if (aEvent.getActionCommand() == "Set Manual Doors Status") {
       // Set Manual Doors Status
       try {
         String[] optionsManDoors = new String[2];
         optionsManDoors[0] = "Open";
         optionsManDoors[1] = "Closed";
         String tempManDoors =
             (String)
                 JOptionPane.showInputDialog(
                     null,
                     "",
                     "Train Model - Set Doors Status",
                     JOptionPane.QUESTION_MESSAGE,
                     null,
                     optionsManDoors,
                     null);
         if (tempManDoors != null) {
           trainList.get(selectedId - 1).issetDoorsOpenManual =
               tempManDoors.equals(optionsManDoors[0]);
           jlManDoors.setText(
               "" + ((trainList.get(selectedId - 1).issetDoorsOpenManual) ? "Open" : "Closed"));
         }
       } catch (Exception e) {
         e.printStackTrace(System.err);
         JOptionPane.showMessageDialog(
             null, "Invalid input.", "Train Model - Warning", JOptionPane.WARNING_MESSAGE);
       }
     } else if (aEvent.getActionCommand() == "Toggle Manual Doors Status") {
       // Toggle Manual Doors Status
       trainList.get(selectedId - 1).issetDoorsOpenUseManual =
           !trainList.get(selectedId - 1).issetDoorsOpenUseManual;
       jlToggleManDoors.setText("" + trainList.get(selectedId - 1).issetDoorsOpenUseManual);
     } else if (aEvent.getActionCommand() == "Set Manual Target Temp.") {
       // Set Manual Target Temp.
       try {
         String tempManTarTemperature =
             (String)
                 JOptionPane.showInputDialog(
                     null,
                     "Enter the target temperature (degrees F) (number only):",
                     "Train Model - Set Target Temperature",
                     JOptionPane.QUESTION_MESSAGE);
         if (tempManTarTemperature != null) {
           trainList.get(selectedId - 1).targetTemperatureManual =
               Double.parseDouble(tempManTarTemperature);
           jlManTarTemperature.setText(
               "" + trainList.get(selectedId - 1).targetTemperatureManual);
         }
       } catch (Exception e) {
         e.printStackTrace(System.err);
         JOptionPane.showMessageDialog(
             null,
             "Invalid target temperature entered.",
             "Train Model - Warning",
             JOptionPane.WARNING_MESSAGE);
       }
     } else if (aEvent.getActionCommand() == "Toggle Manual Target Temp.") {
       // Toggle Manual Target Temp.
       trainList.get(selectedId - 1).issetTargetTemperatureManual =
           !trainList.get(selectedId - 1).issetTargetTemperatureManual;
       jlToggleManTarTemperature.setText(
           "" + trainList.get(selectedId - 1).issetTargetTemperatureManual);
     } else {
       JOptionPane.showMessageDialog(
           null, "Invalid action event.", "Error", JOptionPane.ERROR_MESSAGE);
     }
   } catch (Exception e) {
     e.printStackTrace(System.err);
     JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
   }
 }
Exemplo n.º 28
0
  /**
   * Réagit au clique de la souris sur un bouton
   *
   * @param e L'ActionEvent généré
   */
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() instanceof JButton) {
      JButton b = (JButton) e.getSource();
      if (b.getName() == "statTab") { // Si on clique sur l'onglet statistiques
        cartes.show(panneau, "statistiques");
      } else if (b.getName() == "payTab") { // Si on clique sur l'onglet de paiement
        cartes.show(panneau, "paiement");
      } else if (b.getName() == "loginButton") { // Si on clique sur le bonton de login
        char[] input = passTextField.getPassword();
        String pass = new String("root"); // Le mot de passe
        if (pass.equals(new String(input))) {
          cartes.show(panneau, "paiement");
          loginLabel.setText("");
        } else loginLabel.setText("Mot de passe incorrect");

        Arrays.fill(input, '0');
        passTextField.selectAll();
      } else if (b.getName() == "annuler") { // Si clique sur annuler
        // On réserte la sélection et on déselectionne les tables
        ControleurTables.deleteSelection();
        this.tableCounter = 0;
        this.payTextField.setText("");
        this.valider.setEnabled(false);
        this.valider.setBackground(Color.GRAY);
      } else if (b.getName() == "valider") { // Si on clique sur valider

        // On récupère la date
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, (int) this.difTemps);
        // On récupère le mode de paiement sélectionné
        String type = new String("carte bleue");
        if (especes.isSelected()) {
          type = "especes";
        } else if (cheque.isSelected()) {
          type = "cheque";
        }
        try { // On verifie que le prix rentré est correct
          // On met tout dans le meme try pour annuler l'insertion de la commande dans la bdd en cas
          // d'erreur
          float prix = Float.parseFloat(payTextField.getText());
          ModelePaiement mP = new ModelePaiement();
          mP.insert(cal, prix, type);
          // On recupère la selection
          ArrayList<Table> tab = ControleurTables.getSelection();
          // On met toutes les tables à laver
          for (int i = 0; i < tab.size(); i++) {
            tab.get(i).setStatut(Table.ALAVER);
            tab.get(i).setNom(null);
          }
          // On déselectionne les tables
          ControleurTables.deleteSelection();
          this.tableCounter = 0;
          this.payTextField.setText("");
          this.valider.setEnabled(false);
          this.valider.setBackground(Color.GRAY);
          // On insère le paiement dans la bdd
          modeleTable.updateTables(this.tables);
        } catch (NumberFormatException nfe) {
          JOptionPane.showMessageDialog(
              null, "Veuillez entrez un rpix valide.", "Erreur prix", JOptionPane.ERROR_MESSAGE);
        }
      } else if (b.getName() == "trier") { // Si on appuie sur trier
        float ca = -1;
        ModelePaiement mP = new ModelePaiement();
        if (service.isSelected()) { // Si on selection le chiffre d'affaire par service
          ca =
              mP.getCAService(
                  (String)
                      serviceComboBox
                          .getSelectedItem()); // On sélectonne le chiffre d'affaire en focntion du
                                               // service

        } else if (date.isSelected()) { // Si on selection le chiffre d'affaire par date
          try { // On verifie que la date est bien valide
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            cal.setTime(sdf.parse(dateTextField.getText()));
            ca = mP.getCADate(cal); // On va chercher le chiffre d'affaire en fonction de la date
          } catch (Exception npe) {
            JOptionPane.showMessageDialog(
                null,
                "Veuillez entrez une date de la forme 03/06/2012.",
                "Erreur date",
                JOptionPane.ERROR_MESSAGE);
          }
        }

        if (ca > -1) { // Si on a récupérer un chiffre d'affaire
          chiffreAffaire.setText("Chiffre d'affaire : " + Float.toString(ca));
        }
      } else if (b.getName() == "option") { // Si on clique sur option
        String strDate =
            JOptionPane.showInputDialog(null, "Réglage de temps (ex: 03/06/1996 15:06) ", null);

        try {
          Calendar cal = Calendar.getInstance();
          Calendar now = Calendar.getInstance();

          SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
          cal.setTime(sdf.parse(strDate));
          difTemps =
              (int)
                  ((cal.getTimeInMillis() - now.getTimeInMillis())
                      / 1000); // Transformation en secondes
          if ((cal.getTimeInMillis() - now.getTimeInMillis()) % 1000 > 0) {
            difTemps++;
          }
        } catch (Exception exep) {
          JOptionPane.showMessageDialog(
              null,
              "Vous devez entrer une date valide (ex: 03/06/1996 15:06).",
              "Date invalide",
              JOptionPane.ERROR_MESSAGE);
        }
      }
    }
  }
Exemplo n.º 29
0
  // manejo de eventos de turno y los mapas
  public void actionPerformed(ActionEvent e) {
    if (estad == e.getSource()) {
      efectos.reproducirEfectoSonido("Klick");
      // IUpanel02.mainAE();   -----------------------------------------------
      /// setVisible(false);
    }
    if (registrar == e.getSource()) {
      efectos.reproducirEfectoSonido("Klick");
      OpcionesPerfiles.perfiles.mainAE();
      setVisible(false);
    }
    if (facil == e.getSource()) {
      efectos.reproducirEfectoSonido("Klick");
      String nomb = "";
      PerfilesBD coleccion = new PerfilesBD();
      int numPer = 0;
      numPer = coleccion.numeroDePerfiles();
      Perfil perfilesMostrar[] = null;

      if (numPer == 0) {
        perfilesMostrar = new Perfil[4];

        for (int idx = 0; idx < 4; idx++) {
          perfilesMostrar[idx] =
              new Perfil("Asesinator" + (idx + 1), "predt" + (idx + 1) + ".jpg", "123" + idx);
          coleccion.agregarPerfil(perfilesMostrar[idx]);
        }
      }

      try {
        do {
          nomb =
              JOptionPane.showInputDialog(null, "Ingrese Nombre de Jugador Humano", "Asesinator1");

        } while (nomb.length() == 0);

        if (nomb.equals("Asesinator1")
            || nomb.equals("Asesinator2")
            || nomb.equals("Asesinator3")
            || nomb.equals("Asesinator4")) {
          MenuCrearJuego.menu.mainAE(1, nomb, "PC");
          setVisible(false);
          return;
        }

        JLabel jPassword = new JLabel("porfavor ingrese la contraseña ");
        JTextField password = new JPasswordField();
        Object[] ob = {jPassword, password};

        int result =
            JOptionPane.showConfirmDialog(null, ob, "Contraseña", JOptionPane.OK_CANCEL_OPTION);

        String contraseNa = "";
        if (result == JOptionPane.OK_OPTION) {
          contraseNa = password.getText();
        }
        if (result == JOptionPane.CANCEL_OPTION) {
          return;
        }

        if (coleccion.estaRegistrado(contraseNa)) {
          MenuCrearJuego.menu.mainAE(1, nomb, "PC");
          setVisible(false);
        } else {
          JOptionPane.showMessageDialog(
              this,
              "No esta Registrado, usted debe registrarse previamente!",
              "ERROR",
              JOptionPane.ERROR_MESSAGE);
        }
      } catch (Exception exp) {
      }
      return;
    }
    if (dific == e.getSource()) {
      efectos.reproducirEfectoSonido("Klick");
      String nomb = "";
      PerfilesBD coleccion = new PerfilesBD();
      int numPer = 0;
      numPer = coleccion.numeroDePerfiles();
      Perfil perfilesMostrar[] = null;

      if (numPer == 0) {
        perfilesMostrar = new Perfil[4];

        for (int idx = 0; idx < 4; idx++) {
          perfilesMostrar[idx] =
              new Perfil("Asesinator" + (idx + 1), "predt" + (idx + 1) + ".jpg", "123" + idx);
          coleccion.agregarPerfil(perfilesMostrar[idx]);
        }
      }

      try {
        do {
          nomb =
              JOptionPane.showInputDialog(null, "Ingrese Nombre de Jugador Humano", "Asesinator1");

        } while (nomb.length() == 0);

        if (nomb.equals("Asesinator1")
            || nomb.equals("Asesinator2")
            || nomb.equals("Asesinator3")
            || nomb.equals("Asesinator4")) {
          MenuCrearJuego.menu.mainAE(2, nomb, "PC");
          setVisible(false);
          return;
        }

        JLabel jPassword = new JLabel("porfavor ingrese la contraseña ");
        JTextField password = new JPasswordField();
        Object[] ob = {jPassword, password};

        int result =
            JOptionPane.showConfirmDialog(null, ob, "Contraseña", JOptionPane.OK_CANCEL_OPTION);

        String contraseNa = "";
        if (result == JOptionPane.OK_OPTION) {
          contraseNa = password.getText();
        }
        if (result == JOptionPane.CANCEL_OPTION) {
          return;
        }

        if (coleccion.estaRegistrado(contraseNa)) {
          MenuCrearJuego.menu.mainAE(2, nomb, "PC");
          setVisible(false);
        } else {
          JOptionPane.showMessageDialog(
              this,
              "No esta Registrado, usted debe registrarse previamente!",
              "ERROR",
              JOptionPane.ERROR_MESSAGE);
        }
      } catch (Exception exp) {
      }
      return;
    }

    if (red == e.getSource()) {
      efectos.reproducirEfectoSonido("Klick");
      String nomb = "";
      PerfilesBD coleccion = new PerfilesBD();
      final PerfilesBD perfilesDB = coleccion;
      int numPer = 0;
      numPer = coleccion.numeroDePerfiles();
      Perfil perfilesMostrar[] = null;

      if (numPer == 0) {
        perfilesMostrar = new Perfil[4];

        for (int idx = 0; idx < 4; idx++) {
          perfilesMostrar[idx] =
              new Perfil("Asesinator" + (idx + 1), "predt" + (idx + 1) + ".jpg", "123" + idx);
          coleccion.agregarPerfil(perfilesMostrar[idx]);
        }
      }

      try {
        do {
          nomb =
              JOptionPane.showInputDialog(null, "Ingrese Nombre de Jugador Humano", "Asesinator1");

        } while (nomb.length() == 0);
        final String nomb2 = nomb;
        Perfil perfil = null;
        if (nomb.equals("Asesinator1")
            || nomb.equals("Asesinator2")
            || nomb.equals("Asesinator3")
            || nomb.equals("Asesinator4")) {
          if (nomb.equals("Asesinator1")) {
            if (coleccion.estaConectado("1230")) {
              JOptionPane.showMessageDialog(
                  this, "El perfil ya se encuentra en uso!", "ERROR", JOptionPane.ERROR_MESSAGE);
              return;
            }
          }
          if (nomb.equals("Asesinator2")) {
            if (coleccion.estaConectado("1231")) {
              JOptionPane.showMessageDialog(
                  this, "El perfil ya se encuentra en uso!", "ERROR", JOptionPane.ERROR_MESSAGE);
              return;
            }
          }
          if (nomb.equals("Asesinator3")) {
            if (coleccion.estaConectado("1232")) {
              JOptionPane.showMessageDialog(
                  this, "El perfil ya se encuentra en uso!", "ERROR", JOptionPane.ERROR_MESSAGE);
              return;
            }
          }
          if (nomb.equals("Asesinator4")) {
            if (coleccion.estaConectado("1233")) {
              JOptionPane.showMessageDialog(
                  this, "El perfil ya se encuentra en uso!", "ERROR", JOptionPane.ERROR_MESSAGE);
              return;
            }
          }

          if (nomb.equals("Asesinator1")) {
            coleccion.agregarConectado("1230");
          }
          if (nomb.equals("Asesinator2")) {
            coleccion.agregarConectado("1231");
          }
          if (nomb.equals("Asesinator3")) {
            coleccion.agregarConectado("1232");
          }
          if (nomb.equals("Asesinator4")) {
            coleccion.agregarConectado("1233");
          }

          if (!coleccion.estaMontadoServidor()) {

            int numJugadores = 2;
            boolean siga = false;
            do {
              try {
                numJugadores =
                    Integer.parseInt(
                        JOptionPane.showInputDialog(
                            this,
                            "señor jugador, por ser el primero en elegir juego en red,\n"
                                + " ha sido elegido como administrador de la partida,\n"
                                + " `por favor ingrese el numero de jugadores [2,50]"));
              } catch (Exception exp) {
                continue;
              }
              if ((numJugadores >= 2) && (numJugadores < 50)) {
                siga = true;
              }

            } while (!siga);

            cliente.enviarAdmi(numJugadores);
            coleccion.conectar_desconectarServidor(true, ipServer);
            JOptionPane.showMessageDialog(
                this,
                "se modifica el numero de jugadores de la clase Administrador : " + numJugadores);
          }
          MenuCrearJuego.menu.mainAE(1, nomb, "Red");
          MenuCrearJuego.menu.setCliente(cliente);
          setVisible(false);

          return;
        }

        JLabel jPassword = new JLabel("porfavor ingrese la contraseña ");
        JTextField password = new JPasswordField();
        Object[] ob = {jPassword, password};

        int result =
            JOptionPane.showConfirmDialog(null, ob, "Contraseña", JOptionPane.OK_CANCEL_OPTION);

        String contraseNa = "";
        if (result == JOptionPane.OK_OPTION) {
          contraseNa = password.getText();
        }
        if (result == JOptionPane.CANCEL_OPTION) {
          return;
        }

        if (coleccion.estaRegistrado(contraseNa)) {
          if (coleccion.estaConectado(contraseNa)) {
            JOptionPane.showMessageDialog(
                this, "El perfil ya se encuentra en uso!", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
          }

          coleccion.agregarConectado(contraseNa);

          if (!coleccion.estaMontadoServidor()) {

            int numJugadores = 2;
            boolean siga = false;
            do {
              try {
                numJugadores =
                    Integer.parseInt(
                        JOptionPane.showInputDialog(
                            this,
                            "señor jugador, por ser el primero en elegir juego en red,\n"
                                + " ha sido elegido como administrador de la partida,\n"
                                + " `por favor ingrese el numero de jugadores [2,50]"));
              } catch (Exception exp) {
                JOptionPane.showMessageDialog(
                    this, "Error de datos ", "Error", JOptionPane.ERROR_MESSAGE);
                continue;
              }
              if ((numJugadores >= 2) && (numJugadores < 50)) {
                siga = true;
              } else
                JOptionPane.showMessageDialog(
                    this, "Error de datos ", "Error", JOptionPane.ERROR_MESSAGE);

            } while (!siga);
            cliente.enviarAdmi(numJugadores);
            coleccion.conectar_desconectarServidor(true, ipServer);
          }
          MenuCrearJuego.menu.mainAE(1, nomb, "Red");
          MenuCrearJuego.menu.setCliente(cliente);
          setVisible(false);
        } else {
          JOptionPane.showMessageDialog(
              this,
              "No esta Registrado, usted debe registrarse previamente!",
              "ERROR",
              JOptionPane.ERROR_MESSAGE);
        }
      } catch (Exception exp) {
      }
      return;
    }

    if (salir == e.getSource()) {
      efectos.reproducirEfectoSonido("Klick");
      PerfilesBD coleccion = new PerfilesBD();
      // pregunta si de verdad se desea salir del juego
      int n =
          JOptionPane.showConfirmDialog(
              null,
              "Seguro que deseas SALIR?",
              "END GAME",
              JOptionPane.YES_NO_OPTION,
              JOptionPane.QUESTION_MESSAGE);

      if (n == JOptionPane.YES_OPTION) {
        System.exit(12);
      }
    }
  }
Exemplo n.º 30
0
  public Ssys3() {
    store = new Storage();
    tableSorter = new TableRowSorter<Storage>(store);
    jobs = new LinkedList<String>();

    makeGUI();
    frm.setSize(800, 600);
    frm.addWindowListener(
        new WindowListener() {
          public void windowActivated(WindowEvent evt) {}

          public void windowClosed(WindowEvent evt) {
            try {
              System.out.println("joining EDT's");
              for (EDT edt : encryptDecryptThreads) {
                edt.weakStop();
                try {
                  edt.join();
                  System.out.println("  - joined");
                } catch (InterruptedException e) {
                  System.out.println("  - Not joined");
                }
              }
              System.out.println("saving storage");
              store.saveAll(tempLoc);
            } catch (IOException e) {
              e.printStackTrace();
              System.err.println(
                  "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\nFailed to save properly\n\n!!!!!!!!!!!!!!!!!!!!!!!!!");
              System.exit(1);
            }
            clean();
            System.exit(0);
          }

          public void windowClosing(WindowEvent evt) {
            windowClosed(evt);
          }

          public void windowDeactivated(WindowEvent evt) {}

          public void windowDeiconified(WindowEvent evt) {}

          public void windowIconified(WindowEvent evt) {}

          public void windowOpened(WindowEvent evt) {}
        });
    ImageIcon ico = new ImageIcon(ICON_NAME);
    frm.setIconImage(ico.getImage());
    frm.setLocationRelativeTo(null);
    frm.setVisible(true);

    // load config
    storeLocs = new ArrayList<File>();
    String ossl = "openssl";
    int numThreadTemp = 2;
    boolean priorityDecryptTemp = true;
    boolean allowExportTemp = false;
    boolean checkImportTemp = true;
    try {
      Scanner sca = new Scanner(CONF_FILE);
      while (sca.hasNextLine()) {
        String ln = sca.nextLine();
        if (ln.startsWith(CONF_SSL)) {
          ossl = ln.substring(CONF_SSL.length());
        } else if (ln.startsWith(CONF_THREAD)) {
          try {
            numThreadTemp = Integer.parseInt(ln.substring(CONF_THREAD.length()));
          } catch (Exception exc) {
            // do Nothing
          }
        } else if (ln.equals(CONF_STORE)) {
          while (sca.hasNextLine()) storeLocs.add(new File(sca.nextLine()));
        } else if (ln.startsWith(CONF_PRIORITY)) {
          try {
            priorityDecryptTemp = Boolean.parseBoolean(ln.substring(CONF_PRIORITY.length()));
          } catch (Exception exc) {
            // do Nothing
          }
        } else if (ln.startsWith(CONF_EXPORT)) {
          try {
            allowExportTemp = Boolean.parseBoolean(ln.substring(CONF_EXPORT.length()));
          } catch (Exception exc) {
            // do Nothing
          }
        } else if (ln.startsWith(CONF_CONFIRM)) {
          try {
            checkImportTemp = Boolean.parseBoolean(ln.substring(CONF_CONFIRM.length()));
          } catch (Exception exc) {
            // do Nothing
          }
        }
      }
      sca.close();
    } catch (IOException e) {

    }
    String osslWorks = OpenSSLCommander.test(ossl);
    while (osslWorks == null) {
      ossl =
          JOptionPane.showInputDialog(
              frm,
              "Please input the command used to run open ssl\n  We will run \"<command> version\" to confirm\n  Previous command: "
                  + ossl,
              "Find open ssl",
              JOptionPane.OK_CANCEL_OPTION);
      if (ossl == null) {
        System.err.println("Refused to provide openssl executable location");
        System.exit(1);
      }
      osslWorks = OpenSSLCommander.test(ossl);
      if (osslWorks == null)
        JOptionPane.showMessageDialog(
            frm, "Command " + ossl + " unsuccessful", "Unsuccessful", JOptionPane.ERROR_MESSAGE);
    }
    if (storeLocs.size() < 1)
      JOptionPane.showMessageDialog(
          frm,
          "Please select an initial sotrage location\nIf one already exists, or there are more than one, please select it");
    while (storeLocs.size() < 1) {
      JFileChooser jfc = new JFileChooser();
      jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
      if (jfc.showOpenDialog(frm) != JFileChooser.APPROVE_OPTION) {
        System.err.println("Refused to provide an initial store folder");
        System.exit(1);
      }
      File sel = jfc.getSelectedFile();
      if (sel.isDirectory()) storeLocs.add(sel);
    }
    numThreads = numThreadTemp;
    priorityExport = priorityDecryptTemp;
    allowExport = allowExportTemp;
    checkImports = checkImportTemp;

    try {
      PrintWriter pw = new PrintWriter(CONF_FILE);
      pw.println(CONF_SSL + ossl);
      pw.println(CONF_THREAD + numThreads);
      pw.println(CONF_PRIORITY + priorityExport);
      pw.println(CONF_EXPORT + allowExport);
      pw.println(CONF_CONFIRM + checkImports);
      pw.println(CONF_STORE);
      for (File fi : storeLocs) {
        pw.println(fi.getAbsolutePath());
      }
      pw.close();
    } catch (IOException e) {
      System.err.println("Failed to save config");
    }

    File chk = null;
    for (File fi : storeLocs) {
      File lib = new File(fi, LIBRARY_NAME);
      if (lib.exists()) {
        chk = lib;
        // break;
      }
    }

    char[] pass = null;
    if (chk == null) {
      JOptionPane.showMessageDialog(
          frm,
          "First time run\n  Create your password",
          "Create Password",
          JOptionPane.INFORMATION_MESSAGE);
      char[] p1 = askPassword();
      char[] p2 = askPassword();
      boolean same = p1.length == p2.length;
      for (int i = 0; i < Math.min(p1.length, p2.length); i++) {
        if (p1[i] != p2[i]) same = false;
      }
      if (same) {
        JOptionPane.showMessageDialog(
            frm, "Password created", "Create Password", JOptionPane.INFORMATION_MESSAGE);
        pass = p1;
      } else {
        JOptionPane.showMessageDialog(
            frm, "Passwords dont match", "Create Password", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
      }
    } else {
      pass = askPassword();
    }
    sec = OpenSSLCommander.getCommander(chk, pass, ossl);
    if (sec == null) {
      System.err.println("Wrong Password");
      System.exit(1);
    }
    store.useSecurity(sec);
    store.useStorage(storeLocs);

    tempLoc = new File("temp");
    if (!tempLoc.exists()) tempLoc.mkdirs();
    // load stores
    try {
      store.loadAll(tempLoc);
      store.fireTableDataChanged();
    } catch (IOException e) {
      System.err.println("Storage loading failure");
      System.exit(1);
    }

    needsSave = false;
    encryptDecryptThreads = new EDT[numThreads];
    for (int i = 0; i < encryptDecryptThreads.length; i++) {
      encryptDecryptThreads[i] = new EDT(i);
      encryptDecryptThreads[i].start();
    }

    updateStatus();
    txaSearch.grabFocus();
  }