public static void estimateKeyDerivationTime() {
   // This is run in the background after startup. If we haven't recorded it before, do a key
   // derivation to see
   // how long it takes. This helps us produce better progress feedback, as on Windows we don't
   // currently have a
   // native Scrypt impl and the Java version is ~3 times slower, plus it depends a lot on CPU
   // speed.
   checkGuiThread();
   estimatedKeyDerivationTime = Main.instance.prefs.getExpectedKeyDerivationTime();
   if (estimatedKeyDerivationTime == null) {
     new Thread(
             () -> {
               log.info("Doing background test key derivation");
               KeyCrypterScrypt scrypt = new KeyCrypterScrypt(SCRYPT_PARAMETERS);
               long start = System.currentTimeMillis();
               scrypt.deriveKey("test password");
               long msec = System.currentTimeMillis() - start;
               log.info("Background test key derivation took {}msec", msec);
               Platform.runLater(
                   () -> {
                     estimatedKeyDerivationTime = Duration.ofMillis(msec);
                     Main.instance.prefs.setExpectedKeyDerivationTime(estimatedKeyDerivationTime);
                   });
             })
         .start();
   }
 }
Exemplo n.º 2
0
  public void exit() {
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Quit?");
    alert.setHeaderText("You've selected to quit this program.");
    alert.setContentText("Are you sure you want to quit?");

    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() == ButtonType.OK) System.exit(0);
  }
 @Override
 void submitItem(Property item) {
   if (!App.employee.hasPermission(Permission.CLIENT_SETTINGS)) {
     App.notify.showAndWait(Permission.CLIENT_SETTINGS);
   } else {
     App.confirm.showAndWait(
         "Are you sure you want to make these changes?",
         () -> {
           App.properties.add(item.getKey(), item.getValue());
           App.properties.save(new File(System.getProperty("user.dir") + "/app.properties"));
         });
   }
 }
Exemplo n.º 4
0
Arquivo: Main.java Projeto: 8CAKE/ALE
  public void systemClose() {

    if (client.isConnected == true) {
      client.disconnect(messageArea, messageInputArea, superUser);
    }

    try {
      if (dbCon != null) {
        dbCon.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.exit(0);
  }
Exemplo n.º 5
0
 protected void changeLanguage(String language, String country) throws IOException {
   File f = new File("./");
   File[] matchingFiles =
       f.listFiles(
           new FilenameFilter() {
             public boolean accept(File dir, String name) {
               return name.startsWith("epicworship") && name.endsWith("jar");
             }
           });
   Runtime.getRuntime()
       .exec(
           "java -Duser.language="
               + language
               + " -Djavafx.autoproxy.disable=true -Duser.country="
               + country
               + " -jar "
               + matchingFiles[0].getName());
   System.exit(0);
 }
Exemplo n.º 6
0
public class Controller implements Initializable {
  private static final String newLine = System.getProperty("line.separator");
  private int itemCount = 1;
  private int totalItems = 0;
  private int totalQuantity = 0;
  private double subtotal = 0.0;
  private double grandTotal = 0.0;
  private boolean totalItemsLocked = false;
  private Order order = new Order();
  private Writer writer = null;
  private Item item = null;
  private Date transDate = null;
  private java.util.List<Book> inventory = new ArrayList<>();
  private File output = new File("transactions.txt");
  private NumberFormat formatter = NumberFormat.getCurrencyInstance();

  @FXML private Button btn_process;
  @FXML private Button btn_confirm;
  @FXML private Button btn_view;
  @FXML private Button btn_finish;
  @FXML private Button btn_new;
  @FXML private Button btn_exit;
  @FXML private TextField text_totalItems;
  @FXML private TextField text_bookID;
  @FXML private TextField text_quantity;
  @FXML private TextField text_info;
  @FXML private TextField text_subtotal;
  @FXML private Label label_totalItems;
  @FXML private Label label_bookID;
  @FXML private Label label_quantity;
  @FXML private Label label_info;
  @FXML private Label label_subtotal;

  @Override
  public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
    readInventoryFromFile();

    assert btn_process != null
        : "fx:id=\"btn_process\" was not injected: check your FXML file 'checkout.fxml'.";
    assert btn_confirm != null
        : "fx:id=\"btn_confirm\" was not injected: check your FXML file 'checkout.fxml'.";
    btn_confirm.setDisable(true);
    assert btn_view != null
        : "fx:id=\"btn_view\" was not injected: check your FXML file 'checkout.fxml'.";
    btn_view.setDisable(true);
    assert btn_finish != null
        : "fx:id=\"btn_finish\" was not injected: check your FXML file 'checkout.fxml'.";
    btn_finish.setDisable(true);
    assert btn_new != null
        : "fx:id=\"btn_new\" was not injected: check your FXML file 'checkout.fxml'.";
    assert btn_exit != null
        : "fx:id=\"btn_exit\" was not injected: check your FXML file 'checkout.fxml'.";

    assert text_totalItems != null
        : "fx:id=\"text_totalItems\" was not injected: check your FXML file 'checkout.fxml'.";
    assert text_bookID != null
        : "fx:id=\"text_bookID\" was not injected: check your FXML file 'checkout.fxml'.";
    assert text_quantity != null
        : "fx:id=\"text_quantity\" was not injected: check your FXML file 'checkout.fxml'.";
    assert text_info != null
        : "fx:id=\"text_info\" was not injected: check your FXML file 'checkout.fxml'.";
    text_info.setDisable(true);
    assert text_subtotal != null
        : "fx:id=\"text_subtotal\" was not injected: check your FXML file 'checkout.fxml'.";
    text_subtotal.setDisable(true);

    assert label_totalItems != null
        : "fx:id=\"label_totalItems\" was not injected: check your FXML file 'checkout.fxml'.";
    assert label_bookID != null
        : "fx:id=\"label_bookID\" was not injected: check your FXML file 'checkout.fxml'.";
    assert label_quantity != null
        : "fx:id=\"label_quantity\" was not injected: check your FXML file 'checkout.fxml'.";
    assert label_info != null
        : "fx:id=\"label_info\" was not injected: check your FXML file 'checkout.fxml'.";
    assert label_subtotal != null
        : "fx:id=\"label_subtotal\" was not injected: check your FXML file 'checkout.fxml'.";
  }

  public void processItem() {
    createItem();
    if (item != null) {
      text_info.setText(item.toString());
      btn_confirm.setDisable(false);
    }
  }

  public void confirmItem() {
    this.subtotal += item.getTotal();
    String subtotalStr = formatter.format(this.subtotal);
    text_bookID.setText("");
    text_quantity.setText("");
    text_subtotal.setText(subtotalStr);

    confirmAlert();

    order.addItem(item);
    this.totalQuantity += item.getQuantity();
    changeItemNumber();
    btn_confirm.setDisable(true);
    btn_view.setDisable(false);
    text_totalItems.setDisable(true);
    item = null;
  }

  public void viewOrder() {
    String currentOrder = "";
    int counter = 0;
    for (Item i : order.getOrder()) {
      counter++;
      currentOrder += counter + ". " + i.toString() + "\n";
    }
    Alert alert = new Alert(Alert.AlertType.INFORMATION);
    alert.setTitle("Current Order");
    alert.setHeaderText("Your current order is as follows:");
    alert.setContentText(currentOrder);
    alert.getDialogPane().setStyle(" -fx-max-width:500px; -fx-pref-width: 500px;");

    alert.showAndWait();
  }

  public void finishOrder() {
    String message, transaction;
    message = buildInvoice();
    transaction = buildTransaction();

    invoiceAlert(message);
    writeTransactionsToFile(transaction);

    newOrder();
  }

  public void newOrder() {
    text_totalItems.setDisable(false);
    text_totalItems.setText("");
    text_bookID.setText("");
    text_quantity.setText("");
    text_info.setText("");
    text_subtotal.setText("");

    btn_process.setDisable(false);
    btn_confirm.setDisable(true);
    btn_view.setDisable(true);
    btn_finish.setDisable(true);

    this.totalItemsLocked = false;
    this.itemCount = 0;
    this.subtotal = 0.0;
    this.grandTotal = 0.0;
    this.totalQuantity = 0;
    this.order = new Order();
    this.item = null;
    this.transDate = null;

    changeItemNumber();
  }

  public void exit() {
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Quit?");
    alert.setHeaderText("You've selected to quit this program.");
    alert.setContentText("Are you sure you want to quit?");

    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() == ButtonType.OK) System.exit(0);
  }

  private void readInventoryFromFile() {
    try {
      Scanner scan = new Scanner(new File("inventory.txt"));
      while (scan.hasNext()) {
        scan.useDelimiter(", ");
        String id = scan.next().trim();
        String title = scan.next().trim();
        scan.useDelimiter("\n");
        double price = Double.parseDouble(scan.next().replace(",", "").trim());
        Book book = new Book(id, title, price);
        inventory.add(book);
      }
    } catch (FileNotFoundException e) {
      System.out.println("DEBUG: -----Start-----\n" + e + "DEBUG: ------End------\n");
    }
  }

  private void writeTransactionsToFile(String transaction) {
    try {
      writer =
          new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output, true), "utf-8"));
      writer.append(transaction);
      writer.append(newLine);
    } catch (IOException e) {
      System.out.println("DEBUG: -----Start-----\n" + e + "DEBUG: ------End------\n");
    }
    try {
      if (writer != null) writer.close();
    } catch (IOException e) {
      System.out.println("DEBUG: -----Start-----\n" + e + "DEBUG: ------End------\n");
    }
  }

  private void createItem() {
    try {
      if (!totalItemsLocked) {
        totalItems = Integer.parseInt(text_totalItems.getText());
        totalItemsLocked = true;
      }
      String bookQuery = text_bookID.getText();
      boolean found = false;
      for (Book book : inventory)
        if (book.getId().equals(bookQuery)) {
          this.item = new Item(book, Integer.parseInt(text_quantity.getText()));
          found = true;
        }
      if (!found) bookNotFoundAlert(bookQuery);
    } catch (Exception e) {
      System.out.println("DEBUG: -----Start-----\n" + e + "DEBUG: ------End------\n");
    }
  }

  private String buildInvoice() {
    double taxRate = 6;
    String message;

    this.grandTotal = ((taxRate / 100) * this.subtotal) + this.subtotal;

    DateFormat dateFormat = new SimpleDateFormat("dd/MM/YY HH:mm:ss z");
    this.transDate = new Date();

    message = "Date: " + dateFormat.format(this.transDate) + "\n\n";
    message += "Number of line items: " + this.totalItems + "\n\n";
    message += "Item# / ID / Title / Price / Qty / Disc % / Subtotal:\n\n";
    int counter = 0;
    for (Item i : order.getOrder()) {
      counter++;
      message += counter + ". " + i.toString() + "\n";
    }
    message += "\n";
    message += "Order subtotal: " + formatter.format(this.subtotal) + "\n\n";
    message += "Tax rate: " + taxRate + "%\n\n";
    message += "Tax amount: " + formatter.format(((taxRate / 100) * this.subtotal)) + "\n\n";
    message += "Order total: " + formatter.format(this.grandTotal) + "\n\n";
    message += "Thanks for shopping at Funky Town Books\n\n";

    return message;
  }

  private String buildTransaction() {
    String transaction = "";
    DateFormat dateFormat;

    for (Item i : order.getOrder()) {
      dateFormat = new SimpleDateFormat("YYMMddHHmmss");
      transaction += dateFormat.format(this.transDate) + ", ";
      transaction +=
          i.getBook().getId() + ", " + i.getBook().getTitle() + ", " + i.getBook().getPriceStr();
      transaction +=
          ", " + i.getQuantity() + ", " + i.getPercentStr() + ", " + i.getTotalStr() + ", ";
      dateFormat = new SimpleDateFormat("dd/MM/YY HH:mm:ss z");
      transaction += dateFormat.format(this.transDate) + newLine;
    }
    return transaction;
  }

  private void changeItemNumber() {
    if (totalItems > itemCount) {
      itemCount++;
      label_bookID.setText("Enter Book ID for Item #" + itemCount + ": ");
      label_quantity.setText("Enter quantity for Item #" + itemCount + ": ");
      label_info.setText("Info for Item #" + itemCount + ": ");
      label_subtotal.setText("Order subtotal for " + this.totalQuantity + " Item(s): ");
      btn_process.setText("Process Item #" + itemCount);
      btn_confirm.setText("Confirm Item #" + itemCount);
    } else {
      label_subtotal.setText("Order subtotal for " + this.totalQuantity + " Item(s): ");
      btn_process.setDisable(true);
      btn_confirm.setDisable(true);
      btn_finish.setDisable(false);
    }
  }

  private void bookNotFoundAlert(String id) {
    Alert alert = new Alert(Alert.AlertType.INFORMATION);
    alert.setTitle("Book Not on File!");
    alert.setHeaderText(null);
    alert.setContentText("Book ID: " + id + " is not in our inventory.");

    alert.show();
  }

  private void confirmAlert() {
    Alert alert = new Alert(Alert.AlertType.INFORMATION);
    alert.setTitle("Item Accepted");
    alert.setHeaderText(null);
    alert.setContentText("Item #" + itemCount + " accepted.");

    alert.show();
  }

  private void invoiceAlert(String message) {
    Alert alert = new Alert(Alert.AlertType.INFORMATION);
    alert.setTitle("Invoice");
    alert.setHeaderText(null);
    alert.setContentText(message);
    alert.getDialogPane().setStyle(" -fx-max-width:500px; -fx-pref-width: 500px;");

    alert.show();
  }
}
Exemplo n.º 7
0
  @Override
  public void start(Stage primaryStage) throws Exception {
    /* create the menu (for the top of the user interface) */
    Menu fileMenu = new Menu("File");
    MenuItem newMenuItem = new MenuItem("New", imageFile("images/new.png"));
    newMenuItem.setAccelerator(KeyCombination.keyCombination("Ctrl+N"));
    fileMenu.getItems().add(newMenuItem);
    fileMenu.getItems().add(new SeparatorMenuItem());
    fileMenu.getItems().add(new MenuItem("Open...", imageFile("images/open.png")));
    fileMenu.getItems().add(new SeparatorMenuItem());
    MenuItem saveMenuItem = new MenuItem("Save", imageFile("images/save.png"));
    fileMenu.getItems().add(saveMenuItem);
    MenuItem saveAsMenuItem = new MenuItem("Save As...", imageFile("images/save_as.png"));
    fileMenu.getItems().add(saveAsMenuItem);
    fileMenu.getItems().add(new SeparatorMenuItem());
    MenuItem exitMenuItem = new MenuItem("Exit", imageFile("images/exit.png"));
    fileMenu.getItems().add(exitMenuItem);
    exitMenuItem.setAccelerator(KeyCombination.keyCombination("Ctrl+Q"));
    exitMenuItem.setOnAction(e -> System.exit(0));

    Menu editMenu = new Menu("Edit");
    editMenu.getItems().add(new MenuItem("Cut", imageFile("images/cut.png")));
    editMenu.getItems().add(new MenuItem("Copy", imageFile("images/copy.png")));
    editMenu.getItems().add(new MenuItem("Paste", imageFile("images/paste.png")));

    Menu helpMenu = new Menu("Help");
    helpMenu.getItems().add(new MenuItem("About...", imageFile("images/about.png")));
    helpMenu.getItems().add(new SeparatorMenuItem());
    helpMenu.getItems().add(new MenuItem("Help...", imageFile("images/help.png")));

    MenuBar menuBar = new MenuBar();
    menuBar.getMenus().add(fileMenu);
    menuBar.getMenus().add(editMenu);
    menuBar.getMenus().add(helpMenu);
    primaryStage.setTitle("Lab08");
    // grid contains all of the textfeilds, labels , buttons, ect..
    GridPane grid = new GridPane();
    // the tableview puts all of our data into a exel like format
    TableView<StudentRecord> table = new TableView<>();
    table.setItems(DataSource.getAllMarks());
    table.setEditable(true);

    TableColumn<StudentRecord, String> IDColumn = null;
    IDColumn = new TableColumn<>("SID");
    IDColumn.setMinWidth(100);
    // the thing in quotes is what it will search for in the StudentRecords.java (MAKE SURE THERE IS
    // A GET FUNCTION FOR THAT VARIBALE)
    IDColumn.setCellValueFactory(new PropertyValueFactory<>("ID"));

    TableColumn<StudentRecord, Double> AssignmentColumn = null;
    AssignmentColumn = new TableColumn<>("Assignment");
    AssignmentColumn.setMinWidth(100);
    AssignmentColumn.setCellValueFactory(new PropertyValueFactory<>("Assign"));

    TableColumn<StudentRecord, Float> MidtermColumn = null;
    MidtermColumn = new TableColumn<>("Midterm");
    MidtermColumn.setMinWidth(100);
    MidtermColumn.setCellValueFactory(new PropertyValueFactory<>("Midterm"));

    TableColumn<StudentRecord, Float> FinalColumn = null;
    FinalColumn = new TableColumn<>("Final Exam");
    FinalColumn.setMinWidth(100);
    FinalColumn.setCellValueFactory(new PropertyValueFactory<>("Final"));

    TableColumn<StudentRecord, String> GradeColumn = null;
    GradeColumn = new TableColumn<>("Letter Grade");
    GradeColumn.setMinWidth(100);
    GradeColumn.setCellValueFactory(new PropertyValueFactory<>("Grade"));

    table.getColumns().add(IDColumn);
    table.getColumns().add(AssignmentColumn);
    table.getColumns().add(MidtermColumn);
    table.getColumns().add(FinalColumn);
    table.getColumns().add(GradeColumn);

    Label IDLabel = new Label("SID:");
    grid.add(IDLabel, 0, 0);
    TextField IDField = new TextField();
    IDField.setPromptText("SID");
    grid.add(IDField, 1, 0);

    Label AssignLabel = new Label("Assignments:");
    grid.add(AssignLabel, 2, 0);

    TextField AssignField = new TextField();
    AssignField.setPromptText("Assignment");
    grid.add(AssignField, 3, 0);

    Label MidLabel = new Label("Midterm:");
    grid.add(MidLabel, 0, 1);

    TextField midField = new TextField();
    midField.setPromptText("Midterm");
    grid.add(midField, 1, 1);

    Label FinalLabel = new Label("Final:");
    grid.add(FinalLabel, 2, 1);

    TextField FinalField = new TextField();
    FinalField.setPromptText("Final");
    grid.add(FinalField, 3, 1);

    Button AddButton = new Button("Add");
    AddButton.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent e) {
            char Grade;
            String SID = IDField.getText();
            Float Assignment = Float.parseFloat(AssignField.getText());
            Float Midterm = Float.parseFloat(midField.getText());
            Float Final = Float.parseFloat(FinalField.getText());
            table.getItems().add(new StudentRecord(SID, Assignment, Midterm, Final));

            IDField.setText("");
            AssignField.setText("");
            midField.setText("");
            FinalField.setText("");
          }
        });
    grid.add(AddButton, 0, 2);

    layout = new BorderPane();
    layout.setTop(menuBar);
    layout.setCenter(table);
    layout.setBottom(grid);

    Scene scene = new Scene(layout);
    grid.setPadding(new Insets(10, 10, 10, 10));
    grid.setVgap(10);
    grid.setHgap(10);

    primaryStage.setScene(scene);
    primaryStage.show();
  }
Exemplo n.º 8
0
 public void configureFileChooser(FileChooser fc) {
   fc.setInitialDirectory(new File(System.getProperty("user.home")));
   fc.getExtensionFilters()
       .add(new FileChooser.ExtensionFilter("Файлы \"зерна\"", GRAIN_FILE_EXTENSION));
 }
Exemplo n.º 9
0
  @Override
  public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("JavaFX Demo");

    /* create the menu (for the top of the user interface) */
    Menu fileMenu = new Menu("File");
    MenuItem newMenuItem = new MenuItem("New", imageFile("images/new.png"));
    newMenuItem.setAccelerator(KeyCombination.keyCombination("Ctrl+N"));
    fileMenu.getItems().add(newMenuItem);
    fileMenu.getItems().add(new SeparatorMenuItem());
    fileMenu.getItems().add(new MenuItem("Open...", imageFile("images/open.png")));
    fileMenu.getItems().add(new SeparatorMenuItem());
    fileMenu.getItems().add(new MenuItem("Save", imageFile("images/save.png")));
    fileMenu.getItems().add(new MenuItem("Save As...", imageFile("images/save_as.png")));
    fileMenu.getItems().add(new SeparatorMenuItem());
    MenuItem exitMenuItem = new MenuItem("Exit", imageFile("images/exit.png"));
    fileMenu.getItems().add(exitMenuItem);
    exitMenuItem.setAccelerator(KeyCombination.keyCombination("Ctrl+Q"));
    exitMenuItem.setOnAction(e -> System.exit(0));

    Menu editMenu = new Menu("Edit");
    editMenu.getItems().add(new MenuItem("Cut", imageFile("images/cut.png")));
    editMenu.getItems().add(new MenuItem("Copy", imageFile("images/copy.png")));
    editMenu.getItems().add(new MenuItem("Paste", imageFile("images/paste.png")));

    Menu helpMenu = new Menu("Help");
    helpMenu.getItems().add(new MenuItem("About...", imageFile("images/about.png")));
    helpMenu.getItems().add(new SeparatorMenuItem());
    helpMenu.getItems().add(new MenuItem("Help...", imageFile("images/help.png")));

    MenuBar menuBar = new MenuBar();
    menuBar.getMenus().add(fileMenu);
    menuBar.getMenus().add(editMenu);
    menuBar.getMenus().add(helpMenu);

    /* create the table (for the center of the user interface) */
    table = new TableView<>();
    table.setItems(DataSource.getAllStudents());
    table.setEditable(true);

    /* create the table's columns */
    TableColumn<Student, Integer> sidColumn = null;
    sidColumn = new TableColumn<>("SID");
    sidColumn.setMinWidth(100);
    sidColumn.setCellValueFactory(new PropertyValueFactory<>("sid"));

    TableColumn<Student, String> firstNameColumn = null;
    firstNameColumn = new TableColumn<>("First Name");
    firstNameColumn.setMinWidth(200);
    firstNameColumn.setCellValueFactory(new PropertyValueFactory<>("firstName"));
    firstNameColumn.setCellFactory(TextFieldTableCell.<Student>forTableColumn());
    firstNameColumn.setOnEditCommit(
        (CellEditEvent<Student, String> event) -> {
          ((Student) event.getTableView().getItems().get(event.getTablePosition().getRow()))
              .setFirstName(event.getNewValue());
        });

    TableColumn<Student, String> lastNameColumn = null;
    lastNameColumn = new TableColumn<>("Last Name");
    lastNameColumn.setMinWidth(200);
    lastNameColumn.setCellValueFactory(new PropertyValueFactory<>("lastName"));
    lastNameColumn.setCellFactory(TextFieldTableCell.<Student>forTableColumn());
    lastNameColumn.setOnEditCommit(
        (CellEditEvent<Student, String> event) -> {
          ((Student) event.getTableView().getItems().get(event.getTablePosition().getRow()))
              .setLastName(event.getNewValue());
        });

    TableColumn<Student, Double> gpaColumn = null;
    gpaColumn = new TableColumn<>("GPA");
    gpaColumn.setMinWidth(100);
    gpaColumn.setCellValueFactory(new PropertyValueFactory<>("gpa"));

    table.getColumns().add(sidColumn);
    table.getColumns().add(lastNameColumn);
    table.getColumns().add(firstNameColumn);
    table.getColumns().add(gpaColumn);

    /* create an edit form (for the bottom of the user interface) */
    GridPane editArea = new GridPane();
    editArea.setPadding(new Insets(10, 10, 10, 10));
    editArea.setVgap(10);
    editArea.setHgap(10);

    Label sidLabel = new Label("SID:");
    editArea.add(sidLabel, 0, 0);
    TextField sidField = new TextField();
    sidField.setPromptText("SID");
    editArea.add(sidField, 1, 0);

    Label fnameLabel = new Label("First name:");
    editArea.add(fnameLabel, 0, 1);
    TextField fnameField = new TextField();
    fnameField.setPromptText("First Name");
    editArea.add(fnameField, 1, 1);

    Label lnameLabel = new Label("Last name:");
    editArea.add(lnameLabel, 0, 2);
    TextField lnameField = new TextField();
    lnameField.setPromptText("Last Name");
    editArea.add(lnameField, 1, 2);

    Label gpaLabel = new Label("GPA:");
    editArea.add(gpaLabel, 0, 3);
    TextField gpaField = new TextField();
    gpaField.setPromptText("GPA");
    editArea.add(gpaField, 1, 3);

    Button addButton = new Button("Add");
    addButton.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent e) {
            int sid = Integer.parseInt(sidField.getText());
            String firstName = fnameField.getText();
            String lastName = lnameField.getText();
            double gpa = Double.parseDouble(gpaField.getText());

            table.getItems().add(new Student(sid, firstName, lastName, gpa));

            sidField.setText("");
            fnameField.setText("");
            lnameField.setText("");
            gpaField.setText("");
          }
        });
    editArea.add(addButton, 1, 4);

    /* arrange all components in the main user interface */
    layout = new BorderPane();
    layout.setTop(menuBar);
    layout.setCenter(table);
    layout.setBottom(editArea);

    Scene scene = new Scene(layout, 600, 600);
    primaryStage.setScene(scene);
    primaryStage.show();
  }
 public void quit() {
   System.exit(0);
 }
Exemplo n.º 11
0
 public static File getUserHomeDir() {
   return new File(System.getProperty("user.home"));
 }
Exemplo n.º 12
0
  void setupTracksContextMenu() {
    ContextMenu cm = tracksContextMenu;
    List<MenuItem> items = cm.getItems();
    items.clear();

    Playlist pl = getSelectedPlaylist();
    if (pl == null) {
      items.add(
          menuItem(
              "-> " + res.getString("add_to"),
              () -> {
                menuAddToPlaylist();
              }));
      if (rememberedPlaylist != null) {
        items.add(
            menuItem(
                "-> "
                    + String.format(
                        res.getString("add_to_featured"), rememberedPlaylist.getTitle()),
                () -> {
                  Track t = getSelectedTrack();
                  if (t != null) {
                    addToPlaylist(t, rememberedPlaylist);
                  }
                }));
      }
    } else {
      items.add(
          menuItem(
              "(+) " + res.getString("add_files"),
              () -> {
                FileChooser fileChooser = new FileChooser();
                fileChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
                fileChooser.setTitle(String.format(res.getString("add_files_to"), pl.getTitle()));
                fileChooser
                    .getExtensionFilters()
                    .addAll(new FileChooser.ExtensionFilter("MP3", "*.mp3"));
                List<File> files = fileChooser.showOpenMultipleDialog(null);
                if (files != null) {
                  addToPlaylist(files, pl);
                }
              }));
      items.add(
          menuItem(
              "(+) " + res.getString("add_folder_recursively"),
              () -> {
                DirectoryChooser dirChooser = new DirectoryChooser();
                dirChooser.setTitle(String.format(res.getString("add_folder_to"), pl.getTitle()));
                dirChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
                File dir = dirChooser.showDialog(null);
                if (dir == null) return;
                Collection<File> files = FileUtils.listFiles(dir, new String[] {"mp3"}, true);
                addToPlaylist(new ArrayList(files), pl);
              }));
      items.add(new SeparatorMenuItem());
      if (rememberedPlaylist != null)
        items.add(
            menuItem(
                "-> "
                    + String.format(
                        res.getString("add_to_featured"), rememberedPlaylist.getTitle()),
                () -> {
                  Track t = getSelectedTrack();
                  if (t != null) addToPlaylist(t, rememberedPlaylist);
                }));
      items.add(
          menuItem(
              "-> " + res.getString("add_to"),
              () -> {
                menuAddToPlaylist();
              }));
      items.add(new SeparatorMenuItem());
      items.add(
          menuItem(
              "(...) " + res.getString("rename_track"),
              () -> {
                renameTrack();
              }));
      items.add(new SeparatorMenuItem());
      items.add(
          menuItem(
              "(-) " + res.getString("delete_track") + pl.getTitle(),
              () -> {
                deleteTrackFromPlaylist();
              }));
      items.add(
          menuItem(
              "(-) " + res.getString("delete_dead_items"),
              () -> {
                Track t = getSelectedTrack();
                if (t == null) {
                  return;
                }
                deleteDeadFromOfflinePlaylist(pl);
              }));
    }
  }
Exemplo n.º 13
0
  @Override
  public void start(Stage primaryStage) {

    VBox loginPane = new VBox();
    loginPane.setAlignment(Pos.CENTER);
    primaryStage.setTitle("Amoeba");
    primaryStage.setScene(new Scene(loginPane, 800, 600));
    primaryStage.show();

    TextField username = new TextField();
    username.setPromptText("Username");
    username.setMaxSize(200, 50);

    Timeline renderTimer = new Timeline();
    Timeline inputTimer = new Timeline();

    ColorPicker colorPicker = new ColorPicker();
    colorPicker.setEditable(true);
    colorPicker.setValue(Color.BLACK);

    lagLabel.setTranslateX(25);
    lagLabel.setTranslateY(10);
    lagLabel.setTextFill(Color.RED);

    TextField address = new TextField("localhost");
    address.setPromptText("Server IP Address");
    address.setMaxSize(200, 50);

    TextField port = new TextField("8080");
    port.setPromptText("Port Number");
    port.setMaxSize(200, 50);

    Button btn = new Button("Play");
    btn.setDefaultButton(true);

    loginPane.getChildren().addAll(username, colorPicker, address, port, btn);

    primaryStage.setResizable(false);
    music.setCycleCount(MediaPlayer.INDEFINITE);
    renderPane.setBackground(new Background(backgroundImage));
    renderPane.setPrefSize(800, 600);

    chatBox.setPrefSize(400, 100);
    chatBox.setTranslateX(0);
    chatBox.setTranslateY(468);
    chatBox.setWrapText(true);
    chatBox.setEditable(false);
    chatBox.setStyle("-fx-opacity: 0.5");

    chatInput.setPrefSize(400, 10);
    chatInput.setTranslateX(0);
    chatInput.setTranslateY(570);
    chatInput.setStyle("-fx-opacity: 0.8");

    highScores.setPrefSize(400, 210);
    highScores.setEditable(false);
    currentScores.setPrefSize(400, 250);
    currentScores.setEditable(false);
    currentScores.setLayoutY(210);
    scores.setTranslateX(-390);
    scores.setTranslateY(0);
    scores.setStyle("-fx-opacity: 0.8");

    scores.setOnMouseEntered(
        (e) -> {
          scores.setTranslateX(0);
        });

    scores.setOnMouseExited(
        (e) -> {
          if (e.getX() > 350) {
            scores.setTranslateX(-390);
          }
        });

    btn.setOnAction(
        (e) -> {
          if (!networkController.isConnected()) {
            networkController.connect(address.getText(), Integer.parseInt(port.getText()));
            if (username.getText().isEmpty()) {
              username.setText("Anonymous");
            }
            networkController.sendMessage(new LoginMessage(username.getText(), ""));

            ArrayList<KeyValuePair> properties = new ArrayList<>();
            properties.add(new KeyValuePair("color", colorPicker.getValue().toString()));
            networkController.sendMessage(new SetBlobPropertiesMessage(properties));

            primaryStage.setScene(new Scene(renderPane));
            renderTimer.play();
            inputTimer.play();
            music.play();
          }
        });

    inputTimer.setCycleCount(Timeline.INDEFINITE);
    inputTimer
        .getKeyFrames()
        .add(
            new KeyFrame(
                Duration.seconds(0.05),
                (e) -> {
                  if (sendCoordinates) {
                    networkController.sendMessage(new MoveTowardCoordinatesMessage(x, y));
                  }
                }));

    renderTimer.setCycleCount(Timeline.INDEFINITE);
    renderTimer
        .getKeyFrames()
        .add(
            new KeyFrame(
                Duration.seconds(0.01),
                (e) -> {
                  render();
                }));

    renderPane.setOnMouseReleased(
        (e) -> {
          this.sendCoordinates = false;
        });

    renderPane.setOnMouseDragged(
        (e) -> {
          this.sendCoordinates = true;
          this.x = e.getX();
          this.y = e.getY();
        });

    renderPane.setOnMouseClicked(
        (e) -> {
          if (e.getButton() == MouseButton.SECONDARY) {
            networkController.sendMessage(new BoostMessage());
          } else if (e.getClickCount() > 1 || e.getButton() == MouseButton.MIDDLE) {
            networkController.sendMessage(new SplitMessage());
          }
        });

    renderPane.setOnKeyPressed(
        (e) -> {
          if (e.getCode().equals(KeyCode.ENTER) && !chatInput.getText().isEmpty()) {
            networkController.sendMessage(new ChatMessage("", chatInput.getText()));
            chatInput.clear();
          }
        });

    primaryStage.setOnCloseRequest(
        (e) -> {
          networkController.sendMessage(new LogoutMessage());
          try {
            Thread.sleep(100);
          } catch (InterruptedException ex) {
            Logger.getLogger(AmoebaClient.class.getName()).log(Level.WARNING, null, ex);
          } finally {
            System.exit(0);
          }
        });
  }
Exemplo n.º 14
0
  private void render() {
    ArrayList<NetworkMessage> messages = networkController.getMessages();

    for (NetworkMessage message : messages) {
      String messageType =
          message.getClass().getName().replace("NetworkMessages.", "").replace("Messages.", "");
      switch (messageType) {
        case "PelletPositionMessage":
          {
            PelletPositionMessage m = (PelletPositionMessage) message;
            Drawable drawable = getCachedDrawable(m.id);
            if (drawable != null) {
              drawable.node.relocate(m.x, m.y);
              drawable.cacheMisses = 0;
            } else {
              Random r = new Random();
              Node node =
                  drawCircle(
                      m.x, m.y, 5, new Color(r.nextFloat(), r.nextFloat(), r.nextFloat(), 1));
              drawableCache.add(new Drawable(m.id, node));
            }
          }
          break;
        case "BlobStateMessage":
          {
            BlobStateMessage m = (BlobStateMessage) message;
            Color color = Color.web(m.color);
            Node node;
            if (color.getBrightness() != 0) {
              node = drawCircle(m.x, m.y, m.size / 2, color);
            } else {
              node = drawCircle(m.x, m.y, m.size / 2, color.brighter().brighter());
            }
            Node nameText =
                drawText((m.x - m.username.length() * 5), (m.y - m.size / 2), m.username, color);
            Drawable drawable = getCachedDrawable(m.id);
            if (drawable != null) {
              node.setLayoutX((drawable.node.getTranslateX() - m.x) / 10000);
              node.setLayoutY((drawable.node.getTranslateY() - m.y) / 10000);
              drawable.node = node;
              drawable.cacheMisses = 0;
              Drawable nameTag = getCachedDrawable(m.id + 9000);
              nameTag.node = nameText;
              nameTag.cacheMisses = 0;
            } else {
              drawableCache.add(new Drawable(m.id, node));
              drawableCache.add(new Drawable(m.id + 9000, nameText));
            }
          }
          break;
        case "PingMessage":
          {
            renderPane.getChildren().clear();
            ArrayList<Drawable> drawables = new ArrayList<>(drawableCache);
            for (Drawable drawable : drawables) {
              if (drawable.cacheMisses > 1) {
                drawableCache.remove(drawable);
              }
              drawable.cacheMisses++;
              renderPane.getChildren().add(drawable.node);
            }
            renderPane.getChildren().addAll(chatBox, chatInput, lagLabel, scores);

            lag = System.currentTimeMillis() - lastReceivedTime;
            lastReceivedTime = System.currentTimeMillis();
            lagLabel.setText("Net Lag: " + Long.toString(lag));
          }
          break;
        case "HighScoreMessage":
          {
            HighScoreMessage m = (HighScoreMessage) message;
            highScores.setText("HIGH SCORES:" + m.text);
          }
          break;
        case "CurrentScoreMessage":
          {
            CurrentScoreMessage m = (CurrentScoreMessage) message;
            currentScores.setText("Current Scores:" + m.text);
          }
          break;
        case "ChatMessage":
          {
            ChatMessage m = (ChatMessage) message;
            chatBox.appendText(m.username + "> " + m.text + "\n");
          }
          break;
      }
    }
  }
 /**
  * Cancel button click handler.
  *
  * @param event {@link javafx.event.ActionEvent}
  */
 @FXML
 private void cancelButtonClick(ActionEvent event) {
   System.exit(0);
 }
Exemplo n.º 16
0
 static {
   isProxyingEnabled.addListener(
       (observable, oldValue, newValue) -> {
         if (newValue) {
           System.setProperty("http.proxySet", "true");
           System.setProperty("http.proxyHost", "127.0.0.1");
           System.setProperty("http.proxyPort", "8080");
           System.setProperty("https.proxySet", "true");
           System.setProperty("https.proxyHost", "127.0.0.1");
           System.setProperty("https.proxyPort", "8080");
         } else {
           System.clearProperty("http.proxySet");
           System.clearProperty("http.proxyHost");
           System.clearProperty("http.proxyPort");
           System.clearProperty("https.proxySet");
           System.clearProperty("https.proxyHost");
           System.clearProperty("https.proxyPort");
         }
       });
 }
 public void miExitHandle(ActionEvent actionEvent) {
   System.exit(0);
 }
Exemplo n.º 18
0
  /**
   * The opening class. When the launch method is run, the code in here begins to execute. All code
   *
   * @param primaryStage The intial stage opened on run
   * @throws Exception
   */
  @SuppressWarnings("unchecked")
  public void start(Stage primaryStage) throws Exception {
    primaryStage.setMaximized(true);
    primaryStage.setTitle("Equipment Manager");
    Button executive = new Button("Executive Options");
    TextField search = new TextField();
    search.setPromptText("Search");
    TableView<Item> table;

    // create filenames
    String fileName = System.getProperty("user.home") + "/item.csv";
    String passFileName = System.getProperty("user.home") + "/notoflookinghere.csv";
    String IDFileName = System.getProperty("user.home") + "/memberlist.csv";
    String logFileName = System.getProperty("user.home") + "/Log.csv";
    File x = new File(fileName);
    // if no file exists with given names, create default files
    if (!x.exists()) {
      csvFileWriter write = new csvFileWriter();
      write.writeCsvFile(logFileName);
      write.writeCsvFile(fileName);
      write.writeCsvFile(IDFileName);
      ArrayList<Item> list = new ArrayList<>();
      list.add(new Item(1000, "password", true, "none", false));
      write.enterData(list);
      write.writeCsvFile(passFileName);
    } else {
      System.out.println("Files Read");
    }

    manage.searchFor(fileName, search.getText());

    table = new TableView<>();
    table.setItems(UIManager.getItems(fileName, search.getText()));
    table.setMaxWidth(675);
    table
        .getColumns()
        .addAll(
            UIManager.referenceColumn(),
            UIManager.nameColumn(),
            UIManager.availableColumn(),
            UIManager.IDColumn(),
            UIManager.permColumn());

    Button checkout = new Button("Checkout");
    checkout.setOnAction(
        e -> {
          Checking.checkOut(fileName, IDFileName, passFileName);
          table.setItems(UIManager.getItems(fileName, search.getText()));
        });

    Button checkIn = new Button("Checkin");
    checkIn.setOnAction(
        e -> {
          Checking.checkIn(fileName);
          table.setItems(UIManager.getItems(fileName, search.getText()));
        });

    search.setOnKeyPressed(e -> table.setItems(UIManager.getItems(fileName, search.getText())));

    // This creates and sets up all the menu bars on the top of the page
    MenuBar menuBar = new MenuBar();

    // Menu Tabs
    Menu help = new Menu("_Help");
    Menu exec = new Menu("_Executive Settings");
    menuBar.getMenus().addAll(help, exec);

    // Menu Items
    MenuItem code = new MenuItem("View Code");
    MenuItem report = new MenuItem("Report a Bug");
    MenuItem openOptions = new MenuItem("Open Executive Options");
    help.getItems().addAll(code, report);
    exec.getItems().addAll(openOptions);

    // Menu External Links
    URI codeLink = new URI("https://github.com/NHSTechTeam/Equipment-System");
    URI reportLink = new URI("https://github.com/NHSTechTeam/Equipment-System/issues");

    // Menu Actions
    code.setOnAction(e -> UIManager.openWebpage(codeLink));
    report.setOnAction(e -> UIManager.openWebpage(reportLink));
    openOptions.setOnAction(
        e -> {
          try {
            ExecutiveMain.executive(fileName, passFileName, logFileName, IDFileName);
          } catch (URISyntaxException e1) {
            e1.printStackTrace();
          }
        });

    HBox menu = new HBox();
    menu.setPadding(new Insets(10, 10, 10, 10));
    menu.setSpacing(10);
    menu.setAlignment(Pos.CENTER);
    menu.getChildren().addAll(checkout, checkIn);

    executive.setOnAction(
        e -> {
          try {
            ExecutiveMain.executive(fileName, passFileName, logFileName, IDFileName);
          } catch (URISyntaxException e1) {
            e1.printStackTrace();
          }
        });

    BorderPane borderLayout = new BorderPane();
    VBox layout = new VBox(10);
    borderLayout.setTop(menuBar);
    borderLayout.setCenter(layout);
    layout.getChildren().addAll(search, table, menu, executive);
    layout.setAlignment(Pos.CENTER);
    Scene scene = new Scene(borderLayout, 300, 250);
    scene.getStylesheets().add("style.css");
    primaryStage.getIcons().add(new Image("images/icon.png"));
    primaryStage.setScene(scene);
    primaryStage.show();
  }