com.jfoenix.controls.JFXComboBox

Here are the examples of the java api com.jfoenix.controls.JFXComboBox taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

77 Examples 7

19 Source : ServiceInputLuggageViewController.java
with MIT License
from ThijsZijdel

// Method to check whether a combobox has been filled
public String checkComboBox(JFXComboBox comboBox) {
    if (comboBox.getValue() != null && !comboBox.getValue().toString().isEmpty()) {
        return comboBox.getValue().toString();
    } else {
        return "";
    }
}

19 Source : AutoCompleteComboBoxListener.java
with MIT License
from karakasis

/**
 * @author Christos
 */
public clreplaced AutoCompleteComboBoxListener<T> implements EventHandler<KeyEvent> {

    private JFXComboBox<T> comboBox;

    private ObservableList<T> data;

    private boolean moveCaretToPos = false;

    private int caretPos;

    private StringConverter<T> sc;

    AutoCompleteComboBoxListener(final JFXComboBox<T> comboBox) {
        this.comboBox = comboBox;
        data = comboBox.gereplacedems();
        // this.comboBox.setEditable(true);
        this.comboBox.setOnKeyPressed(t -> comboBox.hide());
        this.comboBox.setOnKeyReleased(AutoCompleteComboBoxListener.this);
        this.sc = this.comboBox.getConverter();
    }

    @Override
    public void handle(KeyEvent event) {
        if (event.getCode() == KeyCode.UP) {
            caretPos = -1;
            moveCaret(comboBox.getEditor().getText().length());
            return;
        } else if (event.getCode() == KeyCode.DOWN) {
            if (!comboBox.isShowing()) {
                comboBox.show();
            }
            caretPos = -1;
            moveCaret(comboBox.getEditor().getText().length());
            return;
        } else if (event.getCode() == KeyCode.BACK_SPACE) {
            moveCaretToPos = true;
            caretPos = comboBox.getEditor().getCaretPosition();
        } else if (event.getCode() == KeyCode.DELETE) {
            moveCaretToPos = true;
            caretPos = comboBox.getEditor().getCaretPosition();
        }
        if (event.getCharacter().matches("[a-z]"))
            comboBox.setValue((T) String.valueOf(comboBox.getValue()).toUpperCase());
        if (event.getCode() == KeyCode.RIGHT || event.getCode() == KeyCode.LEFT || event.isControlDown() || event.getCode() == KeyCode.HOME || event.getCode() == KeyCode.END || event.getCode() == KeyCode.TAB) {
            return;
        }
        // if(comboBox.gereplacedems().isEmpty()) comboBox.gereplacedems().addAll(data);
        ObservableList<T> list = FXCollections.observableArrayList();
        for (T aData : data) {
            if (sc.toString(aData).toLowerCase().contains(AutoCompleteComboBoxListener.this.comboBox.getEditor().getText().toLowerCase())) {
                list.add(aData);
            }
        /*
            if (String.valueOf(aData).toLowerCase().startsWith(
                    AutoCompleteComboBoxListener.this.comboBox
                            .getEditor().getText().toLowerCase())) {
                list.add(aData);
            }*/
        }
        String t = comboBox.getEditor().getText();
        comboBox.gereplacedems().clear();
        comboBox.gereplacedems().addAll(list);
        comboBox.getEditor().setText(t);
        if (!moveCaretToPos) {
            caretPos = -1;
        }
        moveCaret(t.length());
        if (!list.isEmpty()) {
            comboBox.show();
        }
    }

    private void moveCaret(int textLength) {
        if (caretPos == -1) {
            comboBox.getEditor().positionCaret(textLength);
        } else {
            comboBox.getEditor().positionCaret(caretPos);
        }
        moveCaretToPos = false;
    }
}

18 Source : ManageReceptionUIController.java
with Apache License 2.0
from Shehanka

/**
 * @author chamodshehanka on 4/25/2018
 * @project RentLio
 */
public clreplaced ManageReceptionUIController implements Initializable {

    @FXML
    private JFXTextField txtReceptionId;

    @FXML
    private JFXComboBox<String> cmbBranchName;

    @FXML
    private JFXTextField txtReceptionName;

    @FXML
    private JFXTextField txtReceptionAddress;

    @FXML
    private JFXTextField txtReceptionEmail;

    @FXML
    private JFXTextField txtReceptionTel;

    @FXML
    private JFXTextField txtReceptionNIC;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // generateReceptionId();
        setBranches();
    }

    @FXML
    private void AddReceptionAction() {
        ReceptionDTO receptionDTO = new ReceptionDTO(txtReceptionId.getText(), cmbBranchName.getValue(), txtReceptionName.getText(), txtReceptionAddress.getText(), txtReceptionEmail.getText(), Integer.valueOf(txtReceptionTel.getText()), txtReceptionNIC.getText());
        try {
            boolean isAdded = ReceptionController.addReception(receptionDTO);
            if (isAdded) {
                new AlertBuilder("info", "Manage Reception", "Reception Add", "Reception has been successfully added !!");
            } else {
                new AlertBuilder("error", "Manage Reception", "Reception Add", "Reception couldn't add !!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void getReceptionByID() {
        try {
            ReceptionDTO receptionDTO = ReceptionController.findById(txtReceptionId.getText());
            if (receptionDTO != null) {
                cmbBranchName.gereplacedems().setAll(getBranchByID(receptionDTO.getBranchId()));
                txtReceptionName.setText(receptionDTO.getName());
                txtReceptionAddress.setText(receptionDTO.getAddress());
                txtReceptionEmail.setText(receptionDTO.getEmail());
                txtReceptionTel.setText(String.valueOf(receptionDTO.getTel()));
                txtReceptionNIC.setText(receptionDTO.getNic());
            } else {
                new AlertBuilder("warn", "Manage Reception", "Reception Search", "Reception couldn't find !!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getBranchByID(String branchId) {
        BranchDTO branchDTO = new BranchDTO();
        try {
            branchDTO = BranchController.getBranchById(branchId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return branchDTO.getAddress();
    }

    @FXML
    private void updateReceptionAction() {
        ReceptionDTO receptionDTO = new ReceptionDTO(txtReceptionId.getText(), cmbBranchName.getValue(), txtReceptionName.getText(), txtReceptionAddress.getText(), txtReceptionEmail.getText(), Integer.valueOf(txtReceptionTel.getText()), txtReceptionNIC.getText());
        try {
            boolean isUpdated = ReceptionController.updateReception(receptionDTO);
            if (isUpdated) {
                new AlertBuilder("info", "Manage Reception", "Reception Update", "Reception has been successfully updated !!");
            } else {
                new AlertBuilder("error", "Manage Reception", "Reception Update", "Reception couldn't update !!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void deleteReceptionAction() {
        try {
            boolean isDeleted = ReceptionController.deleteReception(txtReceptionId.getText());
            if (isDeleted) {
                new AlertBuilder("info", "Manage Reception", "Reception Delete", "Reception has been successfully deleted !!");
            } else {
                new AlertBuilder("error", "Manage Reception", "Reception Delete", "Reception couldn't delete !!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void generateReceptionId() {
        try {
            txtReceptionId.setText(IDGenerator.getNewID("reception", "R"));
        // Set Request Focus
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setBranches() {
        List<BranchDTO> branchDTOArrayList = new ArrayList<>();
        try {
            branchDTOArrayList = BranchController.getAllBranches();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ArrayList branchList = new ArrayList();
        for (BranchDTO branchDTO : branchDTOArrayList) {
            branchList.add(branchDTO.getAddress());
        }
        cmbBranchName.gereplacedems().addAll(branchList);
    }
}

18 Source : AnimationDemo.java
with MIT License
from schlegel11

private JFXComboBox<String> createBodyComboBox(Consumer<String> selectionChangedConsumer) {
    JFXComboBox<String> comboBox = new JFXComboBox<>();
    comboBox.setPrefWidth(170);
    comboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> selectionChangedConsumer.accept(newValue));
    comboBox.focusColorProperty().bind(colorTransitionProperty);
    comboBox.unFocusColorProperty().bind(colorTransitionProperty);
    return comboBox;
}

18 Source : SM3Controller.java
with MIT License
from ffffffff0x

public clreplaced SM3Controller extends ViewControllerObject {

    /**
     * JTA_dst1 :HEX result
     * JTA_dst :base64 result
     */
    byte[] file = null;

    @FXML
    private JFXComboBox JCB_charset;

    @FXML
    private JFXToggleButton JTB_modeSelect;

    @Override
    protected void initialize() {
        super.initialize();
        ViewInit.comboBoxCharset(JCB_charset);
    }

    @Override
    public void ONClickConfirm() {
        super.ONClickConfirm();
        try {
            String[] dst = new String[0];
            if (JTB_modeSelect.getText().equals(Init.languageResourceBundle.getString("TextMode"))) {
                try {
                    dst = hash(JTA_src.getText().getBytes(JCB_charset.getValue().toString()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                dst = hash(file);
                FileEncodeend();
            }
            JTA_dst1.setText(dst[0]);
            JTA_dst.setText(dst[1]);
        } catch (Exception e) {
            ViewUtils.textAreaValidate(JTA_dst);
        }
    }

    private String[] hash(byte[] message) throws IOException {
        String[] out = new String[2];
        out[0] = Hex.encodeHexString(Modern_SM3.hash(message));
        out[1] = Base64.encodeBase64String(Modern_SM3.hash(message));
        return out;
    }

    @FXML
    public void ONClick_JCB_modeSelect() {
        if (JTB_modeSelect.isSelected()) {
            JTB_modeSelect.setText(Init.languageResourceBundle.getString("FileMode"));
            JTA_src.setEditable(false);
            try {
                File file_temp = ViewUtils.getFile();
                JTA_src.setText(file_temp.toString());
                file = FileUtils.getFilebyte(file_temp);
            } catch (Exception e) {
                e.printStackTrace();
                JTB_modeSelect.selectedProperty().setValue(false);
                JTB_modeSelect.setText(Init.languageResourceBundle.getString("TextMode"));
                JTA_src.setText("");
                JTA_src.setEditable(true);
            }
        } else {
            JTB_modeSelect.setText(Init.languageResourceBundle.getString("TextMode"));
            JTA_src.setText("");
            JTA_src.setEditable(true);
        }
    }

    public void FileEncodeend() {
        JTB_modeSelect.selectedProperty().set(false);
        JTB_modeSelect.setText(Init.languageResourceBundle.getString("TextMode"));
        JTA_src.setText("");
        JTA_src.setEditable(true);
    }
}

18 Source : HashController.java
with MIT License
from ffffffff0x

public clreplaced HashController extends ViewControllerObject {

    /**
     * JTA_dst1 :HEX result
     * JTA_dst :base64 result
     */
    byte[] file = null;

    @FXML
    private JFXComboBox JCB_charset;

    @FXML
    private JFXComboBox JCB_hashMode;

    @FXML
    private JFXToggleButton JTB_modeSelect;

    @Override
    protected void initialize() {
        super.initialize();
        initComboBox();
    }

    @Override
    public void ONClickConfirm() {
        super.ONClickConfirm();
        try {
            String[] dst = new String[0];
            if (JTB_modeSelect.getText().equals(Init.languageResourceBundle.getString("TextMode"))) {
                try {
                    dst = hash(JTA_src.getText().getBytes(JCB_charset.getValue().toString()));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                dst = hash(file);
                FileEncodeend();
            }
            JTA_dst1.setText(dst[0]);
            JTA_dst.setText(dst[1]);
        } catch (Exception e) {
            ViewUtils.textAreaValidate(JTA_dst);
        }
    }

    private void initComboBox() {
        JCB_hashMode.gereplacedems().addAll("MD5", "MD5-16", "MD2", "MD4", "SHA-1", "SHA-224", "SHA-256", "SHA-384", "SHA-512");
        JCB_hashMode.setValue("MD5");
        JCB_hashMode.setVisibleRowCount(6);
        ViewInit.comboBoxCharset(JCB_charset);
    }

    private String[] hash(byte[] message) {
        String[] out = new String[2];
        if (JCB_hashMode.getValue().equals("MD5-16")) {
            byte[] md5_16;
            md5_16 = Arrays.copyOfRange(Modern_Hash.hash(message, JCB_hashMode.getValue().toString()), 4, 12);
            out[0] = Hex.encodeHexString(md5_16);
            out[1] = Base64.encodeBase64String(md5_16);
        } else {
            out[0] = Hex.encodeHexString(Modern_Hash.hash(message, JCB_hashMode.getValue().toString()));
            out[1] = Base64.encodeBase64String(Modern_Hash.hash(message, JCB_hashMode.getValue().toString()));
        }
        return out;
    }

    @FXML
    public void ONClick_JCB_modeSelect() {
        if (JTB_modeSelect.isSelected()) {
            JTB_modeSelect.setText(Init.languageResourceBundle.getString("FileMode"));
            JTA_src.setEditable(false);
            try {
                File file_temp = ViewUtils.getFile();
                JTA_src.setText(file_temp.toString());
                file = FileUtils.getFilebyte(file_temp);
            } catch (Exception e) {
                e.printStackTrace();
                JTB_modeSelect.selectedProperty().setValue(false);
                JTB_modeSelect.setText(Init.languageResourceBundle.getString("TextMode"));
                JTA_src.setText("");
                JTA_src.setEditable(true);
            }
        } else {
            JTB_modeSelect.setText(Init.languageResourceBundle.getString("TextMode"));
            JTA_src.setText("");
            JTA_src.setEditable(true);
        }
    }

    public void FileEncodeend() {
        JTB_modeSelect.selectedProperty().set(false);
        JTB_modeSelect.setText(Init.languageResourceBundle.getString("TextMode"));
        JTA_src.setText("");
        JTA_src.setEditable(true);
    }
}

18 Source : URLController.java
with MIT License
from ffffffff0x

/**
 * @author RyuZU
 */
public clreplaced URLController extends ViewControllerObject {

    @FXML
    private JFXComboBox JCB_charset;

    @Override
    protected void initialize() {
        super.initialize();
        ViewInit.comboBoxCharset(JCB_charset);
        ViewInit.textAreaErrorInfoGeneral(JTA_dst);
    }

    @Override
    public void ONClickEncode() {
        super.ONClickEncode();
        try {
            JTA_dst.setText(Coding_URL.encode(JTA_src.getText(), JCB_charset.getValue().toString()));
        } catch (UnsupportedEncodingException e) {
            // e.printStackTrace();
            ViewUtils.textAreaValidate(JTA_dst);
        }
    }

    @Override
    public void ONClickDecode() {
        super.ONClickDecode();
        try {
            JTA_dst.setText(Coding_URL.decode(JTA_src.getText(), JCB_charset.getValue().toString()));
        } catch (UnsupportedEncodingException e) {
            // e.printStackTrace();
            ViewUtils.textAreaValidate(JTA_dst);
        }
    }
}

18 Source : HTMLCharEntityController.java
with MIT License
from ffffffff0x

/**
 * @author RyuZU
 */
public clreplaced HTMLCharEnreplacedyController extends ViewControllerObject {

    @FXML
    private JFXComboBox JCB_reference;

    @Override
    protected void initialize() {
        super.initialize();
        initComboBoxReference();
    }

    @Override
    public void ONClickEncode() {
        super.ONClickEncode();
        try {
            JTA_dst.setText(Coding_HTMLCharEnreplacedy.encode(JTA_src.getText(), JCB_reference.getValue().toString()));
        } catch (Exception e) {
            ViewUtils.textAreaValidate(JTA_dst);
        }
    }

    @Override
    public void ONClickDecode() {
        super.ONClickDecode();
        try {
            JTA_dst.setText(Coding_HTMLCharEnreplacedy.decode(JTA_src.getText(), JCB_reference.getValue().toString()));
        } catch (Exception e) {
            ViewUtils.textAreaValidate(JTA_dst);
        }
    }

    public void initComboBoxReference() {
        JCB_reference.gereplacedems().addAll("NCR: &#[dec];", "NCR: &#x[hex];", "CER: &[char];");
        JCB_reference.setValue("NCR: &#[dec];");
        JCB_reference.setVisibleRowCount(3);
    }
}

18 Source : BaseConversionController.java
with MIT License
from ffffffff0x

public clreplaced BaseConversionController extends ViewControllerObject {

    @FXML
    private JFXTextField JTF_split;

    @FXML
    private JFXComboBox<Integer> JCB_srcBase;

    @FXML
    private JFXComboBox<Integer> JCB_dstBase;

    @Override
    protected void initialize() {
        super.initialize();
        initComboBox();
    }

    @Override
    public void ONClickConfirm() {
        super.ONClickConfirm();
        try {
            JTA_dst.setText(Coding_BaseConversion.conversion(JTA_src.getText(), Integer.parseInt(JCB_srcBase.getValue().toString()), Integer.parseInt(JCB_dstBase.getValue().toString()), JTF_split.getText()));
        } catch (NumberFormatException e) {
            ViewUtils.textAreaValidate(JTA_dst);
        }
    }

    @FXML
    public void initComboBox() {
        JCB_srcBase.gereplacedems().add(2);
        JCB_srcBase.gereplacedems().add(8);
        JCB_srcBase.gereplacedems().add(10);
        JCB_srcBase.gereplacedems().add(16);
        for (int i = 3; i < 8; i++) {
            JCB_srcBase.gereplacedems().add(i);
        }
        for (int i = 9; i < 10; i++) {
            JCB_srcBase.gereplacedems().add(i);
        }
        for (int i = 11; i < 16; i++) {
            JCB_srcBase.gereplacedems().add(i);
        }
        for (int i = 17; i < 31; i++) {
            JCB_srcBase.gereplacedems().add(i);
        }
        JCB_srcBase.setValue(10);
        JCB_srcBase.setVisibleRowCount(6);
        JCB_dstBase.gereplacedems().add(2);
        JCB_dstBase.gereplacedems().add(8);
        JCB_dstBase.gereplacedems().add(10);
        JCB_dstBase.gereplacedems().add(16);
        for (int i = 3; i < 8; i++) {
            JCB_dstBase.gereplacedems().add(i);
        }
        for (int i = 9; i < 10; i++) {
            JCB_dstBase.gereplacedems().add(i);
        }
        for (int i = 11; i < 16; i++) {
            JCB_dstBase.gereplacedems().add(i);
        }
        for (int i = 17; i < 31; i++) {
            JCB_dstBase.gereplacedems().add(i);
        }
        JCB_dstBase.setValue(16);
        JCB_dstBase.setVisibleRowCount(6);
    }
}

18 Source : ROTController.java
with MIT License
from ffffffff0x

public clreplaced ROTController extends ViewControllerObject {

    @FXML
    private JFXComboBox JCB_rotNum;

    @Override
    protected void initialize() {
        super.initialize();
        initComboxSelect();
    }

    @Override
    public void ONReleasedOrSelected() {
        super.ONReleasedOrSelected();
        try {
            JTA_dst.setText(Clreplacedical_ROT.encode(JTA_src.getText(), JCB_rotNum.getValue().toString()));
        } catch (Exception e) {
            ViewUtils.textAreaValidate(JTA_dst);
        }
    }

    public void initComboxSelect() {
        JCB_rotNum.gereplacedems().addAll("ROT01", "ROT02", "ROT03", "ROT04", "ROT05", "ROT06", "ROT07", "ROT08", "ROT09", "ROT10", "ROT11", "ROT12", "ROT13", "ROT14", "ROT15", "ROT16", "ROT17", "ROT18", "ROT19", "ROT20", "ROT21", "ROT22", "ROT23", "ROT24", "ROT25");
        JCB_rotNum.setValue("ROT13");
        JCB_rotNum.setVisibleRowCount(6);
    }
}

17 Source : TopVehiclesUIController.java
with Apache License 2.0
from Shehanka

/**
 * @author chamodshehanka on 6/27/2018
 * @project RentLio
 */
public clreplaced TopVehiclesUIController implements Initializable {

    @FXML
    private PieChart topVehiclesChart;

    @FXML
    private JFXComboBox<Integer> chbxTest;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        setComboBoxValues();
    }

    @FXML
    private void setPieChartGraph() {
        Integer chartType = chbxTest.getValue();
        // switch by vehicle type
        switch(chartType) {
            case 1:
                ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList(new PieChart.Data("Prius", 13), new PieChart.Data("Audi A7", 25), new PieChart.Data("Audi R8", 10), new PieChart.Data("BMW i8", 22), new PieChart.Data("Premio", 30));
                topVehiclesChart.setData(pieChartData);
                topVehiclesChart.setreplacedle("Top Vehicles");
                break;
            case 2:
                pieChartData = FXCollections.observableArrayList(new PieChart.Data("Prius", 73), new PieChart.Data("Audi A7", 25), new PieChart.Data("Audi R8", 17), new PieChart.Data("BMW i8", 45), new PieChart.Data("Premio", 90));
                topVehiclesChart.setData(pieChartData);
                break;
            case 3:
                break;
            default:
                new AlertBuilder("warn", "Top Vehicles", "Top Vehicle Graph", "Invalid type of graph !!");
        }
    }

    private void getPieChartData() {
    }

    private void setComboBoxValues() {
        chbxTest.gereplacedems().addAll(1, 2, 3);
    }
}

17 Source : RequieredFieldsValidators.java
with Apache License 2.0
from LaynezCoder

public static void toJFXComboBox(JFXComboBox comboBox) {
    RequiredFieldValidator validator = new RequiredFieldValidator(MESSAGE);
    validator.setIcon(new FontAwesomeIconView(WARNING_ICON));
    comboBox.getValidators().add(validator);
    comboBox.focusedProperty().addListener((o, oldVal, newVal) -> {
        if (!newVal) {
            comboBox.validate();
        }
    });
}

17 Source : ComboBoxController.java
with GNU Lesser General Public License v3.0
from javafxchina

@ViewController(value = "/fxml/ui/Combobox.fxml", replacedle = "Material Design Example")
public clreplaced ComboBoxController {

    @FXML
    private JFXComboBox<Label> jfxComboBox;

    @FXML
    private JFXComboBox<Label> jfxEditableComboBox;

    /**
     * init fxml when loaded.
     */
    @PostConstruct
    public void init() {
        jfxComboBox.focusedProperty().addListener((o, oldVal, newVal) -> {
            if (!newVal) {
                ValidationFacade.validate(jfxComboBox);
            }
        });
        ChangeListener<? super Boolean> comboBoxFocus = (o, oldVal, newVal) -> {
            if (!newVal) {
                ValidationFacade.validate(jfxEditableComboBox);
            }
        };
        jfxEditableComboBox.focusedProperty().addListener(comboBoxFocus);
        jfxEditableComboBox.getEditor().focusedProperty().addListener(comboBoxFocus);
        jfxEditableComboBox.setConverter(new StringConverter<Label>() {

            @Override
            public String toString(Label object) {
                return object == null ? "" : object.getText();
            }

            @Override
            public Label fromString(String string) {
                return string == null || string.isEmpty() ? null : new Label(string);
            }
        });
    }
}

17 Source : MoneyConvertController.java
with MIT License
from ffffffff0x

/**
 * @author: RyuZUSUNC
 * @create: 2021-03-01 14:33
 */
public clreplaced MoneyConvertController extends ViewControllerObject {

    private final BigDecimal MAX_VALUE = new BigDecimal("9999999999999999.99");

    @FXML
    private JFXComboBox JCB_language;

    @Override
    protected void initialize() {
        super.initialize();
        initComboBox();
        JTA_src.setPromptText("MAX:9999999999999999.99");
    }

    @Override
    public void ONClickConfirm() {
        super.ONClickConfirm();
        try {
            if (MAX_VALUE.compareTo(new BigDecimal(JTA_src.getText())) == -1) {
                JTA_src.setText("");
                JTA_dst.setText(Init.languageResourceBundle.getString("ErrorMessage"));
            } else {
                JTA_dst.setText(Practical_MoneyConvert.convert(new BigDecimal(JTA_src.getText())));
            }
        } catch (Exception e) {
            ViewUtils.textAreaValidate(JTA_dst);
        }
    }

    private void initComboBox() {
        JCB_language.gereplacedems().addAll(Init.languageResourceBundle.getString("Chinese"));
        JCB_language.setValue(Init.languageResourceBundle.getString("Chinese"));
        JCB_language.setVisibleRowCount(6);
    }
}

16 Source : RestRequestEditController.java
with MIT License
from warmuuh

public clreplaced RestRequestEditController implements RequestTypeEditor, AutoCompletionAware {

    TextField requestUrl;

    JFXComboBox<String> httpMethod;

    private GenericBinding<RestRequestContainer, String> urlBinding = GenericBinding.of(RestRequestContainer::getUrl, RestRequestContainer::setUrl);

    private GenericBinding<RestRequestContainer, String> httpMethodBinding = GenericBinding.of(RestRequestContainer::getHttpMethod, RestRequestContainer::setHttpMethod);

    private AutoCompleter completer;

    @Override
    @SneakyThrows
    public Node getRoot() {
        Node root = new RestRequestEditControllerFxml(this);
        return root;
    }

    @Override
    public void displayRequest(RequestContainer request) {
        if (!(request instanceof RestRequestContainer))
            throw new IllegalArgumentException("Other request types not yet supported");
        RestRequestContainer restRequest = (RestRequestContainer) request;
        urlBinding.bindTo(requestUrl.textProperty(), restRequest);
        httpMethodBinding.bindTo(httpMethod.valueProperty(), restRequest);
        urlBinding.addListener(s -> request.setDirty(true));
        httpMethodBinding.addListener(s -> request.setDirty(true));
        // bind to param tab:
        request.onInvalidate.clear();
        // contract with query-param tab
        request.onInvalidate.add(() -> requestUrl.setText(restRequest.getUrl()));
        request.getAspect(RestQueryParamAspect.clreplaced).ifPresent(a -> {
            a.parseQueryParams(requestUrl.getText());
            a.linkToUrlTextfield(requestUrl.textProperty());
        });
        completer.attachVariableCompletionTo(requestUrl);
    }

    @Override
    public void setAutoCompleter(AutoCompleter completer) {
        this.completer = completer;
    }

    public static clreplaced RestRequestEditControllerFxml extends HboxExt {

        public RestRequestEditControllerFxml(RestRequestEditController controller) {
            HBox.setHgrow(this, Priority.ALWAYS);
            var methods = new JFXComboBox<String>();
            add(methods);
            methods.setId("httpMethods");
            controller.httpMethod = methods;
            methods.setValue("GET");
            methods.gereplacedems().add("GET");
            methods.gereplacedems().add("POST");
            methods.gereplacedems().add("PUT");
            methods.gereplacedems().add("DELETE");
            methods.gereplacedems().add("PATCH");
            methods.gereplacedems().add("HEAD");
            methods.gereplacedems().add("OPTIONS");
            controller.requestUrl = add(new LongTextField(), true);
            controller.requestUrl.setId("requestUrl");
        }
    }
}

16 Source : SelectValueDialog.java
with MIT License
from warmuuh

public clreplaced SelectValueDialog {

    private Dialog dialog;

    @Getter
    boolean cancelled = true;

    JFXComboBox<String> valueSelection;

    Label promptLabel;

    Label replacedle;

    public SelectValueDialog() {
    }

    public void showAndWait(String replacedle, String prompt, Optional<String> prefilledValue, List<String> values) {
        JFXDialogLayout content = new SelectValueDialogFxml(this);
        this.replacedle.setText(replacedle);
        promptLabel.setText(prompt);
        valueSelection.gereplacedems().addAll(values);
        prefilledValue.ifPresent(valueSelection::setValue);
        dialog = FxmlUtil.createDialog(content);
        dialog.showAndWait();
    }

    public String getInput() {
        return valueSelection.getValue();
    }

    private void onSave() {
        cancelled = false;
        dialog.close();
    }

    private void onCancel() {
        cancelled = true;
        dialog.close();
    }

    public static clreplaced SelectValueDialogFxml extends JFXDialogLayout {

        public SelectValueDialogFxml(SelectValueDialog controller) {
            setHeading(controller.replacedle = label("replacedle"));
            var vbox = new FxmlBuilder.VboxExt();
            controller.promptLabel = vbox.add(label(""));
            controller.valueSelection = vbox.add(new JFXComboBox<>());
            setBody(vbox);
            setActions(submit(controller::onSave), cancel(controller::onCancel));
        }
    }
}

16 Source : ImportDialog.java
with MIT License
from warmuuh

public clreplaced ImportDialog {

    VBox importerArea;

    JFXComboBox<ImporterPlugin> importerSelector;

    private Dialog dialog;

    private ImporterPlugin selectedImporter = null;

    private Toaster toaster;

    private Workspace workspace;

    public void showAndWait(List<ImporterPlugin> importers, Toaster toaster, Workspace workspace) {
        this.toaster = toaster;
        this.workspace = workspace;
        JFXDialogLayout content = new ImportDialogFxml(this);
        importerSelector.setPromptText("Select Importer");
        importers.forEach(i -> importerSelector.gereplacedems().add(i));
        importerSelector.setConverter(new StringConverter<ImporterPlugin>() {

            @Override
            public String toString(ImporterPlugin object) {
                return object.getName();
            }

            @Override
            public ImporterPlugin fromString(String string) {
                return null;
            }
        });
        importerSelector.getSelectionModel().selectedItemProperty().addListener((obs, o, v) -> {
            if (o != v && v != null) {
                selectedImporter = v;
                importerArea.getChildren().clear();
                importerArea.getChildren().add(v.getImportControls());
            }
        });
        dialog = FxmlUtil.createDialog(content);
        dialog.showAndWait();
    }

    public void onClose() {
        dialog.close();
    }

    public void onImport() {
        if (selectedImporter != null) {
            if (selectedImporter.importInto(workspace, toaster)) {
                dialog.close();
            }
        }
    }

    public clreplaced ImportDialogFxml extends JFXDialogLayout {

        public ImportDialogFxml(ImportDialog controller) {
            setHeading(label("Import"));
            var vbox = new FxmlBuilder.VboxExt();
            controller.importerSelector = vbox.add(new JFXComboBox());
            controller.importerArea = vbox.add(vbox("importerArea"));
            setBody(vbox);
            setActions(submit(controller::onImport, "Import"), cancel(controller::onClose, "Close"));
        }
    }
}

16 Source : SettingController.java
with GNU General Public License v3.0
from unclezs

/**
 * 设置控制器
 *
 * @author unclezs.com
 * @date 2019.07.07 11:52
 */
@FXController("setting")
@SuppressWarnings("unchecked")
public clreplaced SettingController implements LifeCycleFxController {

    private static final int MAX_THREAD_NUM = 50;

    private static final int MAX_DELAY_TIME = 1000;

    private static final int MAX_DELAY_TIME_PART = 130;

    public ToggleGroup saveTypeGroup, exitHandlerGroup;

    public JFXToggleButton merge, autoImport;

    public JFXComboBox<Integer> threadNum, delay;

    public JFXButton useProxy;

    public TextField proxyPort, proxyHost, savePathInput;

    public TableView<SearchTextRule> textTable;

    public TableView<SearchAudioRule> audioTable;

    public TableColumn<SearchTextRule, Button> deleteTextRule;

    public TableColumn<SearchAudioRule, Button> audioDeleteTextRule;

    public TabPane root;

    public JFXComboBox<LanguageLocale> language;

    @Override
    public void initialize() {
        initData();
        initEventHandler();
    }

    @Override
    public void onHidden() {
        ApplicationUtil.storeConfig();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        for (int i = 0; i < MAX_DELAY_TIME_PART; i++) {
            delay.gereplacedems().add(i);
        }
        for (int i = MAX_DELAY_TIME_PART; i < MAX_DELAY_TIME; i += 5) {
            delay.gereplacedems().add(i);
        }
        for (int i = 1; i < MAX_THREAD_NUM; i++) {
            threadNum.gereplacedems().add(i);
        }
        merge.selectedProperty().bindBidirectional(DataManager.application.getSetting().getMergeFile());
        savePathInput.textProperty().bindBidirectional(DataManager.application.getSetting().getSavePath());
        saveTypeGroup.selectToggle(saveTypeGroup.getToggles().get(DataManager.application.getSetting().getSaveType()));
        autoImport.selectedProperty().bindBidirectional(DataManager.application.getSetting().getAutoImportClipboardLink());
        exitHandlerGroup.selectToggle(exitHandlerGroup.getToggles().get(DataManager.application.getSetting().getExitHandler().get()));
        proxyHost.textProperty().bindBidirectional(DataManager.application.getSetting().getProxyHost());
        proxyPort.textProperty().bindBidirectional(DataManager.application.getSetting().getProxyPort());
        useProxy(DataManager.application.getSetting().getUseProxy().get());
        threadNum.valueProperty().addListener(e -> DataManager.application.getSetting().getThreadNum().set(threadNum.getValue()));
        threadNum.valueProperty().bindBidirectional(DataManager.application.getSetting().getThreadNum().asObject());
        delay.valueProperty().addListener(e -> DataManager.application.getSetting().getDelay().set(delay.getValue()));
        delay.valueProperty().bindBidirectional(DataManager.application.getSetting().getDelay().asObject());
        language.valueProperty().bindBidirectional(DataManager.application.getSetting().getLanguage());
        initTable();
    }

    /**
     * 初始话规则表格数据
     */
    private void initTable() {
        // 文本小说
        initTable(textTable, SearchTextRule.clreplaced, SearchTextRuleMapper.clreplaced, deleteTextRule);
        // 有声小说
        initTable(audioTable, SearchAudioRule.clreplaced, SearchAudioRuleMapper.clreplaced, audioDeleteTextRule);
        ThreadUtil.execute(() -> {
            textTable.sereplacedems(DataManager.application.getTextRules());
            audioTable.sereplacedems(DataManager.application.getAudioRules());
        });
    }

    /**
     * 绑定列
     *
     * @param column    列
     * @param colName   列名
     * @param converter 类型转换器
     * @param consumer  编辑提交事件处理
     * @param <T>       /
     * @param <R>       /
     */
    private <T, R> void setCellFactory(TableColumn<T, R> column, String colName, StringConverter<R> converter, Consumer<TableColumn.CellEditEvent<T, R>> consumer) {
        column.setCellValueFactory(new PropertyValueFactory<>(colName));
        column.setCellFactory(TextFieldTableCell.forTableColumn(converter));
        column.setOnEditCommit(consumer::accept);
    }

    /**
     * 绑定表格数据
     *
     * @param dataClazz  绑定行的数据类
     * @param table      表格数据
     * @param baseMapper 操作数据得mapper
     * @param opCol      操作列
     */
    private <T> void initTable(TableView<T> table, Clreplaced<T> dataClazz, Clreplaced<? extends BaseMapper<T>> baseMapper, TableColumn<T, Button> opCol) {
        Field[] fields = dataClazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String colName = field.getName();
            TableColumn<T, ?> column = table.getColumns().stream().filter(col -> (opCol != col) && col.getUserData().equals(colName)).findFirst().orElse(null);
            StringConverter converter = new StringConverter() {

                @Override
                public String toString(Object object) {
                    return Convert.toStr(object);
                }

                @Override
                public Object fromString(String string) {
                    return Convert.convert(field.getType(), string);
                }
            };
            if (column != null) {
                setCellFactory(column, colName, converter, e -> {
                    try {
                        field.set(e.getRowValue(), e.getNewValue());
                        MybatisUtil.execute(baseMapper, mapper -> mapper.updateById(e.getRowValue()));
                    } catch (IllegalAccessException ex) {
                        ex.printStackTrace();
                    }
                });
            }
        }
        opCol.setCellValueFactory(param -> createDelBtn(() -> {
            table.gereplacedems().remove(param.getValue());
            MybatisUtil.execute(baseMapper, mapper -> mapper.deleteById(((Rule) param.getValue()).getSite()));
            ToastUtil.success("删除成功");
        }));
        table.prefWidthProperty().bind(root.widthProperty());
    }

    /**
     * 创建删除按钮
     *
     * @param clickHandler 这一行的数据
     * @return /
     */
    private SimpleObjectProperty<Button> createDelBtn(Runnable clickHandler) {
        Glyph graphic = new Glyph("FontAwesome", "\uf057");
        Button delBtn = new Button(ResourceUtil.getString("delete"), graphic);
        delBtn.getStyleClreplaced().addAll("del-btn");
        delBtn.setOnMouseClicked(e -> {
            AlertUtil.confirm("确认删除嘛?", res -> {
                if (res) {
                    clickHandler.run();
                }
            });
        });
        return new SimpleObjectProperty<>(delBtn);
    }

    /**
     * 改变保存文件夹
     */
    @FXML
    public void changeSavePath() {
        // 文件选择
        DirectoryChooser chooser = new DirectoryChooser();
        File dir = new File(DataManager.application.getSetting().getSavePath().get());
        if (dir.exists()) {
            chooser.setInitialDirectory(dir);
        }
        chooser.setreplacedle("选择下载位置");
        File file = chooser.showDialog(DataManager.currentStage);
        if (file != null && file.exists()) {
            savePathInput.setText(FileUtil.getPath(file));
        }
    }

    /**
     * 打开保存文件夹
     */
    @FXML
    public void openSavePath() {
        File dir = new File(DataManager.application.getSetting().getSavePath().get());
        if (dir.exists()) {
            DesktopUtil.openDir(dir);
        } else {
            DesktopUtil.openDir(new File("/"));
        }
    }

    /**
     * 初始化事件监听
     */
    private void initEventHandler() {
        saveTypeGroup.selectedToggleProperty().addListener(l -> DataManager.application.getSetting().getTextNovelSaveType().set(((JFXRadioButton) saveTypeGroup.getSelectedToggle()).getText()));
        exitHandlerGroup.selectedToggleProperty().addListener(l -> DataManager.application.getSetting().getExitHandler().set(exitHandlerGroup.getToggles().indexOf(exitHandlerGroup.getSelectedToggle())));
        useProxy.setOnMouseClicked(e -> {
            boolean userProxy = !DataManager.application.getSetting().getUseProxy().get();
            DataManager.application.getSetting().getUseProxy().set(userProxy);
            useProxy(userProxy);
        });
        language.valueProperty().addListener(e -> ToastUtil.success(ResourceUtil.getString("update_success")));
    }

    /**
     * 应用代理
     *
     * @param useProxy 是否使用
     */
    private void useProxy(boolean useProxy) {
        Setting setting = DataManager.application.getSetting();
        if (useProxy) {
            if (StrUtil.isNotEmpty(setting.getProxyHost().get()) && StrUtil.isNotEmpty(setting.getProxyPort().get())) {
                System.setProperty("proxyHost", setting.getProxyHost().get());
                System.setProperty("proxyPort", setting.getProxyPort().get());
            }
            this.useProxy.setText(ResourceUtil.getString("disable"));
        } else {
            System.setProperty("proxyHost", "");
            System.setProperty("proxyPort", "");
            this.useProxy.setText(ResourceUtil.getString("enabled"));
        }
    }

    /**
     * 到出有声规则
     */
    @FXML
    public void exportAudioRule() {
        exportRuleJson(false);
    }

    /**
     * 导出文本规则
     */
    @FXML
    public void exportTextRule() {
        exportRuleJson(true);
    }

    /**
     * 导入有声规则
     */
    @FXML
    public void importAudioRule() {
        importRuleJson(false);
    }

    /**
     * 导入文本规则
     */
    @FXML
    public void importTextRule() {
        importRuleJson(true);
    }

    /**
     * 导入解析配置
     *
     * @param isText 是否为文本小说
     */
    private void importRuleJson(boolean isText) {
        FileChooser fileChooser = new FileChooser();
        FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("JSON", "*.json");
        fileChooser.getExtensionFilters().add(filter);
        File file = fileChooser.showOpenDialog(DataManager.currentStage);
        if (file != null && file.exists()) {
            boolean accept = cn.hutool.core.io.FileUtil.pathEndsWith(file, "json");
            if (accept) {
                try {
                    AbstractLoadingTask saveTask;
                    if (isText) {
                        List<SearchTextRule> rules = JSON.parseArray(cn.hutool.core.io.FileUtil.readUtf8String(file), SearchTextRule.clreplaced);
                        List<SearchTextRule> collect = rules.stream().filter(rule -> {
                            for (SearchTextRule item : textTable.gereplacedems()) {
                                if (item.getSite().equals(rule.getSite())) {
                                    return false;
                                }
                            }
                            return true;
                        }).collect(Collectors.toList());
                        textTable.gereplacedems().addAll(collect);
                        saveTask = new AbstractLoadingTask() {

                            @Override
                            protected Object call() {
                                for (SearchTextRule rule : collect) {
                                    MybatisUtil.execute(SearchTextRuleMapper.clreplaced, mapper -> mapper.insert(rule));
                                }
                                return null;
                            }
                        };
                    } else {
                        List<SearchAudioRule> rules = JSON.parseArray(cn.hutool.core.io.FileUtil.readUtf8String(file), SearchAudioRule.clreplaced);
                        List<SearchAudioRule> collect = rules.stream().filter(rule -> {
                            for (SearchAudioRule item : audioTable.gereplacedems()) {
                                if (item.getSite().equals(rule.getSite())) {
                                    return false;
                                }
                            }
                            return true;
                        }).collect(Collectors.toList());
                        audioTable.gereplacedems().addAll(collect);
                        saveTask = new AbstractLoadingTask() {

                            @Override
                            protected Object call() {
                                for (SearchAudioRule rule : collect) {
                                    MybatisUtil.execute(SearchAudioRuleMapper.clreplaced, mapper -> mapper.insert(rule));
                                }
                                return null;
                            }
                        };
                    }
                    saveTask.setSuccessHandler(e -> ToastUtil.success(ResourceUtil.getString("import_success")));
                    ThreadUtil.execute(saveTask);
                } catch (JSONException exception) {
                    ToastUtil.error("导入失败,请确认为JSON格式");
                }
            }
        }
    }

    private void exportRuleJson(boolean isText) {
        FileChooser fileChooser = new FileChooser();
        String fileName = isText ? "文本小说规则.json" : "有声小说规则.json";
        fileChooser.setInitialFileName(fileName);
        File file = fileChooser.showSaveDialog(DataManager.currentStage);
        if (file != null) {
            cn.hutool.core.io.FileUtil.writeUtf8String(JSON.toJSONString(isText ? textTable.gereplacedems() : audioTable.gereplacedems()), file);
            ToastUtil.success("导出成功");
        }
    }

    /**
     * 测试代理
     */
    public void testProxy() {
        AbstractLoadingTask<String> task = new AbstractLoadingTask<String>() {

            @Override
            protected String call() throws IOException {
                Doreplacedent doc = RequestUtil.doc("http://www.cip.cc/");
                return doc.select(".kq-well").first().text();
            }
        };
        ThreadUtil.execute(task);
        task.setSuccessHandler(es -> {
            if (task.getValue() == null) {
                ToastUtil.error("代理无效");
            } else {
                AlertUtil.alert("代理信息", task.getValue());
            }
        });
    }
}

16 Source : ServiceInputLuggageViewController.java
with MIT License
from ThijsZijdel

// Method that loops through all the fields checking whether the ones that are not allowed to be empty aren't
public boolean checkFields() {
    boolean appropriate = true;
    // Date picker and timepicker cannot be looped through since theyre not inside an array
    // Check whether the date field has been filled in appropriately
    // Get the date, if its empty let the user know it has to be filled
    if (dateJFXDatePicker.getValue() == null || dateJFXDatePicker.getValue().toString().isEmpty()) {
        dateJFXDatePicker.setStyle("-fx-background-color: #f47142");
        appropriate = false;
    } else {
        dateJFXDatePicker.setStyle(null);
    }
    // Get the time, if its empty let the user know it has to be filled
    if (timeJFXTimePicker.getValue() == null || timeJFXTimePicker.getValue().toString().isEmpty()) {
        timeJFXTimePicker.setStyle("-fx-background-color: #f47142");
        appropriate = false;
    } else {
        timeJFXTimePicker.setStyle(null);
    }
    // Loop through the comboboxes
    for (Map.Entry<String, JFXComboBox> entry : comboBoxes.entrySet()) {
        String key = entry.getKey();
        JFXComboBox value = entry.getValue();
        // first check for the comboboxes that have to be selected in both forms
        if (key.equals("color") || key.equals("type") || key.equals("airport") || key.equals("flight")) {
            if (value.getValue() == null || value.getValue().toString().isEmpty()) {
                value.setStyle("-fx-background-color: #f47142");
                appropriate = false;
            } else {
                value.setStyle(null);
            }
        }
        // check the comboboxes for the lost form, in this case only the destination is an additional combobox
        // where an option has to be selected
        if (form.getType().equals("Lost") && key.equals("destination")) {
            if (value.getValue() == null || value.getValue().toString().isEmpty()) {
                value.setStyle("-fx-background-color: #f47142");
                appropriate = false;
            } else {
                value.setStyle(null);
            }
        }
    }
    // loop through the textfields
    for (Map.Entry<String, JFXTextField> entry : textFields.entrySet()) {
        String key = entry.getKey();
        JFXTextField value = entry.getValue();
        // If its a lost form, the following fields cannot be empty
        if (form.getType().equals("Lost")) {
            if (key.equals("name") || key.equals("address") || key.equals("place") || key.equals("postalcode") || key.equals("country") || key.equals("phone") || key.equals("email")) {
                if (value.getText() == null || value.getText().isEmpty()) {
                    value.setStyle("-fx-background-color: #f47142");
                    appropriate = false;
                } else {
                    value.setStyle(null);
                }
            }
        }
    }
    return appropriate;
}

16 Source : ServiceConfirmedMatchLuggageViewController.java
with MIT License
from ThijsZijdel

/**
 * FXML Controller clreplaced
 *
 * @author Thijs Zijdel - 500782165
 */
public clreplaced ServiceConfirmedMatchLuggageViewController implements Initializable, FoundLuggageFields, LostLuggageFields {

    // al the lost fields
    @FXML
    private JFXTextField registrationNr;

    @FXML
    private JFXTextField luggageTag;

    @FXML
    private JFXTextField type;

    @FXML
    private JFXTextField brand;

    @FXML
    private JFXTextField mainColor;

    @FXML
    private JFXTextField secondColor;

    @FXML
    private JFXTextField size;

    @FXML
    private JFXTextField weight;

    @FXML
    private JFXTextArea signatures;

    @FXML
    private JFXTextField preplacedangerId;

    @FXML
    private JFXTextField preplacedangerName;

    @FXML
    private JFXTextField address;

    @FXML
    private JFXTextField place;

    @FXML
    private JFXTextField postalCode;

    @FXML
    private JFXTextField country;

    @FXML
    private JFXTextField email;

    @FXML
    private JFXTextField phone;

    @FXML
    private JFXTextField timeLost;

    @FXML
    private JFXTextField dateLost;

    @FXML
    private JFXTextField flight;

    // Al the found fields
    // Note: 1 -> so they are alternated
    @FXML
    private JFXTextField registrationNr1;

    @FXML
    private JFXTextField luggageTag1;

    @FXML
    private JFXTextField type1;

    @FXML
    private JFXTextField brand1;

    @FXML
    private JFXTextField mainColor1;

    @FXML
    private JFXTextField secondColor1;

    @FXML
    private JFXTextField size1;

    @FXML
    private JFXTextField weight1;

    @FXML
    private JFXTextArea signatures1;

    @FXML
    private JFXTextField preplacedangerId1;

    @FXML
    private JFXTextField preplacedangerName1;

    @FXML
    private JFXTextField address1;

    @FXML
    private JFXTextField place1;

    @FXML
    private JFXTextField postalCode1;

    @FXML
    private JFXTextField country1;

    @FXML
    private JFXTextField email1;

    @FXML
    private JFXTextField phone1;

    @FXML
    private JFXTextField timeFound;

    @FXML
    private JFXTextField dateFound;

    @FXML
    private JFXTextField locationFound;

    @FXML
    private JFXTextField flight1;

    // Detail fields
    @FXML
    private JFXTextField detailsMatcheId;

    @FXML
    private JFXTextField detailsName;

    @FXML
    private JFXTextField detailsPhone;

    @FXML
    private JFXTextField detailsEmail;

    @FXML
    private JFXTextField detailsAddress;

    @FXML
    private JFXTextField detailsPlace;

    @FXML
    private JFXTextField detailsCode;

    @FXML
    private JFXTextField detailsCountry;

    @FXML
    private JFXComboBox detailsDeliverer;

    // getting the main language of the application
    private final String LANGUAGE = MainApp.getLanguage();

    // page replacedle
    private final String replacedLE = "Matched luggage";

    private final String replacedLE_DUTCH = "Overeenkomende bagage";

    // conection to the main database
    private final MyJDBC DB = MainApp.getDatabase();

    // current date
    private String currentDate;

    // the match id that will be generated and asigned
    private int matcheID;

    /**
     * Initializes the controller clreplaced that adds all the needed functionality,
     * to the: ServiceConfirmedMatchLuggageView.FXML view.
     *
     * @param url location  used to resolve relative paths for the root object
     * @param rb resources   used to localize the root object
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // Try to set the replacedle of the page
        try {
            if (MainApp.language.equals("dutch")) {
                MainViewController.getInstance().getreplacedle(replacedLE_DUTCH);
            } else {
                MainViewController.getInstance().getreplacedle(replacedLE);
            }
        } catch (IOException ex) {
            Logger.getLogger(ServiceMatchingViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        // getting the current data
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        LocalDate localDate = LocalDate.now();
        currentDate = dtf.format(localDate);
        // try to load initialize and set methodes
        try {
            setLostFields(getManualLostLuggageResultSet());
            setFoundFields(getManualFoundLuggageResultSet());
            generateMatcheId();
            setDetails();
            setMatched();
        } catch (SQLException ex) {
            Logger.getLogger(ServiceConfirmedMatchLuggageViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Here will the matcheId be generated
     * Note: the checking will also be done here
     *
     * @throws SQLException     getting a resultSet from the db
     * @void no direct output
     */
    private void generateMatcheId() throws SQLException {
        ResultSet resultSet = DB.executeResultSetQuery("SELECT COUNT(*) AS 'count' FROM matched;");
        while (resultSet.next()) {
            // get the amount of matches in the db
            int count = resultSet.getInt("count");
            // expect that the matcheId's are: 0,1,2,3.. etc.
            // So replacedign to the matcheID the amount of matches + 1
            matcheID = count++;
        }
        // check the matche id at least one time
        do {
            matcheID++;
        // if the return (of the check) is not true
        // add 1 to the matcheId and check it again
        } while (!checkMatcheId());
    }

    /**
     * Here will be checked if the (semi) generated matcheId already exists
     *
     * @throws SQLException     getting a resultSet from the db
     * @return boolean          if the match id already exist
     */
    private boolean checkMatcheId() throws SQLException {
        // i would have prevered this query in a different place..
        ResultSet resultSetCheck = DB.executeResultSetQuery("" + "SELECT COUNT(*) AS 'check' " + "FROM matched WHERE matchedid = '" + matcheID + "';");
        // loop trough the resultset
        while (resultSetCheck.next()) {
            int check = resultSetCheck.getInt("check");
            // if the check does not exists, return true
            // The count of exsiting matches with the same id is than zero
            return check == 0;
        }
        // if there wasn't any resultset return false
        return false;
    }

    /**
     * Here will all the detail fields be set
     * Note: the preplacedenger data from the lost luggage is used
     *
     * @void   no direct output
     */
    private void setDetails() {
        detailsName.setText(preplacedangerName.getText());
        detailsPhone.setText(phone.getText());
        detailsEmail.setText(email.getText());
        detailsAddress.setText(address.getText());
        detailsPlace.setText(place.getText());
        detailsCode.setText(postalCode.getText());
        detailsCountry.setText(country.getText());
        detailsMatcheId.setText(Integer.toString(matcheID));
        // list of deliverers (can be changed to a table in the db)
        ObservableList<String> deliverers = FXCollections.observableArrayList();
        deliverers.add("DHL");
        deliverers.add("Post NL");
        deliverers.add("Correndon");
        deliverers.add("Self service");
        // add the deliverers to the combo box
        detailsDeliverer.gereplacedems().addAll(deliverers);
    }

    /**
     * Here will the lost and found luggage be added to the matched table
     * And the id will also be set in the lost & found tables
     *
     * @throws SQLException     updating data in the db
     * @void   no direct output
     */
    private void setMatched() throws SQLException {
        // get the right values to set in the DB
        String matchIDstring = Integer.toString(matcheID);
        String idLostLuggage = registrationNr.getText();
        String idFoundLuggage = registrationNr1.getText();
        // check if an user is logged in
        if (MainApp.currentUser.getId() != null) {
            // insert the match in the matched table with the right data
            // note: choosen for a prepared statement (no user input involved)
            // generated id
            DB.executeInsertMatchQuery(// generated id
            matchIDstring, // found id
            idFoundLuggage, // lost id
            idLostLuggage, // employee
            MainApp.currentUser.getId(), // current date
            currentDate);
            // update the lost luggage item with the right matcheId
            DB.executeUpdateLuggageFieldQuery("lostluggage", "matchedId", matchIDstring, idLostLuggage);
            // update the found luggage item with the right matcheId
            DB.executeUpdateLuggageFieldQuery("foundluggage", "matchedId", matchIDstring, idFoundLuggage);
        } else {
            System.out.println("No user logged in.");
        }
    }

    /**
     * Here will the the deliverer be updated in the table on the current id
     *
     * @throws SQLException     updating (setting) data in the db
     * @void   no direct output
     */
    @FXML
    protected void confirmDeliverer() throws SQLException {
        // check if an user is logged in
        if (MainApp.currentUser.getId() != null) {
            // using a prepared statment to set the deliverer
            DB.executeUpdateQueryWhere(// table
            "matched", // field
            "delivery", // where
            "matchedId", // value (deliverer)
            detailsDeliverer.getValue().toString(), // id of match
            Integer.toString(matcheID));
        } else {
            System.out.println("No user logged in.");
        }
    }

    /**
     * Here will the resultSet of the lost manual matching luggage be get
     * For getting the right resultSet the correct instance id will be preplaceded
     *
     * @return resultSet     resultSet for the right luggage
     */
    @Override
    public ResultSet getManualLostLuggageResultSet() throws SQLException {
        String id = LostLuggageManualMatchingInstance.getInstance().currentLuggage().getRegistrationNr();
        ServiceDataLost detailsItem = new ServiceDataLost();
        ResultSet resultSet = detailsItem.getAllDetailsLost(id);
        return resultSet;
    }

    /**
     * Here are all the detail fields been set with the right data from:
     * The resultSet given
     *
     * @param resultSet         this will be converted to temp strings and integers
     * @void no direct          the fields will be set within this method
     */
    @FXML
    @Override
    public void setLostFields(ResultSet resultSet) throws SQLException {
        // loop trough all the luggages in the resultSet
        // Note: there will be only one
        while (resultSet.next()) {
            int getRegistrationNr = resultSet.getInt("F.registrationNr");
            String getDateLost = resultSet.getString("F.dateLost");
            String getTimeLost = resultSet.getString("F.timeLost");
            String getLuggageTag = resultSet.getString("F.luggageTag");
            String getLuggageType = resultSet.getString("T." + LANGUAGE + "");
            String getBrand = resultSet.getString("F.brand");
            String getMainColor = resultSet.getString("c1." + LANGUAGE + "");
            String getSecondColor = resultSet.getString("c2." + LANGUAGE + "");
            String getSize = resultSet.getString("F.size");
            String getWeight = resultSet.getString("F.weight");
            String getOtherCharacteristics = resultSet.getString("F.otherCharacteristics");
            int getPreplacedengerId = resultSet.getInt("F.preplacedengerId");
            String getName = resultSet.getString("P.name");
            String getAddress = resultSet.getString("P.address");
            String getPlace = resultSet.getString("P.place");
            String getPostalcode = resultSet.getString("P.postalcode");
            String getCountry = resultSet.getString("P.country");
            String getEmail = resultSet.getString("P.email");
            String getPhone = resultSet.getString("P.phone");
            String getFlight = resultSet.getString("F.Flight");
            // set al the fields
            registrationNr.setText(Integer.toString(getRegistrationNr));
            luggageTag.setText(getLuggageTag);
            type.setText(getLuggageType);
            brand.setText(getBrand);
            mainColor.setText(getMainColor);
            secondColor.setText(getSecondColor);
            size.setText(getSize);
            weight.setText(getWeight);
            signatures.setText(getOtherCharacteristics);
            preplacedangerId.setText(Integer.toString(getPreplacedengerId));
            preplacedangerName.setText(getName);
            address.setText(getAddress);
            place.setText(getPlace);
            postalCode.setText(getPostalcode);
            country.setText(getCountry);
            email.setText(getEmail);
            phone.setText(getPhone);
            // locationFound.setText(getLocationFound);
            dateLost.setText(getDateLost);
            timeLost.setText(getTimeLost);
            flight.setText(getFlight);
        }
    }

    /**
     * Here will the resultSet of the found manual matching luggage be get
     * For getting the right resultSet the correct instance id will be preplaceded
     *
     * @return resultSet     resultSet for the right luggage
     */
    @Override
    public ResultSet getManualFoundLuggageResultSet() throws SQLException {
        String id = FoundLuggageManualMatchingInstance.getInstance().currentLuggage().getRegistrationNr();
        ServiceDataFound detailsItem = new ServiceDataFound();
        ResultSet resultSet = detailsItem.getAllDetailsFound(id);
        return resultSet;
    }

    /**
     * Here are all the detail fields been set with the right data from:
     * The resultSet given
     *
     * @param resultSet         this will be converted to temp strings and integers
     * @void no direct          the fields will be set within this method
     */
    @FXML
    @Override
    public void setFoundFields(ResultSet resultSet) throws SQLException {
        // loop trough all the luggages in the resultSet
        // Note: there will be only one
        while (resultSet.next()) {
            int getRegistrationNr = resultSet.getInt("F.registrationNr");
            String getDateFound = resultSet.getString("F.dateFound");
            String getTimeFound = resultSet.getString("F.timeFound");
            String getLuggageTag = resultSet.getString("F.luggageTag");
            String getLuggageType = resultSet.getString("T." + LANGUAGE + "");
            String getBrand = resultSet.getString("F.brand");
            String getMainColor = resultSet.getString("c1." + LANGUAGE + "");
            String getSecondColor = resultSet.getString("c2." + LANGUAGE + "");
            String getSize = resultSet.getString("F.size");
            String getWeight = resultSet.getString("F.weight");
            String getOtherCharacteristics = resultSet.getString("F.otherCharacteristics");
            String getPreplacedengerId = resultSet.getString("F.preplacedengerId");
            String getName = resultSet.getString("P.name");
            String getAddress = resultSet.getString("P.address");
            String getPlace = resultSet.getString("P.place");
            String getPostalcode = resultSet.getString("P.postalcode");
            String getCountry = resultSet.getString("P.country");
            String getEmail = resultSet.getString("P.email");
            String getPhone = resultSet.getString("P.phone");
            String getFlight = resultSet.getString("F.arrivedWithFlight");
            String getLocationFound = resultSet.getString("L." + LANGUAGE + "");
            // set al the fields
            registrationNr1.setText(Integer.toString(getRegistrationNr));
            luggageTag1.setText(getLuggageTag);
            type1.setText(getLuggageType);
            brand1.setText(getBrand);
            mainColor1.setText(getMainColor);
            secondColor1.setText(getSecondColor);
            size1.setText(getSize);
            weight1.setText(getWeight);
            signatures1.setText(getOtherCharacteristics);
            preplacedangerId1.setText(getPreplacedengerId);
            preplacedangerName1.setText(getName);
            address1.setText(getAddress);
            place1.setText(getPlace);
            postalCode1.setText(getPostalcode);
            country1.setText(getCountry);
            email1.setText(getEmail);
            phone1.setText(getPhone);
            locationFound.setText(getLocationFound);
            dateFound.setText(getDateFound);
            timeFound.setText(getTimeFound);
            flight1.setText(getFlight);
        }
    }

    /**
     * When the 'manual match ' button is clicked the instances will be set
     * And the stage will be closed
     *
     * @param event             when the button is clicked
     * @throws java.io.IOException  possible switching views
     */
    @FXML
    protected void manualMatching(ActionEvent event) throws IOException {
        // if the user is not on the matching view, switch to that view
        if (ServiceHomeViewController.isOnMatchingView() == false) {
            MainApp.switchView("/Views/Service/ServiceMatchingView.fxml");
        }
        // initialize the instances with the right luggage
        FoundLuggage preplacedFoundLuggage = FoundLuggageDetailsInstance.getInstance().currentLuggage();
        FoundLuggageManualMatchingInstance.getInstance().currentLuggage().setRegistrationNr(preplacedFoundLuggage.getRegistrationNr());
        LostLuggage preplacedLostLuggage = LostLuggageDetailsInstance.getInstance().currentLuggage();
        LostLuggageManualMatchingInstance.getInstance().currentLuggage().setRegistrationNr(preplacedLostLuggage.getRegistrationNr());
        // close this stage
        closeStage();
    }

    @FXML
    public void openEditViewLost() throws IOException {
        MainApp.switchView("/Views/Service/ServiceEditLostLuggageView.fxml");
        closeStage();
    }

    @FXML
    public void openEditViewFound() throws IOException {
        MainApp.switchView("/Views/Service/ServiceEditFoundLuggageView.fxml");
        closeStage();
    }

    @FXML
    public void contactedPreplacedenger() {
    // set switch before this   DISABLED
    }

    /**
     * Close the current stage by getting the window of a fields scene's
     * And casting this to a stage, and close this stage
     */
    public void closeStage() {
        Stage stage = (Stage) registrationNr.getScene().getWindow();
        stage.close();
    }
}

16 Source : AnimationDemo.java
with MIT License
from schlegel11

private Group createBody(ObservableMap<String, Timeline> animations) {
    JFXComboBox<String> comboBox = createBodyComboBox(animationName -> animations.get(animationName).play());
    comboBox.gereplacedems().addAll(animations.keySet());
    animations.addListener((MapChangeListener<? super String, ? super Timeline>) change -> {
        if (change.wasAdded()) {
            comboBox.gereplacedems().add(change.getKey());
        }
    });
    comboBox.getSelectionModel().selectFirst();
    JFXButton button = createBodyButton(() -> animations.get(comboBox.getSelectionModel().getSelectedItem()).play());
    HBox hBox = new HBox(comboBox, button);
    hBox.setAlignment(Pos.BOTTOM_CENTER);
    hBox.setSpacing(23);
    return new Group(hBox);
}

16 Source : AddBuild_Controller.java
with MIT License
from karakasis

/**
 * FXML Controller clreplaced
 *
 * @author Christos
 */
public clreplaced AddBuild_Controller implements Initializable {

    @FXML
    JFXTextField buildName;

    @FXML
    JFXComboBox select;

    @FXML
    JFXComboBox selectAsc;

    @FXML
    JFXButton addButton;

    JFXDialog parentDialog;

    int selectedClreplacedIndex;

    String build;

    String clreplacedName;

    String ascendancy;

    private BuildsPanel_Controller root;

    private MainApp_Controller closer;

    /**
     * Initializes the controller clreplaced.
     */
    public void hook(BuildsPanel_Controller root, MainApp_Controller closer) {
        this.closer = closer;
        this.root = root;
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        /*
        Marauder
        Ranger
        Witch
        Duelist
        Templar
        Shadow
        Scion
        */
        addButton.setDisable(true);
        select.gereplacedems().add("Marauder");
        select.gereplacedems().add("Ranger");
        select.gereplacedems().add("Witch");
        select.gereplacedems().add("Duelist");
        select.gereplacedems().add("Templar");
        select.gereplacedems().add("Shadow");
        select.gereplacedems().add("Scion");
        buildName.textProperty().addListener((observable, oldValue, newValue) -> {
            addButton.setDisable(true);
            if (!buildName.getText().equals("")) {
                if (select.getSelectionModel().getSelectedIndex() != -1) {
                    if (selectAsc.getSelectionModel().getSelectedIndex() != -1) {
                        addButton.setDisable(false);
                    }
                }
            }
        });
    }

    @FXML
    private void handleButtonAction(ActionEvent event) {
        // when user presses add. Callback to MainApp_Controller.
        root.addNewBuild(buildName.getText(), clreplacedName, ascendancy);
        closer.closePopup();
    }

    @FXML
    private void clreplacedChanged(ActionEvent event) {
        selectedClreplacedIndex = select.getSelectionModel().getSelectedIndex();
        if (selectedClreplacedIndex == 0) {
            clreplacedName = "Marauder";
            selectAsc.gereplacedems().clear();
            selectAsc.gereplacedems().add("Juggernaut");
            selectAsc.gereplacedems().add("Berserker");
            selectAsc.gereplacedems().add("Chieftain");
        } else if (selectedClreplacedIndex == 1) {
            clreplacedName = "Ranger";
            selectAsc.gereplacedems().clear();
            selectAsc.gereplacedems().add("Deadeye");
            selectAsc.gereplacedems().add("Raider");
            selectAsc.gereplacedems().add("Pathfinder");
        } else if (selectedClreplacedIndex == 2) {
            clreplacedName = "Witch";
            selectAsc.gereplacedems().clear();
            selectAsc.gereplacedems().add("Necromancer");
            selectAsc.gereplacedems().add("Occultist");
            selectAsc.gereplacedems().add("Elementalist");
        } else if (selectedClreplacedIndex == 3) {
            clreplacedName = "Duelist";
            selectAsc.gereplacedems().clear();
            selectAsc.gereplacedems().add("Slayer");
            selectAsc.gereplacedems().add("Gladiator");
            selectAsc.gereplacedems().add("Champion");
        } else if (selectedClreplacedIndex == 4) {
            clreplacedName = "Templar";
            selectAsc.gereplacedems().clear();
            selectAsc.gereplacedems().add("Inquisitor");
            selectAsc.gereplacedems().add("Hierophant");
            selectAsc.gereplacedems().add("Guardian");
        } else if (selectedClreplacedIndex == 5) {
            clreplacedName = "Shadow";
            selectAsc.gereplacedems().clear();
            selectAsc.gereplacedems().add("replacedreplacedin");
            selectAsc.gereplacedems().add("Saboteur");
            selectAsc.gereplacedems().add("Trickster");
        } else if (selectedClreplacedIndex == 6) {
            clreplacedName = "Scion";
            selectAsc.gereplacedems().clear();
            selectAsc.gereplacedems().add("Ascendant");
        }
        addButton.setDisable(true);
        if (!buildName.getText().equals("")) {
            if (select.getSelectionModel().getSelectedIndex() != -1) {
                if (selectAsc.getSelectionModel().getSelectedIndex() != -1) {
                    addButton.setDisable(false);
                }
            }
        }
    }

    @FXML
    private void ascChanged(ActionEvent event) {
        ascendancy = (String) selectAsc.getSelectionModel().getSelectedItem();
        if (!buildName.getText().equals("")) {
            addButton.setDisable(false);
        } else {
            addButton.setDisable(true);
        }
    }

    public void preplacedDialog(JFXDialog parent) {
        this.parentDialog = parent;
    }
}

16 Source : EditUserFormController.java
with MIT License
from HouariZegai

public clreplaced EditUserFormController implements Initializable {

    @FXML
    private VBox root;

    @FXML
    private JFXTextField userNameField;

    @FXML
    private JFXTextField firstNameField;

    @FXML
    private JFXTextField lastNameField;

    @FXML
    private JFXDatePicker datePicker;

    @FXML
    private JFXTextField emailField;

    @FXML
    private JFXToggleButton isTeacherToggleButton;

    @FXML
    private JFXComboBox<String> comboSection, comboGroup;

    // Error Message
    private JFXSnackbar toastErrorMsg;

    // this variable using to fill the edit form
    public static User userSelected;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // This ComboBox for Edit Account
        comboSection.gereplacedems().addAll(new String[] { "1", "2", "3", "4" });
        comboGroup.gereplacedems().addAll(new String[] { "1", "2", "3" });
        root.setOnKeyPressed(event -> {
            // Add Key Listener, if i click to the Enter Button Call btnLogin() method
            if (event.getCode().equals(ENTER)) {
                btnEdit();
            }
        });
        userNameField.setText(userSelected.getUsername());
        firstNameField.setText(userSelected.getFirstName());
        lastNameField.setText(userSelected.getLastName());
        datePicker.setValue(userSelected.getDateOfBirth().toLocalDate());
        emailField.setText(userSelected.getEmail());
        isTeacherToggleButton.setSelected(userSelected.getIsTeacher());
        if (userSelected.getIsTeacher()) {
            // for hide the Section & group comboBox
            actionToggleButton();
        }
        if (!userSelected.getIsTeacher()) {
            comboSection.getSelectionModel().select(userSelected.getSection());
            comboGroup.getSelectionModel().select(userSelected.getGroup());
        }
        toastErrorMsg = new JFXSnackbar(root);
        userNameField.setOnKeyReleased(event -> {
            // this event for check max length of the answer area
            if (userNameField.getText().length() > 25) {
                userNameField.setText(userNameField.getText().substring(0, 25));
                userNameField.positionCaret(userNameField.getText().length());
            }
        });
    }

    @FXML
    public void btnEdit() {
        // Add New Student
        if (!userNameField.getText().trim().toLowerCase().matches("[a-z0-9_]{4,}")) {
            toastErrorMsg.show("Username error", 1500);
            return;
        }
        if (!firstNameField.getText().trim().toLowerCase().matches("[a-z]{4,}")) {
            toastErrorMsg.show("First name error!", 1500);
            return;
        }
        if (!lastNameField.getText().trim().toLowerCase().matches("[a-z]{4,}")) {
            toastErrorMsg.show("Last name error!", 1500);
            return;
        }
        if (datePicker.getValue() == null) {
            toastErrorMsg.show("Please fill Date of Birth!", 1500);
            return;
        }
        if (!emailField.getText().trim().matches("[a-zA-Z_][\\w]*[-]{0,4}[\\w]+@[a-zA-Z0-9]+.[a-zA-Z]{2,6}")) {
            toastErrorMsg.show("Email error!", 1500);
            return;
        }
        if (!isTeacherToggleButton.isSelected()) {
            if (comboSection.getSelectionModel().getSelectedItem() == null) {
                toastErrorMsg.show("Please fill section !", 1500);
                return;
            }
            if (comboGroup.getSelectionModel().getSelectedItem() == null) {
                toastErrorMsg.show("Please fill group !", 1500);
                return;
            }
        }
        User user = new User();
        user.setId(userSelected.getId());
        user.setUsername(userNameField.getText().trim().toLowerCase());
        user.setFirstName(firstNameField.getText().trim().toLowerCase());
        user.setLastName(lastNameField.getText().trim().toLowerCase());
        user.setDateOfBirth(Date.valueOf(datePicker.getValue()));
        user.setEmail(emailField.getText().trim().toLowerCase());
        user.setIsTeacher(isTeacherToggleButton.isSelected());
        if (!isTeacherToggleButton.isSelected()) {
            user.setSection(Integer.parseInt(comboSection.getSelectionModel().getSelectedItem()));
            user.setGroup(Integer.parseInt(comboGroup.getSelectionModel().getSelectedItem()));
        }
        int status = new UserDao().editUser(user);
        switch(status) {
            case -1:
                toastErrorMsg.show("Connection failed !", 1500);
                break;
            case 0:
                toastErrorMsg.show("User not edited !", 1500);
                break;
            case 2:
                toastErrorMsg.show("Userame already exists !", 1500);
                break;
            case 1:
                {
                    Notifications.create().replacedle("You Successfuly edited user !").graphic(new ImageView(new Image("/com/houarizegai/learnsql/resources/images/icons/valid.png"))).hideAfter(Duration.millis(2000)).position(Pos.BOTTOM_RIGHT).darkStyle().show();
                    ManageAccountController.editUserDialog.close();
                }
        }
    }

    @FXML
    public void btnReset() {
        userNameField.setText(userSelected.getUsername());
        firstNameField.setText(userSelected.getFirstName());
        lastNameField.setText(userSelected.getLastName());
        datePicker.setValue(userSelected.getDateOfBirth().toLocalDate());
        emailField.setText(userSelected.getEmail());
        isTeacherToggleButton.setSelected(userSelected.getIsTeacher());
        if (userSelected.getIsTeacher()) {
            comboSection.setVisible(false);
            comboGroup.setVisible(false);
        } else {
            comboSection.setVisible(true);
            comboGroup.setVisible(true);
            comboSection.getSelectionModel().select(userSelected.getSection());
            comboGroup.getSelectionModel().select(userSelected.getGroup());
        }
    }

    @FXML
    public void btnCancel() {
        ManageAccountController.editUserDialog.close();
    }

    @FXML
    public void actionToggleButton() {
        if (isTeacherToggleButton.isSelected()) {
            comboSection.setVisible(false);
            comboGroup.setVisible(false);
        } else {
            comboSection.setVisible(true);
            comboGroup.setVisible(true);
        }
    }

    @FXML
    private void btnClose() {
        ManageAccountController.editUserDialog.close();
    }
}

16 Source : AddUserFormController.java
with MIT License
from HouariZegai

public clreplaced AddUserFormController implements Initializable {

    /* Start Add Account Pane */
    @FXML
    private VBox root;

    @FXML
    private JFXTextField userNameField;

    @FXML
    private JFXPreplacedwordField preplacedwordField;

    @FXML
    private JFXTextField firstNameField;

    @FXML
    private JFXTextField lastNameField;

    @FXML
    private JFXDatePicker datePicker;

    @FXML
    private JFXTextField emailField;

    @FXML
    private JFXToggleButton isTeacherToggleButton;

    @FXML
    private JFXComboBox<String> comboSection, comboGroup;

    // Error Message
    private JFXSnackbar toastErrorMsg;

    /* End Add Account Pane */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // This ComboBox for Add Account
        comboSection.gereplacedems().addAll(new String[] { "1", "2", "3", "4" });
        comboGroup.gereplacedems().addAll(new String[] { "1", "2", "3" });
        /* End ComboBox */
        root.setOnKeyPressed(event -> {
            // Add Key Listener, if i click to the Enter Button Call btnLogin() method
            if (event.getCode().equals(ENTER)) {
                btnAdd();
            }
        });
        toastErrorMsg = new JFXSnackbar(root);
        userNameField.setOnKeyReleased(event -> {
            // this event for check max length of the answer area
            if (userNameField.getText().length() > 25) {
                userNameField.setText(userNameField.getText().substring(0, 25));
                userNameField.positionCaret(userNameField.getText().length());
            }
        });
        preplacedwordField.setOnKeyReleased(event -> {
            // this event for check max length of the answer area
            if (preplacedwordField.getText().length() > 50) {
                preplacedwordField.setText(preplacedwordField.getText().substring(0, 50));
                preplacedwordField.positionCaret(preplacedwordField.getText().length());
            }
        });
    }

    /* Start Add Account Action Part */
    @FXML
    public void btnClear() {
        userNameField.setText("");
        preplacedwordField.setText("");
        firstNameField.setText("");
        lastNameField.setText("");
        datePicker.setValue(null);
        emailField.setText("");
        isTeacherToggleButton.setSelected(false);
        comboSection.setVisible(true);
        comboGroup.setVisible(true);
        comboSection.getSelectionModel().select(null);
        comboGroup.getSelectionModel().select(null);
    }

    @FXML
    public void btnAdd() {
        // Add New Student
        if (!userNameField.getText().trim().toLowerCase().matches("[a-z0-9_]{4,}")) {
            toastErrorMsg.show("Username error !", 1500);
            return;
        }
        if (preplacedwordField.getText().length() < 8) {
            toastErrorMsg.show("Preplacedword error !", 1500);
            return;
        }
        if (!firstNameField.getText().trim().toLowerCase().matches("[a-z]{3,}")) {
            toastErrorMsg.show("First name error !", 1500);
            return;
        }
        if (!lastNameField.getText().trim().toLowerCase().matches("[a-z]{3,}")) {
            toastErrorMsg.show("Last name error !", 1500);
            return;
        }
        if (datePicker.getValue() == null) {
            toastErrorMsg.show("Please fill Date of Birth !", 1500);
            return;
        }
        if (!emailField.getText().trim().matches("[a-zA-Z_][\\w]*[-]{0,4}[\\w]+@[a-zA-Z0-9]+.[a-zA-Z]{2,6}")) {
            toastErrorMsg.show("Email error !", 1500);
            return;
        }
        if (!isTeacherToggleButton.isSelected()) {
            if (comboSection.getSelectionModel().getSelectedItem() == null) {
                toastErrorMsg.show("Please fill section !", 1500);
                return;
            }
            if (comboGroup.getSelectionModel().getSelectedItem() == null) {
                toastErrorMsg.show("Please fill group !", 1500);
                return;
            }
        }
        User user = new User();
        user.setUsername(userNameField.getText().trim().toLowerCase());
        user.setPreplacedword(preplacedwordField.getText());
        user.setFirstName(firstNameField.getText().trim().toLowerCase());
        user.setLastName(lastNameField.getText().trim().toLowerCase());
        System.out.println("Date : " + datePicker.getValue().toString());
        user.setDateOfBirth(Date.valueOf(datePicker.getValue()));
        user.setEmail(emailField.getText().trim().toLowerCase());
        user.setIsTeacher(isTeacherToggleButton.isSelected());
        if (!isTeacherToggleButton.isSelected()) {
            user.setSection(Integer.parseInt(comboSection.getSelectionModel().getSelectedItem()));
            user.setGroup(Integer.parseInt(comboGroup.getSelectionModel().getSelectedItem()));
        }
        int status = new UserDao().addUser(user);
        switch(status) {
            case -1:
                toastErrorMsg.show("Connection failed :", 1500);
                break;
            case 0:
                toastErrorMsg.show("User not added :", 1500);
                break;
            case 2:
                toastErrorMsg.show("Username aleady exists !", 1500);
                break;
            case 1:
                {
                    Notifications.create().replacedle("You Successfuly added new user !").graphic(new ImageView(new Image("/com/houarizegai/learnsql/resources/images/icons/valid.png"))).hideAfter(Duration.millis(2000)).position(Pos.BOTTOM_RIGHT).darkStyle().show();
                    ManageAccountController.addUserDialog.close();
                }
        }
    }

    @FXML
    public void actionToggleButton() {
        if (isTeacherToggleButton.isSelected()) {
            comboSection.setVisible(false);
            comboGroup.setVisible(false);
        } else {
            comboSection.setVisible(true);
            comboGroup.setVisible(true);
        }
    }

    @FXML
    private void btnClose() {
        ManageAccountController.addUserDialog.close();
    }
}

16 Source : TempViewController.java
with MIT License
from ffffffff0x

public clreplaced TempViewController {

    @FXML
    private JFXButton JBT_enCode;

    @FXML
    private JFXButton JBT_deCode;

    @FXML
    private JFXTextArea JTA_src;

    @FXML
    private JFXTextArea JTA_dst;

    @FXML
    private JFXComboBox JCB_charset;

    @FXML
    private JTextField JTF_split;

    @FXML
    private void initialize() {
    }

    @FXML
    public void ONClick_JBT_enCode() {
        JTA_dst.setText(JTA_src.getText());
    }

    @FXML
    public void ONClick_JBT_deCode() {
    }
}

16 Source : NetworkcreatorController.java
with GNU General Public License v3.0
from afsalashyana

public clreplaced NetworkcreatorController implements Initializable, NeuralNetworkCreationCompleteListener {

    @FXML
    private JFXTextField neuralNetLabel;

    @FXML
    private JFXTextField width;

    @FXML
    private JFXTextField height;

    @FXML
    private JFXComboBox<String> colorMode;

    @FXML
    private JFXTextField neuronLabelList;

    @FXML
    private JFXTextField neuronCountList;

    @FXML
    private JFXComboBox<String> transferFunction;

    @FXML
    private Pane container;

    @FXML
    private AnchorPane rootPane;

    @FXML
    private JFXSpinner loadingSpinner;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        loadingSpinner.setVisible(false);
        // Add ColorModes ,
        ObservableList list = FXCollections.observableArrayList();
        list.add("COLOR_RGB");
        list.add("COLOR_HSL");
        list.add("BLACK_AND_WHITE");
        colorMode.gereplacedems().setAll(list);
        // Add TransferFunctionss
        ObservableList listTransferFunctions = FXCollections.observableArrayList();
        listTransferFunctions.add("LINEAR");
        listTransferFunctions.add("RAMP");
        listTransferFunctions.add("STEP");
        listTransferFunctions.add("SIGMOID");
        listTransferFunctions.add("TANH");
        listTransferFunctions.add("GAUSSIAN");
        listTransferFunctions.add("TRAPEZOID");
        listTransferFunctions.add("SGN");
        listTransferFunctions.add("SIN");
        listTransferFunctions.add("LOG");
        transferFunction.gereplacedems().setAll(listTransferFunctions);
    }

    @FXML
    private void saveNeuralNet(ActionEvent event) {
        String neuralNetLbl = neuralNetLabel.getText();
        Dimension samplingDimension = new Dimension(Integer.parseInt(width.getText()), Integer.parseInt(height.getText()));
        ColorMode mode;
        switch(colorMode.getSelectionModel().getSelectedItem()) {
            case "COLOR_RGB":
                mode = ColorMode.COLOR_RGB;
                break;
            case "COLOR_HSL":
                mode = ColorMode.COLOR_HSL;
                break;
            case "BLACK_AND_WHITE":
                mode = ColorMode.COLOR_RGB;
                break;
            default:
                mode = ColorMode.COLOR_RGB;
                break;
        }
        TransferFunctionType tFunction;
        switch(transferFunction.getSelectionModel().getSelectedItem()) {
            case "LINEAR":
                tFunction = TransferFunctionType.LINEAR;
                break;
            case "RAMP":
                tFunction = TransferFunctionType.RAMP;
                break;
            case "STEP":
                tFunction = TransferFunctionType.STEP;
                break;
            case "SIGMOID":
                tFunction = TransferFunctionType.SIGMOID;
                break;
            case "TANH":
                tFunction = TransferFunctionType.TANH;
                break;
            case "GAUSSIAN":
                tFunction = TransferFunctionType.GAUSSIAN;
                break;
            case "TRAPEZOID":
                tFunction = TransferFunctionType.TRAPEZOID;
                break;
            case "SGN":
                tFunction = TransferFunctionType.SGN;
                break;
            case "SIN":
                tFunction = TransferFunctionType.SIN;
                break;
            case "LOG":
                tFunction = TransferFunctionType.LOG;
                break;
            default:
                tFunction = TransferFunctionType.GAUSSIAN;
                break;
        }
        ArrayList<String> neuronLabels = new ArrayList(Arrays.asList(neuronLabelList.getText().split("[,]")));
        ArrayList<Integer> neuronCounts = new ArrayList();
        for (String neuronCount : neuronCountList.getText().split("[,]")) {
            neuronCounts.add(Integer.parseInt(neuronCount.replaceAll(" ", "")));
            System.out.println("neuronCounts = " + neuronCount);
        }
        // Show File save dialog
        FileChooser fileChooser = new FileChooser();
        fileChooser.setreplacedle("Save Neural Network");
        File file = fileChooser.showSaveDialog(rootPane.getScene().getWindow());
        if (file == null) {
            Calert.showAlert("Not a valid File", "Select target again", Alert.AlertType.ERROR);
            return;
        }
        MLPNetworkMaker maker = new MLPNetworkMaker(neuralNetLbl, samplingDimension, mode, neuronLabels, neuronCounts, tFunction, file.getAbsolutePath());
        maker.setListener(this);
        Thread nnetCreator = new Thread(maker);
        nnetCreator.start();
        loadingSpinner.setVisible(true);
    }

    @Override
    public void networkCreationComplete(Boolean flag) {
        loadingSpinner.setVisible(false);
        if (flag) {
            Calert.showAlert("Done", "Neural Network Saved Successfully", Alert.AlertType.INFORMATION);
        }
    }
}

15 Source : CreateWorkspaceDialog.java
with MIT License
from warmuuh

public clreplaced CreateWorkspaceDialog {

    VBox syncDetailsArea;

    JFXComboBox<SynchronizationDetailFactory> syncSelector;

    JFXTextField workspaceNameInput;

    private Dialog dialog;

    SynchronizationDetailFactory selectedSynchronizer = null;

    private Toaster toaster;

    private Workspace workspace;

    private SyncDetails syncDetails;

    public void showAndWait(List<WorkspaceSynchronizer> synchronizers, Toaster toaster) {
        this.toaster = toaster;
        JFXDialogLayout content = new CreateWorkspaceDialogFxml(this);
        synchronizers.forEach(i -> syncSelector.gereplacedems().add(i.getDetailFactory()));
        // default to first item
        if (syncSelector.gereplacedems().size() > 0) {
            SynchronizationDetailFactory defaultSync = syncSelector.gereplacedems().get(0);
            syncSelector.setValue(defaultSync);
            syncDetailsArea.getChildren().add(defaultSync.getSyncDetailsControls());
            selectedSynchronizer = defaultSync;
        }
        syncSelector.setConverter(new StringConverter<SynchronizationDetailFactory>() {

            @Override
            public String toString(SynchronizationDetailFactory object) {
                return object.getName();
            }

            @Override
            public SynchronizationDetailFactory fromString(String string) {
                return null;
            }
        });
        syncSelector.getSelectionModel().selectedItemProperty().addListener((obs, o, v) -> {
            if (o != v && v != null) {
                selectedSynchronizer = v;
                syncDetailsArea.getChildren().clear();
                syncDetailsArea.getChildren().add(v.getSyncDetailsControls());
            }
        });
        dialog = FxmlUtil.createDialog(content);
        dialog.showAndWait();
    }

    public void onClose() {
        dialog.close();
    }

    public void onCreate() {
        if (selectedSynchronizer != null && workspaceNameInput.validate()) {
            try {
                syncDetails = selectedSynchronizer.createSyncDetails();
                dialog.close();
            } catch (Throwable t) {
                toaster.showToast(ExceptionUtils.getRootCauseMessage(t));
            }
        }
    }

    public SyncDetails getSyncDetails() {
        return syncDetails;
    }

    public String getWorkspaceName() {
        return workspaceNameInput.getText();
    }

    public boolean wasCancelled() {
        return syncDetails == null;
    }

    public static clreplaced CreateWorkspaceDialogFxml extends JFXDialogLayout {

        public CreateWorkspaceDialogFxml(CreateWorkspaceDialog controller) {
            setHeading(new Label("Create Workspace"));
            VboxExt vbox = new VboxExt();
            vbox.add(new Label("Workspace Name"));
            controller.workspaceNameInput = vbox.add(new JFXTextField());
            controller.workspaceNameInput.setValidators(requiredValidator());
            vbox.add(new Label("Synchronization"));
            controller.syncSelector = vbox.add(new JFXComboBox<>());
            controller.syncDetailsArea = vbox.add(new VBox());
            setBody(vbox);
            setActions(submit(controller::onCreate, "Create"), cancel(controller::onClose, "Close"));
        }
    }
}

15 Source : ManageVehicleUIController.java
with Apache License 2.0
from Shehanka

/**
 * @author chamodshehanka on 4/25/2018
 * @project RentLio
 */
public clreplaced ManageVehicleUIController implements Initializable {

    @FXML
    private JFXComboBox<String> cmbVehicleType;

    @FXML
    private ImageView imgVehicle;

    @FXML
    private JFXTextField txtVehicleNumber;

    @FXML
    private JFXComboBox<String> cmbVehicleBrand;

    @FXML
    private JFXTextField txtVehicleModel;

    @FXML
    private JFXTextField txtChreplacedisNumber;

    @FXML
    private JFXTextField txtFuel;

    @FXML
    private JFXTextField txtKMRS;

    @FXML
    private JFXTextField txtEngineCapacity;

    @FXML
    private JFXColorPicker pkVehicleColor;

    @FXML
    private JFXTextField txtNoOfDoors;

    @FXML
    private JFXTextField txtInsuranceCom;

    @FXML
    private JFXTextField txtComment;

    @FXML
    private JFXTextField txtStatus;

    @FXML
    private TableView<VehicleTableModel> tblVehicle;

    @FXML
    private TableColumn<VehicleTableModel, String> colVehicleNo;

    @FXML
    private TableColumn<VehicleTableModel, String> colVehicleType;

    @FXML
    private TableColumn<VehicleTableModel, String> colVehicleBrand;

    @FXML
    private TableColumn<VehicleTableModel, String> colModel;

    @FXML
    private TableColumn<VehicleTableModel, String> colImgURL;

    @FXML
    private TableColumn<VehicleTableModel, String> colModelYear;

    @FXML
    private TableColumn<VehicleTableModel, String> colChreplacedieNo;

    @FXML
    private TableColumn<VehicleTableModel, String> colFuel;

    @FXML
    private TableColumn<VehicleTableModel, Double> colKMRS;

    @FXML
    private TableColumn<VehicleTableModel, String> colCapacity;

    @FXML
    private TableColumn<VehicleTableModel, String> colColor;

    @FXML
    private TableColumn<VehicleTableModel, Integer> colDoors;

    @FXML
    private TableColumn<VehicleTableModel, String> colInsurance;

    @FXML
    private TableColumn<VehicleTableModel, String> colComment;

    @FXML
    private TableColumn<VehicleTableModel, String> colStatus;

    private ObservableList<VehicleTableModel> vehicleTableModelObservableList = FXCollections.observableArrayList();

    private Stage fileChooseStage = new Stage();

    private String fileName;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        setUpUIComponents();
    }

    @FXML
    private void addAction() {
        VehicleDTO vehicleDTO = new VehicleDTO(txtVehicleNumber.getText(), cmbVehicleType.getValue(), cmbVehicleBrand.getValue(), txtVehicleModel.getText(), fileName, "N/A", txtChreplacedisNumber.getText(), txtFuel.getText(), Double.valueOf(txtKMRS.getText()), txtEngineCapacity.getText(), String.valueOf(pkVehicleColor.getValue()), Integer.valueOf(txtNoOfDoors.getText()), txtInsuranceCom.getText(), txtComment.getText(), txtStatus.getText());
        try {
            boolean isAdded = VehicleController.addVehicle(vehicleDTO);
            if (isAdded) {
                new AlertBuilder("info", "Manage Vehicle", "Vehicle Add", "Vehicle added successfully");
            } else {
                new AlertBuilder("error", "Manage Vehicle", "Vehicle Add", "Vehicle couldn't add");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void searchById() {
        try {
            VehicleDTO vehicleDTO = VehicleController.getVehicleById(txtVehicleNumber.getText());
            if (vehicleDTO != null) {
                txtVehicleNumber.setText(vehicleDTO.getVehicleNumber());
                cmbVehicleType.getSelectionModel().select(vehicleDTO.getVehicleType());
                cmbVehicleBrand.getSelectionModel().select(vehicleDTO.getVehicleBrand());
                txtVehicleModel.setText(vehicleDTO.getVehicleModel());
                txtFuel.setText(vehicleDTO.getFuel());
                txtChreplacedisNumber.setText(vehicleDTO.getChreplacediNumber());
                txtStatus.setText(vehicleDTO.getStatus());
                txtKMRS.setText(String.valueOf(vehicleDTO.getKmrs()));
                txtEngineCapacity.setText(vehicleDTO.getEngineCapacity());
                pkVehicleColor.setValue(Color.valueOf(vehicleDTO.getColour()));
                txtNoOfDoors.setText(String.valueOf(vehicleDTO.getDoors()));
                txtInsuranceCom.setText(vehicleDTO.getInsuranceCom());
                txtComment.setText(vehicleDTO.getComment());
                setImgVehicle(vehicleDTO.getImageURL());
            } else {
                new AlertBuilder("warn", "Manage Vehicle", "Vehicle Add", "Vehicle couldn't add");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setImgVehicle(String imgName) {
        imgVehicle.setImage(new Image("/images/" + imgName + ".jpg"));
    }

    @FXML
    private void updateAction() {
        VehicleDTO vehicleDTO = new VehicleDTO(txtVehicleNumber.getText(), cmbVehicleType.getValue(), cmbVehicleBrand.getValue(), txtVehicleModel.getText(), fileName, "N/A", txtChreplacedisNumber.getText(), txtFuel.getText(), Double.valueOf(txtKMRS.getText()), txtEngineCapacity.getText(), String.valueOf(pkVehicleColor.getValue()), Integer.valueOf(txtNoOfDoors.getText()), txtInsuranceCom.getText(), txtComment.getText(), txtStatus.getText());
        try {
            boolean isUpdated = VehicleController.updateVehicle(vehicleDTO);
            if (isUpdated) {
                new AlertBuilder("info", "Manage Vehicle", "Vehicle Update", "Vehicle successfully updated");
            } else {
                new AlertBuilder("warn", "Manage Vehicle", "Vehicle Update", "Vehicle couldn't update");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void deleteAction() {
        try {
            boolean isDeleted = VehicleController.deleteVehicle(txtVehicleNumber.getText());
            if (isDeleted) {
                new AlertBuilder("info", "Manage Vehicle", "Vehicle Delete", "Vehicle successfully deleted");
            } else {
                new AlertBuilder("warn", "Manage Vehicle", "Vehicle Delete", "Vehicle couldn't delete");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setUpUIComponents() {
        cmbVehicleType.gereplacedems().addAll("Family", "Other");
        cmbVehicleBrand.gereplacedems().addAll("Toyota", "Honda", "Suzuki");
        removeImgURL();
        loadVehicleTableView();
    }

    @FXML
    private void browseImgURL() {
        FileChooser fileChooser = new FileChooser();
        File file = fileChooser.showOpenDialog(fileChooseStage);
        if (file != null) {
            fileName = String.valueOf(file);
            String mimeType = null;
            try {
                mimeType = Files.probeContentType(file.toPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (mimeType != null && mimeType.split("/")[0].equals("image")) {
                fileName = fileName.substring(24, fileName.length());
                fileChooser.showSaveDialog(fileChooseStage);
                setImgVehicle(fileName);
            } else {
                new AlertBuilder("error", "Browse", "Image", "Reception couldn't delete !!");
            }
        } else {
            System.out.println("File is null");
        }
    }

    private void loadVehicleTableView() {
        colVehicleNo.setCellValueFactory(new PropertyValueFactory<>("carNumber"));
        colVehicleType.setCellValueFactory(new PropertyValueFactory<>("vehicleType"));
        colVehicleBrand.setCellValueFactory(new PropertyValueFactory<>("brand"));
        colModel.setCellValueFactory(new PropertyValueFactory<>("model"));
        colImgURL.setCellValueFactory(new PropertyValueFactory<>("imageURL"));
        colModelYear.setCellValueFactory(new PropertyValueFactory<>("modelYear"));
        colChreplacedieNo.setCellValueFactory(new PropertyValueFactory<>("chasieNo"));
        colFuel.setCellValueFactory(new PropertyValueFactory<>("fuel"));
        colKMRS.setCellValueFactory(new PropertyValueFactory<>("kmRs"));
        colCapacity.setCellValueFactory(new PropertyValueFactory<>("engineCapacity"));
        colColor.setCellValueFactory(new PropertyValueFactory<>("colour"));
        colDoors.setCellValueFactory(new PropertyValueFactory<>("noOfDoors"));
        colInsurance.setCellValueFactory(new PropertyValueFactory<>("insurance"));
        colComment.setCellValueFactory(new PropertyValueFactory<>("comment"));
        colStatus.setCellValueFactory(new PropertyValueFactory<>("status"));
        tblVehicle.sereplacedems(vehicleTableModelObservableList);
        try {
            List<VehicleDTO> vehicleDTOList = VehicleController.getAllVehicles();
            for (VehicleDTO vehicleDTO : vehicleDTOList) {
                VehicleTableModel vehicleTableModel = new VehicleTableModel();
                vehicleTableModel.setCarNumber(vehicleDTO.getVehicleNumber());
                vehicleTableModel.setVehicleType(vehicleDTO.getVehicleType());
                vehicleTableModel.setBrand(vehicleDTO.getVehicleBrand());
                vehicleTableModel.setModel(vehicleDTO.getVehicleModel());
                vehicleTableModel.setImageURL(vehicleDTO.getImageURL());
                vehicleTableModel.setModelYear(vehicleDTO.getModelYear());
                vehicleTableModel.setChasieNo(vehicleDTO.getChreplacediNumber());
                vehicleTableModel.setFuel(vehicleDTO.getFuel());
                vehicleTableModel.setKmRs(vehicleDTO.getKmrs());
                vehicleTableModel.setEngineCapacity(vehicleDTO.getEngineCapacity());
                vehicleTableModel.setColour(vehicleDTO.getColour());
                vehicleTableModel.setNoOfDoors(vehicleDTO.getDoors());
                vehicleTableModel.setInsurance(vehicleDTO.getInsuranceCom());
                vehicleTableModel.setComment(vehicleDTO.getComment());
                vehicleTableModel.setStatus(vehicleDTO.getStatus());
                vehicleTableModelObservableList.add(vehicleTableModel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void removeImgURL() {
        imgVehicle.setImage(new Image("/images/notAvailable.png"));
    }

    @FXML
    private void getSelectedItem() {
        String vehicleNo = tblVehicle.getSelectionModel().getSelectedItem().getCarNumber();
        txtVehicleNumber.setText(vehicleNo);
        searchById();
    }
}

15 Source : JavaCreationExtraOptions.java
with MIT License
from MSPaintIDE

public clreplaced JavaCreationExtraOptions extends ExtraCreationOptions {

    private static final Logger LOGGER = LoggerFactory.getLogger(JavaCreationExtraOptions.clreplaced);

    private MainGUI mainGUI;

    @FXML
    private JFXComboBox<JavaBuildSystem> buildSystemSelection;

    @FXML
    private JFXTextField groupId;

    @FXML
    private JFXTextField artifactId;

    @FXML
    private JFXTextField version;

    @FXML
    private JFXButton finish;

    @FXML
    private JFXButton cancel;

    @FXML
    private JFXButton help;

    public JavaCreationExtraOptions(MainGUI mainGUI) throws IOException {
        super();
        this.mainGUI = mainGUI;
        FXMLLoader loader = new FXMLLoader(getClreplaced().getClreplacedLoader().getResource("gui/GradleOptions.fxml"));
        loader.setController(this);
        Parent root = loader.load();
        ImageView icon = new ImageView(getClreplaced().getClreplacedLoader().getResource("icons/taskbar/ms-paint-logo-colored.png").toString());
        icon.setFitHeight(25);
        icon.setFitWidth(25);
        JFXDecorator jfxDecorator = new JFXDecorator(this, root, false, true, true);
        jfxDecorator.setGraphic(icon);
        jfxDecorator.setreplacedle("Gradle options");
        Scene scene = new Scene(jfxDecorator);
        scene.getStylesheets().add("style.css");
        setScene(scene);
        this.mainGUI.getThemeManager().addStage(this);
        setreplacedle("Gradle options");
        getIcons().add(new Image(getClreplaced().getClreplacedLoader().getResourcereplacedtream("ms-paint-logo-taskbar.png")));
        this.mainGUI.getThemeManager().onDarkThemeChange(root, Map.of(".search-label", "dark", ".found-context", "dark", ".language-selection", "language-selection-dark"));
    }

    @FXML
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        for (var value : JavaBuildSystem.values()) {
            buildSystemSelection.gereplacedems().add(value);
        }
        buildSystemSelection.valueProperty().addListener((observable, oldValue, newValue) -> {
            var usingDefault = newValue == JavaBuildSystem.DEFAULT;
            groupId.setDisable(usingDefault);
            artifactId.setDisable(usingDefault);
            version.setDisable(usingDefault);
        });
        finish.setOnAction(event -> {
            var settings = language.getLanguageSettings();
            var buildSystem = buildSystemSelection.getValue();
            if (buildSystem != JavaBuildSystem.DEFAULT) {
                var groupIdString = groupId.getText();
                var artifactIdString = artifactId.getText();
                var versionString = version.getText();
                if (groupIdString.isBlank() || artifactIdString.isBlank() || versionString.isBlank())
                    return;
                var parent = ppfProject.getFile().getParentFile();
                LOGGER.info("Creating wrapper in: {}", parent.getAbsolutePath());
                LOGGER.info("Creating gradle project {}:{}:{}", groupIdString, artifactIdString, versionString);
                Commandline.runLiveCommand(Arrays.asList("gradle", "wrapper", "--gradle-version", "5.6.2", "--distribution-type", "all"), parent, "Gradle");
                // TODO: This will fail if the OCR has not been trained yet. This should be resolved somehow, probably by
                // training the database on CMS if no font has been trained yet.
                try {
                    ImageIO.write(createImage("plugins {\n" + "    id 'java'\n" + "    id 'application'\n" + "}\n" + "\n" + "group '" + groupIdString + "'\n" + "version '" + versionString + "'\n" + "mainClreplacedName = '" + groupIdString + ".Main'\n" + "\n" + "sourceCompatibility = 11\n" + "\n" + "repositories {\n" + "    mavenCentral()\n" + "}\n" + "\n" + "dependencies {\n" + "    testCompile group: 'junit', name: 'junit', version: '4.12'\n" + "}\n"), "png", new File(parent, "build.gradle.png"));
                    ImageIO.write(createImage("rootProject.name = '" + artifactIdString + "'\n"), "png", new File(parent, "settings.gradle.png"));
                } catch (IOException | ExecutionException | InterruptedException e) {
                    LOGGER.error("There was an error creating the build.gradle and settings.gradle");
                }
            }
            settings.setSetting(JavaLangOptions.BUILDSYSTEM, buildSystemSelection.getValue());
            close();
            onComplete.run();
        });
        cancel.setOnAction(event -> {
            close();
            createProjectWindow.close();
        });
        help.setOnAction(event -> Browse.browse("https://github.com/MSPaintIDE/MSPaintIDE/blob/master/README.md"));
    }

    private BufferedImage createImage(String text) throws IOException, ExecutionException, InterruptedException {
        var padding = 15;
        ScannedImage letterGrid = generateLetterGrid(mainGUI.getStartupLogic(), null, text);
        var coords = getBiggestCoordinates(letterGrid);
        applyPadding(letterGrid, padding, padding);
        BufferedImage bufferedImage = new BufferedImage(coords[0] + padding * 2, coords[1] + padding * 2, BufferedImage.TYPE_INT_ARGB);
        LetterFileWriter letterFileWriter = new LetterFileWriter(letterGrid, bufferedImage, null);
        letterFileWriter.writeToFile();
        return letterFileWriter.getImage();
    }
}

15 Source : SelectCharacter_PopupController.java
with MIT License
from karakasis

/**
 * FXML Controller clreplaced
 *
 * @author Protuhj
 */
public clreplaced SelectCharacter_PopupController implements Initializable {

    private final ArrayList<CharacterInfo> m_characterList;

    private final ObservableList<Node> allNodes = FXCollections.observableArrayList(item -> new Observable[] { item.visibleProperty() });

    SelectCharacter_PopupController(ArrayList<CharacterInfo> characterList) {
        this.m_characterList = characterList;
    }

    @FXML
    private JFXListView<Node> charactersBox;

    @FXML
    private JFXComboBox<String> cmbLeagueFilter;

    private final HashMap<Node, String> m_NodeToLeague = new HashMap<>();

    private Consumer<CharacterInfo> closePopupFunction;

    public void hook(Consumer<CharacterInfo> closePopupFunction) {
        this.closePopupFunction = closePopupFunction;
    }

    public void update(int id) {
        replacedert (m_characterList != null);
        closePopupFunction.accept(m_characterList.get(id));
    }

    private void filterChanged() {
        filterCharacters(cmbLeagueFilter.getValue());
    }

    private void filterCharacters(String league) {
        for (Node node : allNodes) {
            node.setVisible(league.isEmpty() || "All".equalsIgnoreCase(league) || m_NodeToLeague.get(node).equalsIgnoreCase(league));
        }
    }

    /**
     * Initializes the controller clreplaced.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        replacedert (m_characterList != null);
        Set<String> leagueList = new LinkedHashSet<>();
        leagueList.add("All");
        for (int i = 0; i < m_characterList.size(); i++) {
            // this might require to update the buildsLoaded on each new build added and removed
            CharacterInfo ci = m_characterList.get(i);
            leagueList.add(ci.league);
            FXMLLoader loader = new FXMLLoader(getClreplaced().getResource("characterEntry.fxml"));
            try {
                Node n = loader.load();
                // n.managedProperty().bind(n.visibleProperty());
                m_NodeToLeague.put(n, ci.league);
                // this will add the AnchorPane to the VBox
                // charactersBox.gereplacedems().add(n);
                allNodes.add(n);
            } catch (IOException ex) {
                Logger.getLogger(SelectBuild_PopupController.clreplaced.getName()).log(Level.SEVERE, null, ex);
            }
            // add controller to the linker clreplaced
            CharacterEntry_Controller cec = loader.getController();
            cec.init_for_popup(ci, i, this::update);
        }
        cmbLeagueFilter.gereplacedems().addAll(leagueList);
        cmbLeagueFilter.setOnAction(event -> filterChanged());
        FilteredList<Node> filtered = new FilteredList<>(allNodes, node -> node.visibleProperty().get());
        charactersBox.sereplacedems(filtered);
    }
}

15 Source : ManagementController.java
with MIT License
from HouariZegai

public clreplaced ManagementController implements Initializable {

    /* Table Part */
    @FXML
    private JFXTreeTableView tableEmployees;

    private JFXTreeTableColumn<Employee, String> colName, colJob, colAge, colGender;

    /* Search Part */
    @FXML
    private JFXComboBox<String> comboSearch;

    @FXML
    private JFXTextField fieldSearch;

    /* Management Part */
    @FXML
    private JFXTextField fieldName, fieldJob, fieldAge;

    @FXML
    private JFXComboBox<String> fieldGender;

    /* View Part */
    @FXML
    private Label lblName, lblJob, lblAge, lblGender;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        fieldGender.gereplacedems().addAll("Male", "Female");
        comboSearch.gereplacedems().addAll("Name", "Job", "Age", "Gender");
        // Initialize search
        initSearch();
        // Initialize table
        initTable();
        // Load data to table from database
        loadTable();
    }

    private void initTable() {
        colName = new JFXTreeTableColumn<>("NAME");
        colName.setPrefWidth(200);
        colName.setCellValueFactory((TreeTableColumn.CellDataFeatures<Employee, String> param) -> param.getValue().getValue().getName());
        colJob = new JFXTreeTableColumn<>("JOB");
        colJob.setPrefWidth(200);
        colJob.setCellValueFactory((TreeTableColumn.CellDataFeatures<Employee, String> param) -> param.getValue().getValue().getJob());
        colAge = new JFXTreeTableColumn<>("AGE");
        colAge.setPrefWidth(200);
        colAge.setCellValueFactory((TreeTableColumn.CellDataFeatures<Employee, String> param) -> param.getValue().getValue().getAge());
        colGender = new JFXTreeTableColumn<>("GENDER");
        colGender.setPrefWidth(200);
        colGender.setCellValueFactory((TreeTableColumn.CellDataFeatures<Employee, String> param) -> param.getValue().getValue().getGender());
        tableEmployees.getColumns().addAll(colName, colJob, colAge, colGender);
        tableEmployees.setShowRoot(false);
        tableEmployees.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
            if (newSelection != null) {
                // selected index
                int index = tableEmployees.getSelectionModel().getSelectedIndex();
                lblName.setText(colName.getCellData(index));
                lblJob.setText(colJob.getCellData(index));
                lblAge.setText(colAge.getCellData(index));
                lblGender.setText(colGender.getCellData(index));
                fieldName.setText(colName.getCellData(index));
                fieldJob.setText(colJob.getCellData(index));
                fieldAge.setText(colAge.getCellData(index));
                fieldGender.getSelectionModel().select(colGender.getCellData(index));
            }
        });
    }

    private void loadTable() {
        ObservableList<Employee> employees = FXCollections.observableArrayList();
        List<EmployeeVo> employeesDao = new EmployeeDao().getEmployees();
        if (employeesDao == null) {
            return;
        }
        for (EmployeeVo emp : employeesDao) {
            employees.add(new Employee(emp.getName().substring(0, 1).toUpperCase() + emp.getName().substring(1), emp.getJob().substring(0, 1).toUpperCase() + emp.getJob().substring(1), emp.getAge(), emp.getGender()));
        }
        final TreeItem<Employee> treeItem = new RecursiveTreeItem<>(employees, RecursiveTreeObject::getChildren);
        try {
            tableEmployees.setRoot(treeItem);
        } catch (Exception ex) {
            System.out.println("Error catched !");
        }
    }

    private void initSearch() {
        fieldSearch.textProperty().addListener(e -> {
            filterTable();
        });
        comboSearch.setOnAction(e -> {
            filterTable();
        });
    }

    private void filterTable() {
        tableEmployees.setPredicate(new Predicate<TreeItem<Employee>>() {

            @Override
            public boolean test(TreeItem<Employee> employee) {
                switch(comboSearch.getSelectionModel().getSelectedIndex()) {
                    case 0:
                        return employee.getValue().getName().getValue().toLowerCase().contains(fieldSearch.getText().toLowerCase());
                    case 1:
                        return employee.getValue().getJob().getValue().toLowerCase().contains(fieldSearch.getText().toLowerCase());
                    case 2:
                        return employee.getValue().getAge().getValue().toLowerCase().contains(fieldSearch.getText().toLowerCase());
                    case 3:
                        return employee.getValue().getGender().getValue().toLowerCase().contains(fieldSearch.getText().toLowerCase());
                    default:
                        return employee.getValue().getName().getValue().toLowerCase().contains(fieldSearch.getText().toLowerCase()) || employee.getValue().getJob().getValue().toLowerCase().contains(fieldSearch.getText().toLowerCase()) || employee.getValue().getAge().getValue().toLowerCase().contains(fieldSearch.getText().toLowerCase()) || employee.getValue().getGender().getValue().toLowerCase().contains(fieldSearch.getText().toLowerCase());
                }
            }
        });
    }

    @FXML
    private void onAdd() {
        if (fieldName.getText().isEmpty() || !fieldName.getText().trim().matches("[a-zA-Z ]{4,}")) {
            return;
        }
        if (fieldJob.getText().isEmpty() || !fieldJob.getText().trim().matches("[a-zA-Z ]{2,}")) {
            return;
        }
        if (fieldAge.getText().isEmpty() || !fieldAge.getText().matches("[0-9]+") || Integer.parseInt(fieldAge.getText()) < 1 || Integer.parseInt(fieldAge.getText()) > 150) {
            return;
        }
        if (fieldGender.getSelectionModel().getSelectedItem() == null) {
            return;
        }
        new EmployeeDao().addEmployee(new EmployeeVoBuilder().setName(fieldName.getText().toLowerCase()).setJob(fieldJob.getText().toLowerCase()).setAge(Integer.parseInt(fieldAge.getText())).setGender(fieldGender.getSelectionModel().getSelectedIndex() == 0).getEmployeeVo());
        lblName.setText(null);
        lblJob.setText(null);
        lblAge.setText(null);
        lblGender.setText(null);
        fieldName.setText(null);
        fieldJob.setText(null);
        fieldAge.setText(null);
        fieldGender.getSelectionModel().clearSelection();
        loadTable();
    }

    @FXML
    private void onDelete() {
        new EmployeeDao().deleteEmployee(new EmployeeVoBuilder().setName(lblName.getText()).setJob(lblJob.getText()).setAge(Integer.parseInt(lblAge.getText())).setGender(lblGender.getText().equalsIgnoreCase("Male")).getEmployeeVo());
        lblName.setText(null);
        lblJob.setText(null);
        lblAge.setText(null);
        lblGender.setText(null);
        fieldName.setText(null);
        fieldJob.setText(null);
        fieldAge.setText(null);
        fieldGender.getSelectionModel().clearSelection();
        loadTable();
    }

    @FXML
    private void onEdit() {
        if (fieldName.getText().isEmpty() || !fieldName.getText().matches("[a-zA-Z]{4,}")) {
            return;
        }
        if (fieldJob.getText().isEmpty() || !fieldJob.getText().matches("[a-zA-Z]{2,}")) {
            return;
        }
        if (fieldAge.getText().isEmpty() || !fieldAge.getText().matches("[0-9]+") || Integer.parseInt(fieldAge.getText()) < 1 || Integer.parseInt(fieldAge.getText()) > 150) {
            return;
        }
        if (fieldGender.getSelectionModel().getSelectedItem() == null) {
            return;
        }
        EmployeeVo oldEmployee = new EmployeeVoBuilder().setName(lblName.getText().toLowerCase()).setJob(lblJob.getText().toLowerCase()).setAge(Integer.parseInt(lblAge.getText())).setGender(lblGender.getText().equalsIgnoreCase("Male")).getEmployeeVo();
        EmployeeVo newEmployee = new EmployeeVoBuilder().setName(fieldName.getText().trim().toLowerCase()).setJob(fieldJob.getText().trim().toLowerCase()).setAge(Integer.parseInt(fieldAge.getText())).setGender(fieldGender.getSelectionModel().getSelectedIndex() == 0).getEmployeeVo();
        new EmployeeDao().editEmployee(oldEmployee, newEmployee);
        lblName.setText(null);
        lblJob.setText(null);
        lblAge.setText(null);
        lblGender.setText(null);
        fieldName.setText(null);
        fieldJob.setText(null);
        fieldAge.setText(null);
        fieldGender.getSelectionModel().clearSelection();
        loadTable();
    }

    @FXML
    private void onClear() {
        fieldName.setText(lblName.getText());
        fieldJob.setText(lblJob.getText());
        fieldAge.setText(lblAge.getText());
        fieldGender.getSelectionModel().select(lblGender.getText());
    }
}

15 Source : AESController.java
with MIT License
from ffffffff0x

/**
 * @author RyuZU
 */
public clreplaced AESController {

    private Integer AP_OPTION_STATES = 0;

    private AESControlList aesControlList = new AESControlList();

    @FXML
    private JFXButton JBT_enCode;

    @FXML
    private JFXButton JBT_deCode;

    @FXML
    private JFXTextArea JTA_src;

    @FXML
    private JFXTextArea JTA_dst;

    @FXML
    private JFXButton JBT_option;

    @FXML
    private GridPane GP_option;

    @FXML
    private AnchorPane AP_option;

    @FXML
    private JFXComboBox JCB_encryptMode;

    @FXML
    private JFXComboBox JCB_paddingMode;

    @FXML
    private JFXTextArea JTA_AESKey;

    @FXML
    private JFXTextArea JTA_AESIV;

    @FXML
    private JFXComboBox JCB_outputFormat;

    @FXML
    private JFXComboBox JCB_textEncoding;

    @FXML
    private JFXComboBox JCB_keyFormat;

    @FXML
    private void initialize() {
        AP_option.setVisible(false);
        initButtonOption();
        initComboBoxes();
    }

    @FXML
    public void ONClick_JBT_enCode() {
        setOptions();
    }

    @FXML
    public void ONClick_JBT_deCode() {
        setOptions();
    }

    @FXML
    public void ONClick_JBT_option() {
    // optionPaneAnime(AP_OPTION_STATES);
    }

    @FXML
    public void ONCheck_JCB_Item_NoPadding() {
        if (JCB_paddingMode.getValue().equals("NoPadding")) {
            ViewUtils.alertPane((Stage) JCB_paddingMode.getScene().getWindow(), Init.languageResourceBundle.getString("Warning"), Init.languageResourceBundle.getString("AES_NOPadding_Waring"));
        }
    }

    public void initButtonOption() {
        JBT_option.setGraphic(new ImageView(new Image(this.getClreplaced().getResourcereplacedtream("/img/settings-5-fill.png"))));
    }

    public void initComboBoxes() {
        JCB_encryptMode.gereplacedems().addAll("ECB", "CBC");
        JCB_encryptMode.setValue("ECB");
        JCB_paddingMode.gereplacedems().addAll("PKCS5", "PKCS7", "NoPadding");
        JCB_paddingMode.setValue("PKCS5");
        JCB_outputFormat.gereplacedems().addAll("Base64", "HEX");
        JCB_outputFormat.setValue("HEX");
        JCB_keyFormat.gereplacedems().addAll("Text", "Base64", "HEX");
        JCB_keyFormat.setValue("Text");
        ViewInit.comboBoxCharset(JCB_textEncoding);
    }

    public void optionPaneAnime(Integer states) {
        Timeline timeLine = new Timeline();
        KeyFrame kf_AP_Start;
        KeyFrame kf_AP_Stop;
        KeyFrame kf_BT_Start;
        KeyFrame kf_BT_Stop;
        if (states == 0) {
            kf_AP_Start = new KeyFrame(Duration.seconds(0), "Start", event -> AP_option.setVisible(true), new KeyValue(AP_option.scaleYProperty(), 610));
            kf_AP_Stop = new KeyFrame(Duration.seconds(0.4), "Stop", event -> {
            }, new KeyValue(AP_option.layoutXProperty(), 455));
            kf_BT_Start = new KeyFrame(Duration.seconds(0), "Start", event -> {
            }, new KeyValue(JBT_option.layoutXProperty(), 570));
            kf_BT_Stop = new KeyFrame(Duration.seconds(0.4), "Stop", event -> {
            }, new KeyValue(JBT_option.layoutXProperty(), 410));
            timeLine.getKeyFrames().addAll(kf_AP_Start, kf_AP_Stop, kf_BT_Start, kf_BT_Stop);
            AP_OPTION_STATES = 1;
        } else {
            kf_AP_Start = new KeyFrame(Duration.seconds(0), "Start", event -> {
            }, new KeyValue(AP_option.layoutXProperty(), 455));
            kf_AP_Stop = new KeyFrame(Duration.seconds(0.4), "Stop", event -> {
            }, new KeyValue(AP_option.layoutXProperty(), 610));
            kf_BT_Start = new KeyFrame(Duration.seconds(0), "Start", event -> {
            }, new KeyValue(JBT_option.layoutXProperty(), 410));
            kf_BT_Stop = new KeyFrame(Duration.seconds(0.4), "Stop", event -> AP_option.setVisible(false), new KeyValue(JBT_option.layoutXProperty(), 570));
            timeLine.getKeyFrames().addAll(kf_AP_Start, kf_AP_Stop, kf_BT_Start, kf_BT_Stop);
            AP_OPTION_STATES = 0;
        }
        timeLine.play();
    }

    public void keyCheck(String key, String charset) {
        // // TODO: 2020/11/27
        if (aesControlList.getKEY_FORMAT().equals("HEX")) {
            try {
                Hex.decodeHex(key.toCharArray());
            } catch (DecoderException e) {
                e.printStackTrace();
            }
        } else if (aesControlList.getKEY_FORMAT().equals("Base64")) {
        } else {
        }
    }

    public void setOptions() {
        aesControlList.setKEY_FORMAT(JCB_keyFormat.getValue().toString());
        aesControlList.setENCRYPT_MODE(JCB_encryptMode.getValue().toString());
        aesControlList.setPADDING_MODE(JCB_paddingMode.getValue().toString());
        aesControlList.setOUTPUT_FORMAT(JCB_outputFormat.getValue().toString());
        aesControlList.setTEXT_ENCODING(JCB_textEncoding.getValue().toString());
    }
}

15 Source : ViewInit.java
with MIT License
from ffffffff0x

// combobox添加字符集选项
public static void comboBoxSplit(JFXComboBox JCB_temp) {
    JCB_temp.gereplacedems().addAll(Init.languageResourceBundle.getString("Space_separation"), Init.languageResourceBundle.getString("Line_break"), Init.languageResourceBundle.getString("Semicolon_separated"), Init.languageResourceBundle.getString("Colon_separated"), Init.languageResourceBundle.getString("Comma_separated"), Init.languageResourceBundle.getString("0x_seperated"), Init.languageResourceBundle.getString("%_Separation"), Init.languageResourceBundle.getString("$_separation"), Init.languageResourceBundle.getString("Double_space_separation"), Init.languageResourceBundle.getString("Double_line_break"), Init.languageResourceBundle.getString("Double_semicolon_separated"), Init.languageResourceBundle.getString("Double_colon_separated"), Init.languageResourceBundle.getString("Double_comma_separated"));
    JCB_temp.setValue(Init.languageResourceBundle.getString("Space_separation"));
    JCB_temp.setVisibleRowCount(6);
}

15 Source : PersonLayoutController.java
with MIT License
from FabioAugustoRodrigues

/**
 * FXML Controller clreplaced
 *
 * @author Fábio Augusto Rodrigues
 */
public clreplaced PersonLayoutController implements Initializable {

    @FXML
    private JFXComboBox<String> attributeList;

    @FXML
    private TextField txtSearch;

    @FXML
    private TableView<Person> personTable;

    @FXML
    private TableColumn<Person, String> columnName;

    @FXML
    private TableColumn<Person, String> columnAddress;

    @FXML
    private TableColumn<Person, String> columnEmail;

    @FXML
    private TableColumn<Person, String> columnNumber;

    @FXML
    private TableColumn<Person, String> columnBirthday;

    @FXML
    private Label lblNote;

    @FXML
    private Label lblError;

    private List<Person> listPerson = new ArrayList();

    private ObservableList<Person> observableListPerson;

    MainApp mainApp;

    @FXML
    void actionRegister(ActionEvent event) {
        if (mainApp.showPersonEditDialog("Register", null)) {
            loadPerson(true);
        }
    }

    @FXML
    void actionUpdate(ActionEvent event) {
        if (personTable.getSelectionModel().getSelectedIndex() > -1) {
            if (mainApp.showPersonEditDialog("Update", personTable.getSelectionModel().getSelectedItem()))
                ;
            loadPerson(true);
        } else {
            if (listPerson.isEmpty()) {
                alert("Error", "There are no records to edit", "Register a new person", Alert.AlertType.ERROR);
            } else {
                alert("Error", "Select a record", "To edit you need to select a record from the table", Alert.AlertType.ERROR);
            }
        }
    }

    @FXML
    void actionDelete(ActionEvent event) {
        if (personTable.getSelectionModel().getSelectedIndex() > -1) {
            Alert dialogoExe = new Alert(Alert.AlertType.CONFIRMATION);
            ButtonType btnYes = new ButtonType("Yes");
            ButtonType btnNoAnswer = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
            dialogoExe.setreplacedle("Attention!");
            dialogoExe.setHeaderText("Inform if you want to delete");
            dialogoExe.setContentText("Delete " + personTable.getSelectionModel().getSelectedItem().getName() + "?");
            dialogoExe.getButtonTypes().setAll(btnYes, btnNoAnswer);
            dialogoExe.showAndWait().ifPresent(b -> {
                if (b == btnYes) {
                    DAO.getInstance().delete(personTable.getSelectionModel().getSelectedItem());
                    loadPerson(true);
                }
            });
        } else {
            if (listPerson.isEmpty()) {
                alert("Error", null, "There are no records to delete", Alert.AlertType.ERROR);
            } else {
                alert("Error", "Select a record", "To delete you need to select a record from the table", Alert.AlertType.ERROR);
            }
        }
    }

    @FXML
    void actionSearch(ActionEvent event) {
        try {
            if (attributeList.getValue().equals("Show everyone")) {
                loadPerson(true);
            } else {
                List<Person> people = new ArrayList();
                switch(attributeList.getValue()) {
                    case "ID":
                        people.add(DAO.getInstance().findById(Integer.parseInt(txtSearch.getText())));
                        break;
                    case "Name":
                        people = DAO.getInstance().findByName(txtSearch.getText());
                        break;
                    case "Address":
                        people = DAO.getInstance().findByAddress(txtSearch.getText());
                        break;
                    case "E-mail":
                        people = DAO.getInstance().findByEmail(txtSearch.getText());
                        break;
                    case "Birthday":
                        people = DAO.getInstance().findByBirthday(txtSearch.getText());
                        break;
                    case "Number":
                        people = DAO.getInstance().findByNumber(txtSearch.getText());
                        break;
                    default:
                        break;
                }
                loadPerson(people);
            }
        } catch (NumberFormatException ime) {
            lblError.setText("Enter the valid value type");
        } catch (NullPointerException npe) {
            lblError.setText("Enter some value");
        }
    }

    @FXML
    void keyPressed(KeyEvent event) {
        lblError.setText("");
    }

    @FXML
    void actionCombobox(ActionEvent event) {
        if (attributeList.getValue().equals("Show everyone")) {
            loadPerson(true);
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        loadPerson(false);
        loadCombobox();
        try {
            personTable.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> showNote(newValue));
            loadAutoComplete();
        } catch (NullPointerException npe) {
            lblNote.setText("");
        }
    }

    public boolean loadPerson(boolean cleanTable) {
        try {
            if (cleanTable) {
                cleanTable();
            }
            definingColumn();
            setListPerson(DAO.getInstance().findAll());
            observableListPerson = FXCollections.observableArrayList(listPerson);
            personTable.sereplacedems(observableListPerson);
        } catch (Exception e) {
            alert("Error", null, "An error occurred while retrieving data", Alert.AlertType.ERROR);
            return false;
        }
        return true;
    }

    public void loadPerson(List<Person> arrayListPerson) {
        try {
            cleanTable();
            observableListPerson = FXCollections.observableArrayList(arrayListPerson);
            personTable.sereplacedems(observableListPerson);
        } catch (Exception e) {
            alert("Error", null, "An error occurred while retrieving data", Alert.AlertType.ERROR);
        }
    }

    public void definingColumn() {
        columnName.setCellValueFactory(new PropertyValueFactory<>("name"));
        columnAddress.setCellValueFactory(new PropertyValueFactory<>("address"));
        columnEmail.setCellValueFactory(new PropertyValueFactory<>("email"));
        columnNumber.setCellValueFactory(new PropertyValueFactory<>("number"));
        columnBirthday.setCellValueFactory(new PropertyValueFactory<>("birthday"));
    }

    private void cleanTable() {
        personTable.gereplacedems().clear();
    }

    private void alert(String replacedulo, String headerText, String contentText, Alert.AlertType type) {
        Alert alert = new Alert(type);
        alert.setreplacedle(replacedulo);
        alert.setHeaderText(headerText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }

    public void loadCombobox() {
        List<String> values = new ArrayList();
        values.add("Show everyone");
        values.add("ID");
        values.add("Name");
        values.add("Address");
        values.add("Birthday");
        values.add("E-mail");
        values.add("Number");
        ObservableList<String> obsValues = FXCollections.observableArrayList(values);
        attributeList.sereplacedems(obsValues);
    }

    public void loadAutoComplete() {
        // Variables for autosuggestion :)
        AutoCompletionBinding<String> acb;
        Set<String> ps;
        ArrayList<String> values = new ArrayList();
        for (int i = 0; i < listPerson.size(); i++) {
            values.add(listPerson.get(i).getName());
            values.add(listPerson.get(i).getAddress());
            values.add(listPerson.get(i).getEmail());
            values.add(listPerson.get(i).getBirthday());
            values.add(listPerson.get(i).getNumber());
        }
        String[] _possibleSuggestions = values.toArray(new String[0]);
        ps = new HashSet<>(Arrays.asList(_possibleSuggestions));
        TextFields.bindAutoCompletion(txtSearch, _possibleSuggestions);
    }

    public void showNote(Person person) {
        lblNote.setText(person.getNote());
    }

    public List<Person> getListPerson() {
        return listPerson;
    }

    public void setListPerson(List<Person> listPerson) {
        this.listPerson = listPerson;
    }

    public MainApp getMainApp() {
        return mainApp;
    }

    public void setMainApp(MainApp mainApp) {
        this.mainApp = mainApp;
    }
}

15 Source : RegisterController.java
with Mozilla Public License 2.0
from aesophor

public clreplaced RegisterController implements Initializable {

    @FXML
    private JFXTextField usernameField;

    @FXML
    private JFXTextField fullnameField;

    @FXML
    private JFXPreplacedwordField preplacedwordField;

    @FXML
    private JFXComboBox gradYearBox;

    @FXML
    private JFXButton registerBtn;

    @FXML
    private Label warningMsg;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initGradYearBox(108, 120);
    }

    public void register(ActionEvent e) {
        if (!isFormValid()) {
            warningMsg.setText("Please fill out all the required fields.");
            return;
        }
        String username = usernameField.getText();
        String fullname = fullnameField.getText();
        String preplacedword = preplacedwordField.getText();
        Integer gradYear = (Integer) gradYearBox.getSelectionModel().getSelectedItem();
        try {
            Response register = User.register(username, preplacedword, fullname, gradYear);
            if (register.success()) {
                back(new ActionEvent());
            } else {
                StatusCode statusCode = register.getStatusCode();
                switch(statusCode) {
                    case ALREADY_REGISTERED:
                        warningMsg.setText("An account already exists with this username.");
                        break;
                    default:
                        warningMsg.setText("An error has occurred. Please contact the admin.");
                        break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void back(ActionEvent e) {
        String registerFXML = FXMLTable.getInstance().get("Login");
        Utils.showStage(new FXMLLoader(getClreplaced().getResource(registerFXML)));
        registerBtn.getScene().getWindow().hide();
    }

    public void clearWarningMsg(KeyEvent event) {
        warningMsg.setText("");
    }

    private void initGradYearBox(int min, int max) {
        for (int i = min; i < max; i++) {
            gradYearBox.gereplacedems().addAll(i);
        }
    }

    private boolean isFormValid() {
        String username = usernameField.getText();
        String fullname = fullnameField.getText();
        String preplacedword = preplacedwordField.getText();
        Object gradYear = gradYearBox.getSelectionModel().getSelectedItem();
        return !(username == null | username.isEmpty() | fullname == null | fullname.isEmpty() | preplacedword == null | preplacedword.isEmpty() | gradYear == null);
    }
}

14 Source : ExportDialog.java
with MIT License
from warmuuh

public clreplaced ExportDialog<T> {

    VBox exportArea;

    JFXComboBox<Exporter<T>> exportSelector;

    JFXButton exportBtn;

    private Dialog dialog;

    private Exporter<T> selectedExporter = null;

    private Toaster toaster;

    private T objToExport;

    private Templater templater;

    public void showAndWait(List<Exporter<T>> exporters, Templater templater, Toaster toaster, T objToExport) {
        this.templater = templater;
        this.toaster = toaster;
        this.objToExport = objToExport;
        JFXDialogLayout content = new ExportDialogFxml(this);
        exportSelector.setPromptText("Select Exporter");
        exporters.forEach(exportSelector.gereplacedems()::add);
        exportSelector.setConverter(new StringConverter<Exporter<T>>() {

            @Override
            public String toString(Exporter<T> object) {
                return object.getName();
            }

            @Override
            public Exporter<T> fromString(String string) {
                return null;
            }
        });
        exportSelector.getSelectionModel().selectedItemProperty().addListener((obs, o, v) -> {
            if (o != v && v != null) {
                selectedExporter = v;
                exportArea.getChildren().clear();
                exportArea.getChildren().add(v.getRoot(objToExport, templater));
                exportBtn.setDisable(v.isAdhocExporter());
            }
        });
        dialog = FxmlUtil.createDialog(content);
        dialog.showAndWait();
    }

    public void onClose() {
        dialog.close();
    }

    public void onExport() {
        if (selectedExporter != null) {
            if (selectedExporter.doExport(objToExport, templater, toaster)) {
                dialog.close();
            }
        }
    }

    public clreplaced ExportDialogFxml extends JFXDialogLayout {

        public ExportDialogFxml(ExportDialog controller) {
            setHeading(label("Export"));
            var vbox = new FxmlBuilder.VboxExt();
            controller.exportSelector = vbox.add(new JFXComboBox());
            controller.exportArea = vbox.add(vbox("exportArea"));
            setBody(vbox);
            controller.exportBtn = submit(controller::onExport, "Export");
            setActions(controller.exportBtn, cancel(controller::onClose, "Close"));
        }
    }
}

14 Source : ServiceOverviewFoundViewController.java
with MIT License
from ThijsZijdel

/**
 * FXML Controller clreplaced
 *
 * @author Thijs Zijdel - 500782165
 */
public clreplaced ServiceOverviewFoundViewController implements Initializable, FoundLuggageTable, Search {

    /**
     * View replacedle
     */
    private final String replacedLE = "Overview Found Luggage";

    private final String replacedLE_DUTCH = "Overzicht gevonden bagage";

    // stage for more details when double clicking on a table item
    private final Stage POPUP_STAGE_FOUND = new Stage();

    // list for the search results
    private static ObservableList<FoundLuggage> foundLuggageListSearchResults = FXCollections.observableArrayList();

    // text field for the users search input
    @FXML
    JFXTextField searchField;

    // combo box for a type/field/column search filter
    @FXML
    JFXComboBox searchTypeComboBox;

    // Object for getting the data
    private ServiceDataFound dataListFound;

    // show alos matched luggage state, by default on false
    private boolean showMatchedLuggage = false;

    // resultSet for the items when changing the state of the showMatchedLuggage
    private ResultSet matchedLuggageResultSet;

    // click counts
    private final int DOUBLE_CLICK = 2;

    /* -----------------------------------------
         TableView found luggage's colommen
    ----------------------------------------- */
    @FXML
    private TableView<FoundLuggage> foundLuggageTable;

    @FXML
    private TableColumn<FoundLuggage, String> foundRegistrationNr;

    @FXML
    private TableColumn<FoundLuggage, String> foundDateFound;

    @FXML
    private TableColumn<FoundLuggage, String> foundTimeFound;

    @FXML
    private TableColumn<FoundLuggage, String> foundLuggageTag;

    @FXML
    private TableColumn<FoundLuggage, String> foundLuggageType;

    @FXML
    private TableColumn<FoundLuggage, String> foundBrand;

    @FXML
    private TableColumn<FoundLuggage, String> foundMainColor;

    @FXML
    private TableColumn<FoundLuggage, String> foundSecondColor;

    @FXML
    private TableColumn<FoundLuggage, String> foundSize;

    @FXML
    private TableColumn<FoundLuggage, Integer> foundWeight;

    @FXML
    private TableColumn<FoundLuggage, String> foundOtherCharacteristics;

    @FXML
    private TableColumn<FoundLuggage, Integer> foundPreplacedengerId;

    @FXML
    private TableColumn<FoundLuggage, String> foundArrivedWithFlight;

    @FXML
    private TableColumn<FoundLuggage, Integer> foundLocationFound;

    @FXML
    private TableColumn<FoundLuggage, Integer> foundMatchedId;

    /**
     * Initializes the controller clreplaced that adds all the needed functionality,
     * to the: ServiceOverviewFoundView.FXML view.
     *
     * @param url location  used to resolve relative paths for the root object
     * @param rb resources   used to localize the root object
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // for setting the resource bundle
        MainApp.currentView = "/Views/Service/ServiceOverviewFoundView.fxml";
        // set the view's replacedle, and catch a possible IOException
        try {
            if (MainApp.language.equals("dutch")) {
                MainViewController.getInstance().getreplacedle(replacedLE_DUTCH);
            } else {
                MainViewController.getInstance().getreplacedle(replacedLE);
            }
        } catch (IOException ex) {
            Logger.getLogger(OverviewUserController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        // so the user can change the filter
        initializeComboFilterBox();
        // try to initialize and set the found luggage table
        try {
            // Initialize Table & obj found
            dataListFound = new ServiceDataFound();
            initializeFoundLuggageTable();
            // set the table with the right data
            setFoundLuggageTable(dataListFound.getFoundLuggage());
        } catch (SQLException ex) {
            Logger.getLogger(ServiceOverviewFoundViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        // set screen status
        ServiceHomeViewController.setOnMatchingView(false);
    }

    /**
     * This method is for initializing the filter combo box
     * The comboBox is used for filtering to a specific:
     *                                               column/ field/ detail
     *                                                          When searching.
     * @void - No direct output
     */
    private void initializeComboFilterBox() {
        // add all the filterable fields
        searchTypeComboBox.gereplacedems().addAll("All fields", "RegistrationNr", "LuggageTag", "Brand", "Color", "Weight", "Date", "Preplacedenger", "Location", "Characteristics");
        // set the standard start value to all fields
        searchTypeComboBox.setValue("All fields");
    }

    /**
     * This method is for toggle showing only the matched luggage
     * Note: this is being called by the -fx- toggle button
     *
     * @throws java.sql.SQLException        getting data from the database
     * @void - No direct output             only changing results in the table
     */
    @FXML
    protected void showOnlyMatchedLuggage() throws SQLException {
        // if state of show only matched is false
        if (showMatchedLuggage == false) {
            // set it to trough
            showMatchedLuggage = true;
            // asign the right resultset to the matchedLuggageResultSet
            // note: this is based on the boolean status that's set previously
            matchedLuggageResultSet = dataListFound.getFoundResultSet(showMatchedLuggage);
            // set the table with the right data, the resultset will be converted
            setFoundLuggageTable(dataListFound.getObservableList(matchedLuggageResultSet));
        // if the state of only matched was already true
        } else if (showMatchedLuggage == true) {
            // set the state to false, so only non matched luggage's are shown
            showMatchedLuggage = false;
            // asign the right resultset to the matchedLuggageResultSet
            // note: this is based on the boolean status that's set previously
            matchedLuggageResultSet = dataListFound.getFoundResultSet(showMatchedLuggage);
            // set the table with the right data, the resultset will be converted
            setFoundLuggageTable(dataListFound.getObservableList(matchedLuggageResultSet));
        }
    }

    /**
     * This method is for searching in the table
     * There will be searched on the typed user input and filter value
     * Note: this method is called after each time the user releases a key
     *
     * @throws java.sql.SQLException        searching in the database
     * @void - No direct output             only changing results in the table
     * @call - getSearchQuery               for getting the search query
     * @call - executeResultSetQuery        for getting the resultSet
     * @call - getFoundLuggageSearchList    the result list based on the resultSet
     */
    @FXML
    @Override
    public void search() throws SQLException {
        // get the value of the search type combo box for filtering to a specific column
        String value = searchTypeComboBox.getValue().toString();
        // get the user input for the search
        String search = searchField.getText();
        // Create a new searchData object
        ServiceSearchData searchData = new ServiceSearchData();
        // Get the right query based on the users input
        String finalQuery = searchData.getSearchQuery(value, search, "foundluggage");
        // clear the previous search result list
        foundLuggageListSearchResults.clear();
        // try to execute the query from the database
        // @throws SQLException
        try {
            // get the connection to the datbase
            MyJDBC db = MainApp.getDatabase();
            // create a new resultSet and execute the right query
            ResultSet resultSet = db.executeResultSetQuery(finalQuery);
            // get the observableList from the search object and asign this to the list
            foundLuggageListSearchResults = ServiceDataFound.loopTroughResultSet(resultSet, showMatchedLuggage);
            // set this list on the table
            foundLuggageTable.sereplacedems(foundLuggageListSearchResults);
            // set the right place holder message for when there are no hits
            foundLuggageTable.setPlaceholder(new Label("No hits based on your search"));
        } catch (SQLException ex) {
            Logger.getLogger(ServiceOverviewFoundViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Here is found luggage table overview initialized with the right values
     *
     * @void - No direct output
     */
    @Override
    public void initializeFoundLuggageTable() {
        foundRegistrationNr.setCellValueFactory(new PropertyValueFactory<>("registrationNr"));
        foundDateFound.setCellValueFactory(new PropertyValueFactory<>("dateFound"));
        foundTimeFound.setCellValueFactory(new PropertyValueFactory<>("timeFound"));
        foundLuggageTag.setCellValueFactory(new PropertyValueFactory<>("luggageTag"));
        foundLuggageType.setCellValueFactory(new PropertyValueFactory<>("luggageType"));
        foundBrand.setCellValueFactory(new PropertyValueFactory<>("brand"));
        foundMainColor.setCellValueFactory(new PropertyValueFactory<>("mainColor"));
        foundSecondColor.setCellValueFactory(new PropertyValueFactory<>("secondColor"));
        foundSize.setCellValueFactory(new PropertyValueFactory<>("size"));
        foundWeight.setCellValueFactory(new PropertyValueFactory<>("weight"));
        foundOtherCharacteristics.setCellValueFactory(new PropertyValueFactory<>("otherCharacteristics"));
        foundPreplacedengerId.setCellValueFactory(new PropertyValueFactory<>("preplacedengerId"));
        foundArrivedWithFlight.setCellValueFactory(new PropertyValueFactory<>("arrivedWithFlight"));
        foundLocationFound.setCellValueFactory(new PropertyValueFactory<>("locationFound"));
        foundMatchedId.setCellValueFactory(new PropertyValueFactory<>("matchedId"));
        // set place holder text when there are no results
        foundLuggageTable.setPlaceholder(new Label("No found luggage's to display"));
    }

    /**
     * Here will the found luggage table be set with the right data
     * The data (observable< foundluggage>list) comes from the dataListFound
     *
     * @param list
     * @void - No direct output
     * @call - set foundLuggageTable
     */
    @Override
    public void setFoundLuggageTable(ObservableList<FoundLuggage> list) {
        foundLuggageTable.sereplacedems(list);
    }

    /**
     * Here is checked of a row in the found luggage table is clicked
     * If this is the case, two functions will be activated.
     *
     * @void - No direct output
     * @call - setDetailsOfRow           set the details of the clicked row
     * @call - setAndOpenPopUpDetails    opens the right more details pop up
     */
    public void foundRowClicked() {
        foundLuggageTable.setOnMousePressed((MouseEvent event) -> {
            // --> event         //--> double click
            if (event.isPrimaryButtonDown() && event.getClickCount() == DOUBLE_CLICK) {
                // Make a more details object called foundDetails.
                ServiceMoreDetails foundDetails = new ServiceMoreDetails();
                // Set the detailes of the clicked row and preplaced a stage and link
                foundDetails.setDetailsOfRow("found", event, POPUP_STAGE_FOUND, "/Views/Service/ServiceDetailedFoundLuggageView.fxml");
                // Open the more details pop up.
                foundDetails.setAndOpenPopUpDetails(POPUP_STAGE_FOUND, "/Views/Service/ServiceDetailedFoundLuggageView.fxml", "found");
            }
        });
    }

    /*--------------------------------------------------------------------------
                              Switch view buttons
    --------------------------------------------------------------------------*/
    @FXML
    protected void switchToInput(ActionEvent event) throws IOException {
        MainApp.switchView("/Views/Service/ServiceInputLuggageView.fxml");
    }

    @FXML
    protected void switchToMatching(ActionEvent event) throws IOException {
        MainApp.switchView("/Views/Service/ServiceMatchingView.fxml");
    }
}

14 Source : ManagerLostViewController.java
with MIT License
from ThijsZijdel

/**
 * FXML Controller clreplaced
 *
 * @author Ahmet
 * @author Thijs Zijdel - 500782165
 */
public clreplaced ManagerLostViewController implements Initializable, LostLuggageTable, Search {

    // view replacedle
    private final String replacedLE = "Overview Lost Luggage";

    private final String replacedLE_DUTCH = "Overzicht verloren bagage";

    // list of luggages for the lostTable
    public static ObservableList<LostLuggage> lostLuggageList;

    // double click
    private final int DOUBLE_CLICK = 2;

    // table view for the data
    @FXML
    private TableView<LostLuggage> lostTable;

    // TableView found luggage's colommen
    @FXML
    private TableColumn<LostLuggage, String> managerLostRegistrationNr;

    @FXML
    private TableColumn<LostLuggage, String> managerLostDateLost;

    @FXML
    private TableColumn<LostLuggage, String> managerLostTimeLost;

    @FXML
    private TableColumn<LostLuggage, String> managerLostLuggageTag;

    @FXML
    private TableColumn<LostLuggage, String> managerLostLuggageType;

    @FXML
    private TableColumn<LostLuggage, String> managerLostBrand;

    @FXML
    private TableColumn<LostLuggage, Integer> managerLostMainColor;

    @FXML
    private TableColumn<LostLuggage, String> managerLostSecondColor;

    @FXML
    private TableColumn<LostLuggage, Integer> managerLostSize;

    @FXML
    private TableColumn<LostLuggage, String> managerLostWeight;

    @FXML
    private TableColumn<LostLuggage, String> managerLostOtherCharacteristics;

    @FXML
    private TableColumn<LostLuggage, Integer> managerLostPreplacedengerId;

    @FXML
    private TableColumn<LostLuggage, String> managerLostFlight;

    @FXML
    private TableColumn<LostLuggage, String> managerLostEmployeeId;

    @FXML
    private TableColumn<LostLuggage, Integer> managerLostMatchedId;

    // list for the search results
    private static ObservableList<LostLuggage> lostLuggageListSearchResults = FXCollections.observableArrayList();

    // text field for the users search input
    @FXML
    JFXTextField searchField;

    // combo box for a type/field/column search filter
    @FXML
    JFXComboBox searchTypeComboBox;

    // Object for getting the data
    private ServiceDataLost dataListLost;

    // show alos matched luggage state, by default on false
    private boolean showMatchedLuggage = false;

    // resultSet for the items when changing the state of the showMatchedLuggage
    private ResultSet matchedLuggageResultSet;

    // date filter (from - to)
    @FXML
    JFXDatePicker fromDate;

    @FXML
    JFXDatePicker toDate;

    // display labels
    // results based on the filters set/ search and the total count of lost luggages
    @FXML
    private Label results;

    @FXML
    private Label total;

    /**
     * @author Thijs Zijdel - 500782165
     *
     * Initializing the controller clreplaced for the manager lost view
     *
     * @param url
     * @param rb
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // To Previous Scene
        MainViewController.previousView = "/Views/ManagerHomeView.fxml";
        // set view replacedle
        try {
            if (MainApp.language.equals("dutch")) {
                MainViewController.getInstance().getreplacedle(replacedLE_DUTCH);
            } else {
                MainViewController.getInstance().getreplacedle(replacedLE);
            }
        } catch (IOException ex) {
            Logger.getLogger(OverviewUserController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        // initialize the filter (for columns/fields) combo box with data
        initializeComboFilterBox();
        // initialize the table so it can be set
        initializeLostLuggageTable();
        // try to set the lost luggage table with data
        try {
            // Initialize Table & obj lost
            dataListLost = new ServiceDataLost();
            setLostLuggageTable(dataListLost.getLostLuggage());
            // initialize the total amount of luggage s in the right display
            initializeTotalCountDisplay();
        } catch (SQLException ex) {
            Logger.getLogger(ManagerLostViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        // initialize the click listner for double clicking the table
        initializeOnLostRowDoubleClicked();
        // initialize the total amount results in the right display
        setResultCount();
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * This method is for toggle showing only the matched luggage
     * Note: this is being called by the -fx- toggle button
     *
     * @throws java.sql.SQLException        getting data from the database
     * @void - No direct output             only changing results in the table
     */
    @FXML
    protected void showOnlyMatchedLuggage() throws SQLException {
        // if state of show only matched is false
        if (showMatchedLuggage == false) {
            // set it to true
            showMatchedLuggage = true;
            // asign the right resultset to the matchedLuggageResultSet
            // note: this is based on the boolean status that's set previously
            matchedLuggageResultSet = dataListLost.getLostResultSet(showMatchedLuggage);
            // set the table with the right data, the resultset will be converted
            setLostLuggageTable(dataListLost.getObservableList(matchedLuggageResultSet));
            // Reset the date picker since it is not configured with the only matched
            resetDatePickerFilter();
            // set result count in the display label
            setResultCount();
        // if the state of only matched was already true
        } else if (showMatchedLuggage == true) {
            // set the state to false, so only non matched luggage's are shown
            showMatchedLuggage = false;
            // asign the right resultset to the matchedLuggageResultSet
            // note: this is based on the boolean status that's set previously
            matchedLuggageResultSet = dataListLost.getLostResultSet(showMatchedLuggage);
            // set the table with the right data, the resultset will be converted
            setLostLuggageTable(dataListLost.getObservableList(matchedLuggageResultSet));
            // set result count in the display label
            setResultCount();
        }
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * Here is lost luggage table overview initialized with the right values
     *
     * @void - No direct output
     */
    @Override
    public void initializeLostLuggageTable() {
        managerLostRegistrationNr.setCellValueFactory(new PropertyValueFactory<>("registrationNr"));
        managerLostDateLost.setCellValueFactory(new PropertyValueFactory<>("dateLost"));
        managerLostTimeLost.setCellValueFactory(new PropertyValueFactory<>("timeLost"));
        managerLostLuggageTag.setCellValueFactory(new PropertyValueFactory<>("luggageTag"));
        managerLostLuggageType.setCellValueFactory(new PropertyValueFactory<>("luggageType"));
        managerLostBrand.setCellValueFactory(new PropertyValueFactory<>("brand"));
        managerLostMainColor.setCellValueFactory(new PropertyValueFactory<>("mainColor"));
        managerLostSecondColor.setCellValueFactory(new PropertyValueFactory<>("secondColor"));
        managerLostSize.setCellValueFactory(new PropertyValueFactory<>("size"));
        managerLostWeight.setCellValueFactory(new PropertyValueFactory<>("weight"));
        managerLostOtherCharacteristics.setCellValueFactory(new PropertyValueFactory<>("otherCharacteristics"));
        managerLostPreplacedengerId.setCellValueFactory(new PropertyValueFactory<>("preplacedengerId"));
        managerLostFlight.setCellValueFactory(new PropertyValueFactory<>("flight"));
        managerLostEmployeeId.setCellValueFactory(new PropertyValueFactory<>("employeeId"));
        managerLostMatchedId.setCellValueFactory(new PropertyValueFactory<>("matchedId"));
        // set place holder text when there are no results
        lostTable.setPlaceholder(new Label("No lost luggage's to display"));
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * Here will the lost luggage table be set with the right data
     * The data (observable< lostluggage>list) comes from the dataListLost
     *
     * @param list
     * @void - No direct output
     * @call - set lostLuggageTable
     */
    @Override
    public void setLostLuggageTable(ObservableList<LostLuggage> list) {
        lostTable.sereplacedems(list);
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * This method is for initializing the filter combo box
     * The comboBox is used for filtering to a specific:
     *                                               column/ field/ detail
     *                                                          When searching.
     * @void - No direct output
     */
    private void initializeComboFilterBox() {
        // add all the filterable fields
        searchTypeComboBox.gereplacedems().addAll("All fields", "RegistrationNr", "LuggageTag", "Brand", "Color", "Weight", "Date", "Preplacedenger", "Characteristics");
        // set the standard start value to all fields
        searchTypeComboBox.setValue("All fields");
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * This method is for searching in the table
     * There will be searched on the typed user input and filter value
     * Note: this method is called after each time the user releases a key
     *
     * @throws java.sql.SQLException        searching in the database
     * @void - No direct output             only changing results in the table
     * @call - getSearchQuery               for getting the search query
     * @call - executeResultSetQuery        for getting the resultSet
     * @call - getLostLuggageSearchList     the result list based on the resultSet
     */
    @FXML
    @Override
    public void search() throws SQLException {
        // get the value of the search type combo box for filtering to a specific column
        String value = searchTypeComboBox.getValue().toString();
        // get the user input for the search
        String search = searchField.getText();
        // Create a new searchData object
        ServiceSearchData searchData = new ServiceSearchData();
        // Get the right query based on the users input
        String finalQuery = searchData.getSearchQuery(value, search, "lostluggage");
        // get the final query without the last semicolin to extend it
        finalQuery = finalQuery.substring(0, finalQuery.lastIndexOf(";"));
        // check if there is a filter based on FROM date.
        if (fromDate.getValue() != null && !fromDate.getValue().toString().isEmpty()) {
            // If the final qeury doesn't have any statments, add WHERE
            if (!finalQuery.contains("WHERE")) {
                finalQuery += " WHERE ";
            } else {
                // If the final qeury already contains statments, add a AND
                finalQuery += " AND ";
            }
            // add the filter from TO the query
            finalQuery += " L.dateLost > '" + fromDate.getValue().toString() + "' ";
        }
        // check if there is a filter based on TO date.
        if (toDate.getValue() != null && !toDate.getValue().toString().isEmpty()) {
            // If the final qeury doesn't have any statments, add WHERE
            if (!finalQuery.contains("WHERE")) {
                finalQuery += " WHERE ";
            } else {
                // If the final qeury already contains statments, add a AND
                finalQuery += " AND ";
            }
            // als er maar een where en geen or bevat + and
            // if (finalQuery.contains("WHERE") && )
            // add the filter from FROM the query
            finalQuery += " L.dateLost < '" + toDate.getValue().toString() + "' ";
        }
        // close the query
        finalQuery += ";";
        // clear the previous search result list
        lostLuggageListSearchResults.clear();
        // try to execute the query from the database
        // @throws SQLException
        try {
            // get the connection to the datbasec
            MyJDBC db = MainApp.getDatabase();
            // create a new resultSet and execute tche right query
            ResultSet resultSet = db.executeResultSetQuery(finalQuery);
            // get the observableList from the search object and asign this to the list
            lostLuggageListSearchResults = ServiceDataLost.loopTroughResultSet(resultSet, showMatchedLuggage);
            // set this list on the table
            lostTable.sereplacedems(lostLuggageListSearchResults);
            // set the right place holder message for when there are no hits
            lostTable.setPlaceholder(new Label("No hits based on your search"));
            // set result count in the display label
            setResultCount();
        } catch (SQLException ex) {
            Logger.getLogger(ManagerLostViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * This method is for setting the total amount of lost luggage s in the db
     * This data will be gotten from a count query in the ServiceGetDataFromDB clreplaced
     *
     * Note: this method is called when initializing the controller
     */
    private void initializeTotalCountDisplay() throws SQLException {
        // create a ServiceGetDataFromDB object with the right fields
        // table: lostluggage   field: * (=all)  where: null (no statement)
        ServiceGetDataFromDB totalCount = new ServiceGetDataFromDB("lostluggage", "*", null);
        // set the total of hits in the total (label) display
        total.setText(Integer.toString(totalCount.countHits()));
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * This method is for setting the amount of results in the display
     * Note: this method is called when initializing the controller and searching
     */
    private void setResultCount() {
        // get the amount of items in the lost luggage table
        String hits = Integer.toString(lostTable.gereplacedems().size());
        // if the amount of hits is zero, set it to 0 (to display)
        if (hits == null || "".equals(hits) || lostTable.gereplacedems().isEmpty()) {
            hits = "0";
        }
        // set the amount of hits in the results (label) display.
        results.setText(hits);
    }

    /**
     * @author Ahmet Aksu
     */
    private void initializeOnLostRowDoubleClicked() {
        // method made by Ahmet Aksu, for making the lostTable double click'able
        lostTable.setOnMousePressed((MouseEvent event) -> {
            if (event.isPrimaryButtonDown() && event.getClickCount() == DOUBLE_CLICK) {
                Node node = ((Node) event.getTarget()).getParent();
                TableRow row;
                if (node instanceof TableRow) {
                    row = (TableRow) node;
                } else {
                    // clicking on text part
                    row = (TableRow) node.getParent();
                }
                System.out.println(row.gereplacedem());
                try {
                    MainApp.switchView("/Views/ManagerPreplacedengerInfoView.fxml");
                } catch (IOException ex) {
                    Logger.getLogger(ManagerLostViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    /**
     * This method is for clearing (resetting) the date picker filters
     * Note; i didn't had enough time to also configure this with showing only the matched luggage
     */
    private void resetDatePickerFilter() {
        toDate.setValue(null);
        fromDate.setValue(null);
    }
}

14 Source : ManagerFoundViewController.java
with MIT License
from ThijsZijdel

/**
 * FXML Controller clreplaced
 *
 * @author Ahmet
 * @author Thijs Zijdel - 500782165             For the search functionality
 */
public clreplaced ManagerFoundViewController implements Initializable, FoundLuggageTable, Search {

    // view replacedle
    private final String replacedLE = "Overview Found Luggage";

    private final String replacedLE_DUTCH = "Overzicht gevonden bagage";

    // list of luggages for the lostTable
    public static ObservableList<FoundLuggage> foundLuggageList;

    // double click
    private final int DOUBLE_CLICK = 2;

    @FXML
    private TableView<FoundLuggage> foundLuggage;

    @FXML
    private TableColumn<FoundLuggage, String> managerFoundRegistrationNr;

    @FXML
    private TableColumn<FoundLuggage, String> found_dateFound;

    @FXML
    private TableColumn<FoundLuggage, String> found_timeFound;

    @FXML
    private TableColumn<FoundLuggage, String> found_luggageTag;

    @FXML
    private TableColumn<FoundLuggage, String> found_luggageType;

    @FXML
    private TableColumn<FoundLuggage, String> found_brand;

    @FXML
    private TableColumn<FoundLuggage, Integer> found_mainColor;

    @FXML
    private TableColumn<FoundLuggage, String> found_secondColor;

    @FXML
    private TableColumn<FoundLuggage, Integer> found_size;

    @FXML
    private TableColumn<FoundLuggage, String> found_weight;

    @FXML
    private TableColumn<FoundLuggage, String> found_otherCharacteristics;

    @FXML
    private TableColumn<FoundLuggage, Integer> found_preplacedengerId;

    @FXML
    private TableColumn<FoundLuggage, String> found_arrivedWithFlight;

    @FXML
    private TableColumn<FoundLuggage, Integer> found_locationFound;

    @FXML
    private TableColumn<FoundLuggage, String> found_employeeId;

    @FXML
    private TableColumn<FoundLuggage, Integer> found_matchedId;

    // list for the search results
    private static ObservableList<FoundLuggage> foundLuggageListSearchResults = FXCollections.observableArrayList();

    // text field for the users search input
    @FXML
    JFXTextField searchField;

    // combo box for a type/field/column search filter
    @FXML
    JFXComboBox searchTypeComboBox;

    // Object for getting the data
    private ServiceDataFound dataListFound;

    // show alos matched luggage state, by default on false
    private boolean showMatchedLuggage = false;

    // resultSet for the items when changing the state of the showMatchedLuggage
    private ResultSet matchedLuggageResultSet;

    // date filter (from - to)
    @FXML
    JFXDatePicker fromDate;

    @FXML
    JFXDatePicker toDate;

    // display labels
    // results based on the filters set/ search and the total count of found luggages
    @FXML
    private Label results;

    @FXML
    private Label total;

    /**
     * @author Thijs Zijdel - 500782165
     *
     * Initializing the controller clreplaced for the manager found view
     *
     * @param url
     * @param rb
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // To Previous Scene
        MainViewController.previousView = "/Views/ManagerHomeView.fxml";
        // set view replacedle
        try {
            if (MainApp.language.equals("dutch")) {
                MainViewController.getInstance().getreplacedle(replacedLE_DUTCH);
            } else {
                MainViewController.getInstance().getreplacedle(replacedLE);
            }
        } catch (IOException ex) {
            Logger.getLogger(OverviewUserController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        // initialize the filter (for columns/fields) combo box with data
        initializeComboFilterBox();
        // initialize the table so it can be set
        initializeFoundLuggageTable();
        // try to set the found luggage table with data
        try {
            // Initialize Table & obj found
            dataListFound = new ServiceDataFound();
            setFoundLuggageTable(dataListFound.getFoundLuggage());
            // initialize the total amount of luggage s in the right display
            initializeTotalCountDisplay();
        } catch (SQLException ex) {
            Logger.getLogger(ManagerFoundViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        // initialize the click listner for double clicking the table
        initializeOnFoundRowDoubleClicked();
        // initialize the total amount results in the right display
        setResultCount();
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * This method is for toggle showing only the matched luggage
     * Note: this is being called by the -fx- toggle button
     *
     * @throws java.sql.SQLException        getting data from the database
     * @void - No direct output             only changing results in the table
     */
    @FXML
    protected void showOnlyMatchedLuggage() throws SQLException {
        // if state of show only matched is false
        if (showMatchedLuggage == false) {
            // set it to true
            showMatchedLuggage = true;
            // asign the right resultset to the matchedLuggageResultSet
            // note: this is based on the boolean status that's set previously
            matchedLuggageResultSet = dataListFound.getFoundResultSet(showMatchedLuggage);
            // set the table with the right data, the resultset will be converted
            setFoundLuggageTable(dataListFound.getObservableList(matchedLuggageResultSet));
            // Reset the date picker since it is not configured with the only matched
            resetDatePickerFilter();
            // set result count in the display label
            setResultCount();
        // if the state of only matched was already true
        } else if (showMatchedLuggage == true) {
            // set the state to false, so only non matched luggage's are shown
            showMatchedLuggage = false;
            // asign the right resultset to the matchedLuggageResultSet
            // note: this is based on the boolean status that's set previously
            matchedLuggageResultSet = dataListFound.getFoundResultSet(showMatchedLuggage);
            // set the table with the right data, the resultset will be converted
            setFoundLuggageTable(dataListFound.getObservableList(matchedLuggageResultSet));
            // set result count in the display label
            setResultCount();
        }
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * Here is found luggage table overview initialized with the right values
     *
     * @void - No direct output
     */
    @Override
    public void initializeFoundLuggageTable() {
        managerFoundRegistrationNr.setCellValueFactory(new PropertyValueFactory<>("registrationNr"));
        found_dateFound.setCellValueFactory(new PropertyValueFactory<>("dateFound"));
        found_timeFound.setCellValueFactory(new PropertyValueFactory<>("timeFound"));
        found_luggageTag.setCellValueFactory(new PropertyValueFactory<>("luggageTag"));
        found_luggageType.setCellValueFactory(new PropertyValueFactory<>("luggageType"));
        found_brand.setCellValueFactory(new PropertyValueFactory<>("brand"));
        found_mainColor.setCellValueFactory(new PropertyValueFactory<>("mainColor"));
        found_secondColor.setCellValueFactory(new PropertyValueFactory<>("secondColor"));
        found_size.setCellValueFactory(new PropertyValueFactory<>("size"));
        found_weight.setCellValueFactory(new PropertyValueFactory<>("weight"));
        found_otherCharacteristics.setCellValueFactory(new PropertyValueFactory<>("otherCharacteristics"));
        found_preplacedengerId.setCellValueFactory(new PropertyValueFactory<>("preplacedengerId"));
        found_arrivedWithFlight.setCellValueFactory(new PropertyValueFactory<>("arrivedWithFlight"));
        found_locationFound.setCellValueFactory(new PropertyValueFactory<>("locationFound"));
        found_employeeId.setCellValueFactory(new PropertyValueFactory<>("employeeId"));
        found_matchedId.setCellValueFactory(new PropertyValueFactory<>("matchedId"));
        // set place holder text when there are no results
        foundLuggage.setPlaceholder(new Label("No found luggage's to display"));
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * Here will the found luggage table be set with the right data
     * The data (observable< found luggage>list) comes from the dataListFound
     *
     * @param list
     * @void - No direct output
     * @call - set foundLuggageTable
     */
    @Override
    public void setFoundLuggageTable(ObservableList<FoundLuggage> list) {
        foundLuggage.sereplacedems(list);
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * This method is for initializing the filter combo box
     * The comboBox is used for filtering to a specific:
     *                                               column/ field/ detail
     *                                                          When searching.
     * @void - No direct output
     */
    private void initializeComboFilterBox() {
        // add all the filterable fields
        searchTypeComboBox.gereplacedems().addAll("All fields", "RegistrationNr", "LuggageTag", "Brand", "Color", "Weight", "Date", "Location", "Preplacedenger", "Characteristics");
        // set the standard start value to all fields
        searchTypeComboBox.setValue("All fields");
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * This method is for searching in the table
     * There will be searched on the typed user input and filter value
     * Note: this method is called after each time the user releases a key
     *
     * @throws java.sql.SQLException        searching in the database
     * @void - No direct output             only changing results in the table
     * @call - getSearchQuery               for getting the search query
     * @call - executeResultSetQuery        for getting the resultSet
     * @call - getFoundLuggageSearchList     the result list based on the resultSet
     */
    @FXML
    @Override
    public void search() throws SQLException {
        // get the value of the search type combo box for filtering to a specific column
        String value = searchTypeComboBox.getValue().toString();
        // get the user input for the search
        String search = searchField.getText();
        // Create a new searchData object
        ServiceSearchData searchData = new ServiceSearchData();
        // Get the right query based on the users input
        String finalQuery = searchData.getSearchQuery(value, search, "foundluggage");
        // get the final query without the last semicolin to extend it
        finalQuery = finalQuery.substring(0, finalQuery.lastIndexOf(";"));
        // check if there is a filter based on FROM date.
        if (fromDate.getValue() != null && !fromDate.getValue().toString().isEmpty()) {
            // If the final qeury doesn't have any statments, add WHERE
            if (!finalQuery.contains("WHERE")) {
                finalQuery += " WHERE ";
            } else {
                // If the final qeury already contains statments, add a AND
                finalQuery += " AND ";
            }
            // add the filter from TO the query
            finalQuery += " F.dateFound > '" + fromDate.getValue().toString() + "' ";
        }
        // check if there is a filter based on TO date.
        if (toDate.getValue() != null && !toDate.getValue().toString().isEmpty()) {
            // If the final qeury doesn't have any statments, add WHERE
            if (!finalQuery.contains("WHERE")) {
                finalQuery += " WHERE ";
            } else {
                // If the final qeury already contains statments, add a AND
                finalQuery += " AND ";
            }
            // als er maar een where en geen or bevat + and
            // if (finalQuery.contains("WHERE") && )
            // add the filter from FROM the query
            finalQuery += " F.dateFound < '" + toDate.getValue().toString() + "' ";
        }
        // close the query
        finalQuery += ";";
        // clear the previous search result list
        foundLuggageListSearchResults.clear();
        // try to execute the query from the database
        // @throws SQLException
        try {
            // get the connection to the datbasec
            MyJDBC db = MainApp.getDatabase();
            // create a new resultSet and execute tche right query
            ResultSet resultSet = db.executeResultSetQuery(finalQuery);
            // get the observableList from the search object and asign this to the list
            foundLuggageListSearchResults = ServiceDataFound.loopTroughResultSet(resultSet, showMatchedLuggage);
            // set this list on the table
            foundLuggage.sereplacedems(foundLuggageListSearchResults);
            // set the right place holder message for when there are no hits
            foundLuggage.setPlaceholder(new Label("No hits based on your search"));
            // set result count in the display label
            setResultCount();
        } catch (SQLException ex) {
            Logger.getLogger(ManagerFoundViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * This method is for setting the total amount of found luggage s in the db
     * This data will be gotten from a count query in the ServiceGetDataFromDB clreplaced
     *
     * Note: this method is called when initializing the controller
     */
    private void initializeTotalCountDisplay() throws SQLException {
        // create a ServiceGetDataFromDB object with the right fields
        // table: foundluggage   field: * (=all)  where: null (no statement)
        ServiceGetDataFromDB totalCount = new ServiceGetDataFromDB("foundluggage", "*", null);
        // set the total of hits in the total (label) display
        total.setText(Integer.toString(totalCount.countHits()));
    }

    /**
     * @author Thijs Zijdel - 500782165
     *
     * This method is for setting the amount of results in the display
     * Note: this method is called when initializing the controller and searching
     */
    private void setResultCount() {
        // get the amount of items in the found luggage table
        String hits = Integer.toString(foundLuggage.gereplacedems().size());
        // if the amount of hits is zero, set it to 0 (to display)
        if (hits == null || "".equals(hits) || foundLuggage.gereplacedems().isEmpty()) {
            hits = "0";
        }
        // set the amount of hits in the results (label) display.
        results.setText(hits);
    }

    /**
     * @author Ahmet Aksu
     */
    private void initializeOnFoundRowDoubleClicked() {
        // method made by Ahmet Aksu, for making the foundTable double click'able
        foundLuggage.setOnMousePressed((MouseEvent event) -> {
            if (event.isPrimaryButtonDown() && event.getClickCount() == DOUBLE_CLICK) {
                Node node = ((Node) event.getTarget()).getParent();
                TableRow row;
                if (node instanceof TableRow) {
                    row = (TableRow) node;
                } else {
                    // clicking on text part
                    row = (TableRow) node.getParent();
                }
                System.out.println(row.gereplacedem());
                try {
                    MainApp.switchView("/Views/ManagerPreplacedengerInfoView.fxml");
                } catch (IOException ex) {
                    Logger.getLogger(ManagerFoundViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    /**
     * This method is for clearing (resetting) the date picker filters
     * Note; i didn't had enough time to also configure this with showing only the matched luggage
     */
    private void resetDatePickerFilter() {
        toDate.setValue(null);
        fromDate.setValue(null);
    }
}

14 Source : CreateProjectWindow.java
with MIT License
from MSPaintIDE

public clreplaced CreateProjectWindow extends Stage implements Initializable {

    @FXML
    private JFXTextField projectName;

    @FXML
    private JFXTextField projectLocation;

    @FXML
    private JFXButton browse;

    @FXML
    private JFXComboBox<Language> languageComboBox;

    @FXML
    private JFXButton finish;

    @FXML
    private JFXButton cancel;

    @FXML
    private JFXButton help;

    @FXML
    private Label error;

    private MainGUI mainGUI;

    private boolean isStatic;

    private File staticFile;

    private ExtraCreationOptions defaultCreationOptions = new ExtraCreationOptions.NoExtraOptions();

    public CreateProjectWindow(MainGUI mainGUI) throws IOException {
        super();
        this.mainGUI = mainGUI;
        FXMLLoader loader = new FXMLLoader(getClreplaced().getClreplacedLoader().getResource("gui/CreateProject.fxml"));
        loader.setController(this);
        Parent root = loader.load();
        ImageView icon = new ImageView(getClreplaced().getClreplacedLoader().getResource("icons/taskbar/ms-paint-logo-colored.png").toString());
        icon.setFitHeight(25);
        icon.setFitWidth(25);
        JFXDecorator jfxDecorator = new JFXDecorator(this, root, false, true, true);
        jfxDecorator.setGraphic(icon);
        jfxDecorator.setreplacedle("Welcome to MS Paint IDE");
        Scene scene = new Scene(jfxDecorator);
        scene.getStylesheets().add("style.css");
        setScene(scene);
        this.mainGUI.getThemeManager().addStage(this);
        show();
        setreplacedle("Welcome to MS Paint IDE");
        getIcons().add(new Image(getClreplaced().getClreplacedLoader().getResourcereplacedtream("ms-paint-logo-taskbar.png")));
        this.mainGUI.getThemeManager().onDarkThemeChange(root, Map.of(".search-label", "dark", ".found-context", "dark", ".language-selection", "language-selection-dark"));
    }

    private void updateLocation() {
        if (!this.isStatic)
            return;
        this.projectLocation.setText(this.staticFile.getAbsolutePath() + "\\" + projectName.getText());
    }

    @FXML
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        File startAt = MainGUI.APP_DATA;
        this.languageComboBox.sereplacedems(mainGUI.getLanguages());
        this.languageComboBox.valueProperty().addListener((observable, oldValue, newValue) -> {
            var staticParentOptional = newValue.getStaticParent();
            this.isStatic = staticParentOptional.isPresent();
            this.projectLocation.setEditable(!isStatic);
            this.projectLocation.setDisable(isStatic);
            if (isStatic)
                this.staticFile = staticParentOptional.get();
            updateLocation();
        });
        this.projectName.textProperty().addListener((observable, oldValue, newValue) -> updateLocation());
        finish.setOnAction(event -> {
            File fileLocation = new File(projectLocation.getText());
            String name = projectName.getText();
            Language language = languageComboBox.getValue();
            if (!fileLocation.exists() && !fileLocation.mkdirs()) {
                error.setText("Couldn't find or create project directory!");
                return;
            }
            PPFProject ppfProject = new PPFProject(new File(fileLocation, name.replaceAll("[^\\w\\-. ]+", "") + ".ppf"));
            ppfProject.setName(name);
            ppfProject.setLanguage(language.getClreplaced().getCanonicalName());
            ProjectManager.switchProject(ppfProject);
            Platform.runLater(() -> {
                close();
                language.getExtraCreationOptions().map(ExtraCreationOptions::showWindow).orElse(defaultCreationOptions).onComplete(this, ppfProject, language, () -> this.mainGUI.refreshProject(true));
            });
        });
        browse.setOnAction(event -> {
            FileDirectoryChooser.openDirectorySelector(chooser -> chooser.setInitialDirectory(startAt), file -> projectLocation.setText(file.getAbsolutePath()));
        });
        cancel.setOnAction(event -> close());
        help.setOnAction(event -> Browse.browse("https://github.com/MSPaintIDE/MSPaintIDE/blob/master/README.md"));
    }
}

14 Source : GemEntry_Controller.java
with MIT License
from karakasis

/**
 * FXML Controller clreplaced
 *
 * @author Christos
 */
public clreplaced GemEntry_Controller implements Initializable {

    @FXML
    private JFXComboBox<Gem> gemSelected;

    @FXML
    private Button selectGemButton;

    @FXML
    private AnchorPane disablePanel;

    @FXML
    private JFXTextField act;

    @FXML
    private JFXTextField soldBy;

    @FXML
    private JFXTextField town;

    @FXML
    private JFXComboBox<Gem> replaceGem;

    @FXML
    private JFXToggleButton replaceToggle;

    @FXML
    private AnchorPane root;

    @FXML
    private AnchorPane outerRoot;

    @FXML
    private JFXButton backButton;

    @FXML
    private Spinner<Integer> levelSlider;

    public static boolean skip = false;

    int id;

    GemLinker parent;

    Gem selectedGem;

    int selected;

    private boolean lockClear = false;

    private void handleSpin(ObservableValue<? extends Integer> observableValue, Integer oldValue, Integer newValue) {
        try {
            if (newValue == null) {
                levelSlider.getValueFactory().setValue(selectedGem.level_added);
            } else {
                levelChanged();
            }
        } catch (Exception e) {
            System.out.println("GemEntry Controller spinner error : " + e.getMessage());
        }
    }

    /**
     * Initializes the controller clreplaced.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        replaceGem.setVisible(false);
        ObservableList<Label> list = FXCollections.observableArrayList();
        SpinnerValueFactory<Integer> valueFactoryFrom = new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 100, 1);
        levelSlider.setValueFactory(valueFactoryFrom);
        levelSlider.setEditable(true);
        levelSlider.valueProperty().addListener(this::handleSpin);
        Util.addIntegerLimiterToIntegerSpinner(levelSlider, valueFactoryFrom);
        // ArrayList<Gem> gems = GemHolder.getInstance().getGemsClreplaced();
        /*
        for(Gem gem : gems){
            list.add(gem.getLabel());
            /*
            Label l = new Label();
            l.setText(gem.name.toString());
            Image img = new Image(gem.iconPath);
            l.setGraphic(new ImageView(img));
            list.add(l);
        }
*/
        /*
        ArrayList<Gem> gems = GemHolder.getInstance().getGemsClreplaced();
        gemSelected.gereplacedems().addAll(gems);
        gemSelected.setCellFactory(lv -> new GemListCell());
        gemSelected.setButtonCell(new GemListCell());
        gemSelected.setConverter(new GemToString());*/
        /*
        gemSelected.getEditor().textProperty().addListener(new ChangeListener<String>() {

            @Override
            public void changed(ObservableValue<? extends String> observable,
                                            String oldValue, String newValue) {
                if(!GemEntry_Controller.skip){
                    GemEntry_Controller.skip = true;
                    gemSelected.show();
                    if(newValue.equals("")){
                        ArrayList<Gem> gemsDefault = GemHolder.getInstance().getGemsClreplaced();
                        gemSelected.gereplacedems().clear();
                        gemSelected.gereplacedems().addAll(gemsDefault);
                    }else{
                        ArrayList<Gem> gemsQuery = GemHolder.getInstance().custom(newValue);
                        gemSelected.gereplacedems().clear();
                        gemSelected.gereplacedems().addAll(gemsQuery);
                    }
                    GemEntry_Controller.skip = false;
                }




            }
        });
        */
        /*
        gemSelected.getEditor().focusedProperty().addListener(
            (observable, oldValue, newValue) -> {
               if (newValue) {
               // Select the content of the field when the field gets the focus.
                Platform.runLater(gemSelected.getEditor()::selectAll);
               }
            }
        );*/
        // TextFields.bindAutoCompletion(gemSelected.getEditor(), gemSelected.gereplacedems(),new GemToString());
        /*new AutoCompleteComboBoxListener(gemSelected);*/
        selected = -1;
    }

    public void input(GemLinker parent, int id) {
        this.parent = parent;
        this.id = id;
        replaceGem.setVisible(false);
        replaceToggle.setSelected(false);
        for (Gem g_sib : parent.getSiblings().getGems()) {
            if (!g_sib.equals(selectedGem)) {
                replaceGem.gereplacedems().add(g_sib);
            }
        }
        replaceGem.setCellFactory(lv -> new GemListCell());
        replaceGem.setButtonCell(new GemListCell());
        replaceGem.setConverter(new GemToString());
        // add open window gem selection pop up functionallity
        parent.requestPopup();
    }

    public void load(GemLinker parent, int id, Gem g) {
        this.parent = parent;
        this.id = id;
        for (Gem g_sib : parent.getSiblings().getGems()) {
            if (!g_sib.equals(g)) {
                replaceGem.gereplacedems().add(g_sib);
            }
        }
        replaceGem.setCellFactory(lv -> new GemListCell());
        replaceGem.setButtonCell(new GemListCell());
        replaceGem.setConverter(new GemToString());
        selectedGem = g;
        replaceGem.setVisible(false);
        replaceToggle.setSelected(false);
        if (!selectedGem.getGemName().equals("<empty group>")) {
            // ObservableList<Label> list = gemSelected.gereplacedems();
            // also a way to remove effects from the disablePanel
            disablePanel.setDisable(false);
            disablePanel.setEffect(null);
            // change button
            selectGemButton.setGraphic(new ImageView(g.getSmallIcon()));
            selectGemButton.setText(g.getGemName());
            // gemSelected.getSelectionModel().select(selectedGem);
            /*
            for(Label a : list){
                if(a.getText().equals(selectedGem.getGemName())){
                    gemSelected.getSelectionModel().select(a);
                    break;
                }
            }*/
            levelSlider.getValueFactory().setValue(selectedGem.getLevelAdded());
            if (selectedGem.act == 0) {
                act.setText("Drop only");
            } else {
                act.setText("Act " + selectedGem.act);
            }
            soldBy.setText(selectedGem.npc);
            town.setText(selectedGem.town);
            if (selectedGem.replaced) {
                replaceGem.setVisible(true);
                replaceToggle.setSelected(true);
                replaceGem.setValue(selectedGem.replacedWith);
            } else {
                replaceGem.setVisible(false);
                replaceToggle.setSelected(false);
            }
        }
    }

    public void toggleReplace() {
        if (replaceToggle.isSelected()) {
            replaceGem.setVisible(true);
        } else {
            replaceGem.setVisible(false);
            replaceGem.getSelectionModel().clearSelection();
            selectedGem.replaced = false;
            selectedGem.replacedWith = null;
        }
    }

    @FXML
    private void gemPress() {
        parent.requestPopup();
    }

    public void callback(Gem g) {
        // also a way to remove effects from the disablePanel
        disablePanel.setDisable(false);
        disablePanel.setEffect(null);
        // change button
        selectGemButton.setGraphic(new ImageView(g.getSmallIcon()));
        selectGemButton.setText(g.getGemName());
        selectedGem = g.dupeGem();
        if (selectedGem.act == 0) {
            act.setText("Drop only");
        } else {
            act.setText("Act " + selectedGem.act);
        }
        soldBy.setText(selectedGem.npc);
        town.setText(selectedGem.town);
        if (selectedGem.replaced) {
            replaceGem.setVisible(true);
            replaceToggle.setSelected(true);
        } else {
            replaceGem.setVisible(false);
            replaceToggle.setSelected(false);
        }
        parent.updateGemData(selectedGem);
        levelSlider.getValueFactory().setValue(selectedGem.getLevelAdded());
    }

    public void onGemSelect() {
        gemSelected.hide();
        // selected = gemSelected.getSelectionModel().getSelectedIndex();
        Gem g = (Gem) gemSelected.getValue();
        // gemSelected.getEditor().setText(g.getGemName());
        selectedGem = g.dupeGem();
        levelSlider.getValueFactory().setValue(selectedGem.getLevelAdded());
        act.setText("Act " + selectedGem.act);
        soldBy.setText(selectedGem.npc);
        town.setText(selectedGem.town);
        if (selectedGem.replaced) {
            replaceGem.setVisible(true);
            replaceToggle.setSelected(true);
        } else {
            replaceGem.setVisible(false);
            replaceToggle.setSelected(false);
        }
        parent.updateGemData(selectedGem);
    }

    public void updateComboBox() {
        lockClear = true;
        replaceGem.gereplacedems().clear();
        for (Gem g_sib : parent.getSiblings().getGems()) {
            if (!g_sib.equals(selectedGem)) {
                replaceGem.gereplacedems().add(g_sib);
            }
        }
        if (selectedGem != null && selectedGem.replaced) {
            /*
            if(selectedGem.replacedWith != null){
                System.out.println(selectedGem.getGemName()+" replaces with : "+ selectedGem.replacedWith.getGemName());
            }else{
                System.out.println(selectedGem.getGemName()+" has null replacement ");
            }*/
            replaceGem.setValue(selectedGem.replacedWith);
        } else {
            replaceGem.getSelectionModel().clearSelection();
            replaceToggle.setSelected(false);
        }
        lockClear = false;
    }

    public void levelChanged() {
        selectedGem.level_added = (int) levelSlider.getValue();
        parent.levelChanged();
    }

    public void groupLevelChanged(int value) {
        levelSlider.getValueFactory().setValue(value);
    }

    public void replaceChanged() {
        if (!lockClear) {
            selectedGem.replaced = replaceToggle.isSelected();
            selectedGem.replacedWith = replaceGem.getValue();
            if (selectedGem.replaced) {
                replaceGem.setVisible(true);
                replaceToggle.setSelected(true);
            } else {
                replaceGem.setVisible(false);
                replaceToggle.setSelected(false);
            }
        }
    }

    public void onClick() {
        root.setStyle("color2: onclick-color-inner;");
        outerRoot.setStyle("color4: onclick-color-outer;");
        parent.clicked();
    }

    public void reset() {
        // root.setStyle("-fx-background-color: transparent;"
        // +"-fx-border-style: solid;");
        root.setStyle("color2: transparent;");
        outerRoot.setStyle("color4: transparent;");
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public AnchorPane getRoot() {
        return outerRoot;
    }

    public Gem getGem() {
        return selectedGem;
    }
}

14 Source : ConfigurationPaneController.java
with MIT License
from charlescao460

public final clreplaced ConfigurationPaneController {

    @FXML
    private AnchorPane rootPane;

    @FXML
    private AnchorPane leftPane;

    @FXML
    private AnchorPane rightPane;

    @FXML
    private AnchorPane licensePane;

    @FXML
    private JFXComboBox<IClickerChannel> channelComboBox;

    @FXML
    private Hyperlink sourceHyperLink;

    private StyleClreplacededTextArea textArea;

    private VirtualizedScrollPane<StyleClreplacededTextArea> scrollPane;

    private static final double ANCHOR_PANE_PADDING = 5.00;

    private Emulator emulator;

    private PrimaryViewController primaryViewController;

    private Application application;

    @FXML
    private void initialize() {
        drawDepthShadow();
        initializeComboBox();
        initializeLicensArea();
        initializeHyperLink();
    }

    private void drawDepthShadow() {
        JFXDepthManager.pop(leftPane);
        JFXDepthManager.pop(rightPane);
    }

    private void initializeComboBox() {
        channelComboBox.sereplacedems(FXCollections.observableArrayList(IClickerChannel.values()));
        if (emulator != null)
            channelComboBox.setValue(emulator.getEmulatorChannel());
        channelComboBox.setOnAction(e -> {
            if (channelComboBox.getValue() == null)
                return;
            if (primaryViewController.getStartToggleNode().isSelected()) {
                primaryViewController.getStartToggleNode().setSelected(false);
                primaryViewController.getStartToggleNode().getOnAction().handle(e);
            }
            primaryViewController.showProgressBar();
            (new Thread(() -> {
                if (!emulator.isAvailable())
                    emulator.stopAndGoStandby();
                emulator.changeChannel(channelComboBox.getValue());
                Platform.runLater(() -> {
                    channelComboBox.setValue(emulator.getEmulatorChannel());
                    primaryViewController.hideProgressBar();
                    primaryViewController.refresh();
                });
                UserPreferences.setChannel(emulator.getEmulatorChannel());
            })).start();
        });
    }

    private void initializeLicensArea() {
        textArea = new StyleClreplacededTextArea();
        textArea.setEditable(false);
        scrollPane = new VirtualizedScrollPane<StyleClreplacededTextArea>(textArea);
        licensePane.getChildren().add(scrollPane);
        AnchorPane.setBottomAnchor(scrollPane, ANCHOR_PANE_PADDING);
        AnchorPane.setTopAnchor(scrollPane, ANCHOR_PANE_PADDING);
        AnchorPane.setLeftAnchor(scrollPane, ANCHOR_PANE_PADDING);
        AnchorPane.setRightAnchor(scrollPane, ANCHOR_PANE_PADDING);
        String strLicense = new BufferedReader(new InputStreamReader(this.getClreplaced().getResourcereplacedtream("/resource/Licenses.txt"))).lines().collect(Collectors.joining("\n"));
        textArea.appendText(strLicense);
    }

    private void initializeHyperLink() {
        sourceHyperLink.setOnAction(e -> {
            if (application != null)
                application.getHostServices().showDoreplacedent("https://github.com/charlescao460/iSkipper-Software");
        });
    }

    /**
     * @return the emulator
     */
    public Emulator getEmulator() {
        return emulator;
    }

    /**
     * @param emulator
     *            the emulator to set
     */
    public void setEmulator(Emulator emulator) {
        this.emulator = emulator;
    }

    /**
     * @param primaryViewController
     *            the primaryViewController to set
     */
    public void setPrimaryViewController(PrimaryViewController primaryViewController) {
        this.primaryViewController = primaryViewController;
    }

    /**
     * @return the application
     */
    public Application getApplication() {
        return application;
    }

    /**
     * @param application
     *            the application to set
     */
    public void setApplication(Application application) {
        this.application = application;
    }
}

13 Source : ContentEditor.java
with MIT License
from warmuuh

/**
 * @author peter
 */
public clreplaced ContentEditor extends VBox {

    private static final String DEFAULT_CONTENTTYPE = "text/plain";

    private static ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {

        public Thread newThread(Runnable r) {
            Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);
            return t;
        }
    });

    @Getter
    protected CodeArea codeArea;

    private GenericBinding<Object, String> contentBinding;

    protected JFXComboBox<ContentTypePlugin> highlighters;

    private JFXButton format;

    protected HBox header;

    private SearchBox search;

    private ContentSearch contentSearch;

    protected final VirtualizedScrollPane scrollPane;

    public ContentEditor() {
        getStyleClreplaced().add("contentEditor");
        setupHeader();
        setupCodeArea();
        setupSearch();
        StackPane.setAlignment(search, Pos.TOP_RIGHT);
        // bug: scrollPane has some issue if it is rendered within a tab that
        // is not yet shown with content that needs a scrollbar
        // this leads to e.g. tabs not being updated, if triggered programmatically
        // switching to ALWAYS for scrollbars fixes this issue
        scrollPane = new VirtualizedScrollPane(codeArea, ScrollBarPolicy.ALWAYS, ScrollBarPolicy.ALWAYS);
        StackPane contentPane = new StackPane(scrollPane, search);
        VBox.setVgrow(contentPane, Priority.ALWAYS);
        getChildren().add(contentPane);
    }

    private void setupCodeArea() {
        codeArea = new CodeArea();
        // codeArea.setWrapText(true);
        setupParagraphGraphics();
        EventStream<Object> highLightTrigger = EventStreams.merge(codeArea.multiPlainChanges(), EventStreams.changesOf(highlighters.getSelectionModel().selectedItemProperty()), EventStreams.eventsOf(format, MouseEvent.MOUSE_CLICKED));
        // behavior of TAB: 2 spaces, allow outdention via SHIFT-TAB, if cursor is at beginning
        Nodes.addInputMap(codeArea, InputMap.consume(EventPattern.keyPressed(KeyCode.TAB), e -> codeArea.replaceSelection("  ")));
        Nodes.addInputMap(codeArea, InputMap.consume(EventPattern.keyPressed(KeyCode.TAB, SHIFT_DOWN), e -> {
            var paragraph = codeArea.getParagraph(codeArea.getCurrentParagraph());
            var indentation = StringUtils.countStartSpaces(paragraph.getText());
            // is the cursor in the white spaces
            if (codeArea.getCaretColumn() <= indentation) {
                var charsToRemove = Math.min(indentation, 2);
                codeArea.replaceText(new IndexRange(codeArea.getAbsolutePosition(codeArea.getCurrentParagraph(), 0), codeArea.getAbsolutePosition(codeArea.getCurrentParagraph(), (int) charsToRemove)), "");
            }
        }));
        // sync highlighting:
        // Subscription cleanupWhenNoLongerNeedIt = highLightTrigger
        // .successionEnds(Duration.ofMillis(500))
        // .subscribe(ignore -> {
        // System.out.println("Triggered highlight via end-of-succession");
        // highlightCode();
        // });
        // async highlighting:
        Subscription cleanupWhenNoLongerNeedIt = highLightTrigger.successionEnds(Duration.ofMillis(500)).supplyTask(this::highlightCodeAsync).awaitLatest(codeArea.multiPlainChanges()).filterMap(t -> {
            if (t.isSuccess()) {
                return Optional.of(t.get());
            } else {
                t.getFailure().printStackTrace();
                return Optional.empty();
            }
        }).subscribe(this::applyHighlighting);
        KeyCombination.Modifier controlKey = KeyCombination.CONTROL_DOWN;
        if (SystemUtils.IS_OS_MAC) {
            controlKey = KeyCombination.META_DOWN;
        }
        val keyCombination = PlatformUtil.getControlKeyCombination(KeyCode.F);
        codeArea.setOnKeyPressed(e -> {
            if (keyCombination.match(e)) {
                focusSearch();
            }
        });
    }

    protected void setupParagraphGraphics() {
        codeArea.setParagraphGraphicFactory(LineNumberFactory.get(codeArea));
    }

    private void setupSearch() {
        search = new SearchBox();
        contentSearch = new ContentSearch(codeArea);
        search.onSearch((text, forward) -> {
            if (forward) {
                contentSearch.moveToNextMatch(text);
            } else {
                contentSearch.moveToPrevMatch(text);
            }
        });
        search.onCloseRequest(this::hideSearch);
    }

    private void hideSearch() {
        search.setVisible(false);
        codeArea.requestFocus();
    }

    private void focusSearch() {
        search.setVisible(true);
        search.requestFocus();
    }

    private void setupHeader() {
        highlighters = new JFXComboBox<ContentTypePlugin>();
        highlighters.setConverter(new StringConverter<ContentTypePlugin>() {

            @Override
            public String toString(ContentTypePlugin object) {
                return object.getName();
            }

            @Override
            public ContentTypePlugin fromString(String string) {
                return null;
            }
        });
        highlighters.getSelectionModel().selectedItemProperty().addListener((obs, o, n) -> {
            if (n != null)
                format.setVisible(n.supportFormatting());
        });
        format = new JFXButton("Format");
        format.setVisible(false);
        format.setOnAction(e -> formatCurrentCode());
        header = new HBox(new Label("Content Type:"), highlighters, format);
        header.getStyleClreplaced().add("contentEditor-header");
        getChildren().add(header);
    }

    public void setHeaderVisibility(boolean isVisible) {
        if (isVisible && !getChildren().contains(header)) {
            getChildren().add(header);
        } else {
            getChildren().remove(header);
        }
    }

    private Task<StyleSpans<Collection<String>>> highlightCodeAsync() {
        String text = codeArea.getText();
        Task<StyleSpans<Collection<String>>> task = new Task<StyleSpans<Collection<String>>>() {

            @Override
            protected StyleSpans<Collection<String>> call() throws Exception {
                return computeHighlighting(text);
            }
        };
        executor.execute(task);
        return task;
    }

    private void applyHighlighting(StyleSpans<Collection<String>> highlighting) {
        codeArea.setStyleSpans(0, highlighting);
    }

    public void formatCurrentCode() {
        StopWatch s = new StopWatch();
        s.start();
        try {
            if (getCurrentContenttypePlugin() != null && getCurrentContenttypePlugin().supportFormatting()) {
                codeArea.replaceText(formatCode(codeArea.getText()));
            }
        } finally {
            s.stop();
        // System.out.println("Formatting code and replace: " + s.getTime() + " ms");
        }
    }

    protected String formatCode(String code) {
        if (code == null || code.equals(""))
            return "";
        StopWatch s = new StopWatch();
        s.start();
        try {
            if (getCurrentContenttypePlugin() != null && getCurrentContenttypePlugin().supportFormatting()) {
                return getCurrentContenttypePlugin().formatContent(code);
            } else {
                return code;
            }
        } finally {
            s.stop();
        // System.out.println("Formatting code: " + s.getTime() + " ms");
        }
    }

    protected ContentTypePlugin getCurrentContenttypePlugin() {
        return highlighters.getValue();
    }

    private StyleSpans<Collection<String>> computeHighlighting(String text) {
        StopWatch s = new StopWatch();
        s.start();
        try {
            if (getCurrentContenttypePlugin() != null && !shouldSkipHighlighting(text))
                return getCurrentContenttypePlugin().computeHighlighting(text);
            else
                return noHighlight(text);
        } finally {
            s.stop();
        // System.out.println("Highlighting code: " + s.getTime() + " ms");
        }
    }

    /**
     * Because Flowless cannot handle syntax highlighting of very long lines that well,
     * we just disable highlighting, if text contains very long lines
     *
     * @param text
     * @return
     */
    private boolean shouldSkipHighlighting(String text) {
        /**
         * iterates over the string, counting the chars until next \n thereby.
         * If line is above max, it returns true
         */
        StringCharacterIterator iterator = new StringCharacterIterator(text);
        long curLineLength = 0;
        while (true) {
            char c = iterator.next();
            if (c == CharacterIterator.DONE) {
                break;
            }
            curLineLength++;
            if (c == '\n') {
                if (curLineLength > 1_000) {
                    return true;
                }
                curLineLength = 0;
            }
        }
        return curLineLength > 1_000;
    }

    private StyleSpans<Collection<String>> noHighlight(String text) {
        val b = new StyleSpansBuilder<Collection<String>>();
        b.add(Collections.singleton("plain"), text.length());
        return b.create();
    }

    public void setEditable(boolean editable) {
        codeArea.setEditable(editable);
        if (editable) {
            setupAutoIndentation();
        }
    }

    private void setupAutoIndentation() {
        codeArea.addEventFilter(KeyEvent.KEY_PRESSED, ke -> {
            if (ke.getCode() == KeyCode.ENTER) {
                String currentLine = codeArea.getParagraph(codeArea.getCurrentParagraph()).getText();
                if (getCurrentContenttypePlugin() != null) {
                    Platform.runLater(() -> codeArea.insertText(codeArea.getCaretPosition(), getCurrentContenttypePlugin().computeIndentationForNextLine(currentLine)));
                }
            }
        });
    }

    public void setContentTypePlugins(List<ContentTypePlugin> plugins) {
        highlighters.gereplacedems().addAll(plugins);
        // set plain highlighter as default:
        String contentType = DEFAULT_CONTENTTYPE;
        setActiveContentType(plugins, contentType);
    }

    private void setActiveContentType(List<ContentTypePlugin> plugins, String contentType) {
        plugins.stream().filter(p -> contentType.contains(p.getContentType())).findAny().ifPresent(t -> {
            format.setVisible(t.supportFormatting());
            // System.out.println("Setting active highlighter: " + t);
            highlighters.setValue(t);
        // System.out.println("End Setting active highlighter");
        });
    }

    public void setContentType(String contentType) {
        var stopwatchId = "ContentType:" + contentType;
        Stopwatch.start(stopwatchId);
        setActiveContentType(highlighters.gereplacedems(), contentType);
        Stopwatch.logTime(stopwatchId, "changed highlighter");
        if (CoreApplicationOptionsProvider.options().isAutoformatContent())
            formatCurrentCode();
        Stopwatch.stop(stopwatchId);
    }

    public void setContent(Supplier<String> getter, Consumer<String> setter) {
        // if (contentBinding != null) {
        // Bindings.unbindBidirectional(codeAreaTextBinding, contentBinding);
        // }
        // contentBinding = GenericBinding.of(o -> getter.get(), (o,v) -> setter.accept(v), null);
        // codeAreaTextBinding = Var.mapBidirectional(contentBinding,  s -> s, s->s);
        String curValue = getter.get();
        if (CoreApplicationOptionsProvider.options().isAutoformatContent())
            curValue = formatCode(curValue);
        replaceText(curValue);
        codeArea.textProperty().addListener((obs, o, n) -> {
            if (codeArea.isEditable()) {
                setter.accept(n);
            }
        });
    }

    public void addContent(String additiveContent) {
        // if (contentBinding != null) {
        // Bindings.unbindBidirectional(codeAreaTextBinding, contentBinding);
        // }
        // contentBinding = GenericBinding.of(o -> getter.get(), (o,v) -> setter.accept(v), null);
        // codeAreaTextBinding = Var.mapBidirectional(contentBinding,  s -> s, s->s);
        codeArea.appendText(additiveContent);
    }

    protected void replaceText(String newText) {
        codeArea.replaceText(newText != null ? newText : "");
    }

    public void setDisableContent(Boolean disable) {
        if (disable)
            codeArea.getStyleClreplaced().add("disabled");
        else
            codeArea.getStyleClreplaced().remove("disabled");
        codeArea.setDisable(disable);
    }
}

13 Source : ServiceOverviewLostViewController.java
with MIT License
from ThijsZijdel

/**
 * FXML Controller clreplaced for the lost luggage overview
 *
 * @author Thijs Zijdel - 500782165
 */
public clreplaced ServiceOverviewLostViewController implements Initializable, LostLuggageTable, Search {

    // page replacedle
    private final String replacedLE = "Overview Lost Luggage";

    private final String replacedLE_DUTCH = "Overzicht verloren bagage";

    // stage for more details when double clicking on a table item
    private final Stage POPUP_STAGE_LOST = new Stage();

    // list for the search results
    private static ObservableList<LostLuggage> lostLuggageListSearchResults = FXCollections.observableArrayList();

    // text field for the users search input
    @FXML
    JFXTextField searchField;

    // combo box for a type/field/column search filter
    @FXML
    JFXComboBox searchTypeComboBox;

    // Object for getting the data
    private ServiceDataLost dataListLost;

    // show alos matched luggage state, by default on false
    private boolean showMatchedLuggage = false;

    // resultSet for the items when changing the state of the showMatchedLuggage
    private ResultSet matchedLuggageResultSet;

    // click counts
    private final int DOUBLE_CLICK = 2;

    /* -----------------------------------------
         TableView lost luggage's colommen
    ----------------------------------------- */
    @FXML
    private TableView<LostLuggage> lostLuggageTable;

    @FXML
    private TableColumn<LostLuggage, String> lostRegistrationNr;

    @FXML
    private TableColumn<LostLuggage, String> DateLost;

    @FXML
    private TableColumn<LostLuggage, String> TimeLost;

    @FXML
    private TableColumn<LostLuggage, String> lostLuggageTag;

    @FXML
    private TableColumn<LostLuggage, String> lostLuggageType;

    @FXML
    private TableColumn<LostLuggage, String> lostBrand;

    @FXML
    private TableColumn<LostLuggage, String> lostMainColor;

    @FXML
    private TableColumn<LostLuggage, String> lostSecondColor;

    @FXML
    private TableColumn<LostLuggage, String> lostSize;

    @FXML
    private TableColumn<LostLuggage, Integer> lostWeight;

    @FXML
    private TableColumn<LostLuggage, String> lostOtherCharacteristics;

    @FXML
    private TableColumn<LostLuggage, Integer> lostPreplacedengerId;

    @FXML
    private TableColumn<LostLuggage, String> lostFlight;

    @FXML
    private TableColumn<LostLuggage, Integer> lostMatchedId;

    @FXML
    private JFXButton button_input, button_match;

    @FXML
    private JFXToggleButton matchedLuggageToggle;

    /**
     * Initializes the controller clreplaced that adds all the needed functionality,
     * to the: ServiceOverviewLostView.FXML view.
     *
     * @param url location  used to resolve relative paths for the root object
     * @param rb resources   used to localize the root object
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // for setting the resource bundle
        MainApp.currentView = "/Views/Service/ServiceOverviewLostView.fxml";
        // set the view's replacedle, and catch a possible IOException
        try {
            if (MainApp.language.equals("dutch")) {
                MainViewController.getInstance().getreplacedle(replacedLE_DUTCH);
            } else {
                MainViewController.getInstance().getreplacedle(replacedLE);
            }
        } catch (IOException ex) {
            Logger.getLogger(OverviewUserController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        // so the user can change the filter
        initializeComboFilterBox();
        // try to initialize and set the lost luggage table
        try {
            // Initialize Table & obj lost
            dataListLost = new ServiceDataLost();
            initializeLostLuggageTable();
            // set the table with the right data
            setLostLuggageTable(dataListLost.getLostLuggage());
        } catch (SQLException ex) {
            Logger.getLogger(ServiceOverviewLostViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        // set screen status
        ServiceHomeViewController.setOnMatchingView(false);
    }

    /**
     * This method is for initializing the filter combo box
     * The comboBox is used for filtering to a specific:
     *                                               column/ field/ detail
     *                                                          When searching.
     * @void - No direct output
     */
    private void initializeComboFilterBox() {
        // add all the filterable fields
        searchTypeComboBox.gereplacedems().addAll("All fields", "RegistrationNr", "LuggageTag", "Brand", "Color", "Weight", "Date", "Preplacedenger", "Characteristics");
        // set the standard start value to all fields
        searchTypeComboBox.setValue("All fields");
    }

    /**
     * This method is for toggle showing only the matched luggage
     * Note: this is being called by the -fx- toggle button
     *
     * @throws java.sql.SQLException        getting data from the database
     * @void - No direct output             only changing results in the table
     */
    @FXML
    protected void showOnlyMatchedLuggage() throws SQLException {
        // if state of show only matched is false
        if (showMatchedLuggage == false) {
            // set it to true
            showMatchedLuggage = true;
            // asign the right resultset to the matchedLuggageResultSet
            // note: this is based on the boolean status that's set previously
            matchedLuggageResultSet = dataListLost.getLostResultSet(showMatchedLuggage);
            // set the table with the right data, the resultset will be converted
            setLostLuggageTable(dataListLost.getObservableList(matchedLuggageResultSet));
        // if the state of only matched was already true
        } else if (showMatchedLuggage == true) {
            // set the state to false, so only non matched luggage's are shown
            showMatchedLuggage = false;
            // asign the right resultset to the matchedLuggageResultSet
            // note: this is based on the boolean status that's set previously
            matchedLuggageResultSet = dataListLost.getLostResultSet(showMatchedLuggage);
            // set the table with the right data, the resultset will be converted
            setLostLuggageTable(dataListLost.getObservableList(matchedLuggageResultSet));
        }
    }

    /**
     * This method is for searching in the table
     * There will be searched on the typed user input and filter value
     * Note: this method is called after each time the user releases a key
     *
     * @throws java.sql.SQLException        searching in the database
     * @void - No direct output             only changing results in the table
     * @call - getSearchQuery               for getting the search query
     * @call - executeResultSetQuery        for getting the resultSet
     * @call - getLostLuggageSearchList     the result list based on the resultSet
     */
    @FXML
    @Override
    public void search() throws SQLException {
        // get the value of the search type combo box for filtering to a specific column
        String value = searchTypeComboBox.getValue().toString();
        // get the user input for the search
        String search = searchField.getText();
        // Create a new searchData object
        ServiceSearchData searchData = new ServiceSearchData();
        // Get the right query based on the users input
        String finalQuery = searchData.getSearchQuery(value, search, "lostluggage");
        // clear the previous search result list
        lostLuggageListSearchResults.clear();
        // try to execute the query from the database
        // @throws SQLException
        try {
            // get the connection to the datbase
            MyJDBC db = MainApp.getDatabase();
            // create a new resultSet and execute the right query
            ResultSet resultSet = db.executeResultSetQuery(finalQuery);
            // get the observableList from the search object and asign this to the list
            lostLuggageListSearchResults = ServiceDataLost.loopTroughResultSet(resultSet, showMatchedLuggage);
            // searchData.getLostLuggageSearchList(resultSet);
            // set this list on the table
            lostLuggageTable.sereplacedems(lostLuggageListSearchResults);
            // set the right place holder message for when there are no hits
            lostLuggageTable.setPlaceholder(new Label("No hits based on your search"));
        } catch (SQLException ex) {
            Logger.getLogger(ServiceOverviewLostViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Here is lost luggage table overview initialized with the right values
     *
     * @void - No direct output
     */
    @Override
    public void initializeLostLuggageTable() {
        lostRegistrationNr.setCellValueFactory(new PropertyValueFactory<>("registrationNr"));
        DateLost.setCellValueFactory(new PropertyValueFactory<>("dateLost"));
        TimeLost.setCellValueFactory(new PropertyValueFactory<>("timeLost"));
        lostLuggageTag.setCellValueFactory(new PropertyValueFactory<>("luggageTag"));
        lostLuggageType.setCellValueFactory(new PropertyValueFactory<>("luggageType"));
        lostBrand.setCellValueFactory(new PropertyValueFactory<>("brand"));
        lostMainColor.setCellValueFactory(new PropertyValueFactory<>("mainColor"));
        lostSecondColor.setCellValueFactory(new PropertyValueFactory<>("secondColor"));
        lostSize.setCellValueFactory(new PropertyValueFactory<>("size"));
        lostWeight.setCellValueFactory(new PropertyValueFactory<>("weight"));
        lostOtherCharacteristics.setCellValueFactory(new PropertyValueFactory<>("otherCharacteristics"));
        lostPreplacedengerId.setCellValueFactory(new PropertyValueFactory<>("preplacedengerId"));
        lostFlight.setCellValueFactory(new PropertyValueFactory<>("flight"));
        lostMatchedId.setCellValueFactory(new PropertyValueFactory<>("matchedId"));
        // set place holder text when there are no results
        lostLuggageTable.setPlaceholder(new Label("No lost luggage's to display"));
    }

    /**
     * Here will the lost luggage table be set with the right data
     * The data (observable< lostluggage>list) comes from the dataListLost
     *
     * @param list
     * @void - No direct output
     * @call - set lostLuggageTable
     */
    @Override
    public void setLostLuggageTable(ObservableList<LostLuggage> list) {
        lostLuggageTable.sereplacedems(list);
    }

    /**
     * Here is checked of a row in the lost luggage table is clicked
     * If this is the case, two functions will be activated.
     *
     * @void - No direct output
     * @call - setDetailsOfRow           set the details of the clicked row
     * @call - setAndOpenPopUpDetails    opens the right more details pop up
     */
    public void lostRowClicked() {
        lostLuggageTable.setOnMousePressed((MouseEvent event) -> {
            // --> event         //--> double click
            if (event.isPrimaryButtonDown() && event.getClickCount() == DOUBLE_CLICK) {
                // Make a more details object called lostDetails.
                ServiceMoreDetails lostDetails = new ServiceMoreDetails();
                // Set the detailes of the clicked row and preplaced a stage and link
                lostDetails.setDetailsOfRow("lost", event, POPUP_STAGE_LOST, "/Views/Service/ServiceDetailedLostLuggageView.fxml");
                // Open the more details pop up.
                lostDetails.setAndOpenPopUpDetails(POPUP_STAGE_LOST, "/Views/Service/ServiceDetailedLostLuggageView.fxml", "lost");
            }
        });
    }

    /*--------------------------------------------------------------------------
                              Switch view buttons
    --------------------------------------------------------------------------*/
    @FXML
    protected void switchToInput(ActionEvent event) throws IOException {
        MainApp.switchView("/Views/Service/ServiceInputLuggageView.fxml");
    }

    @FXML
    protected void switchToMatching(ActionEvent event) throws IOException {
        MainApp.switchView("/Views/Service/ServiceMatchingView.fxml");
    }
}

13 Source : ServiceInputLuggageViewController.java
with MIT License
from ThijsZijdel

/**
 * FXML Controller clreplaced for the inputluggage view
 *
 * @author Arthur Krom
 */
public clreplaced ServiceInputLuggageViewController implements Initializable {

    @FXML
    private JFXComboBox missingFoundComboBox, flightJFXComboBox, typeJFXComboBox, colorJFXComboBox, secondColorJFXComboBox, locationJFXComboBox, airportJFXComboBox, destinationJFXComboBox;

    // Hashmap containing all the comboboxes
    private Map<String, JFXComboBox> comboBoxes = new LinkedHashMap<>();

    @FXML
    private GridPane mainGridPane, travellerInfoGridPane, luggageInfoGridPane;

    @FXML
    private Label preplacedengerInformationLbl;

    @FXML
    private JFXButton exportPDFBtn;

    @FXML
    private JFXDatePicker dateJFXDatePicker;

    @FXML
    private JFXTimePicker timeJFXTimePicker;

    @FXML
    private JFXTextField nameJFXTextField, addressJFXTextField, placeJFXTextField, postalcodeJFXTextField, countryJFXTextField, phoneJFXTextField, emailJFXTextField, labelnumberJFXTextField, brandJFXTextField, characterJFXTextField, sizeJFXTextField, weightJFXTextField;

    // Hashmap containing all the text fields
    private Map<String, JFXTextField> textFields = new LinkedHashMap<>();

    // Form object
    private Form form;

    // HashMap that contains all the form values
    private Map<String, String> formValues = new LinkedHashMap<>();

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // Define the previous view
        MainViewController.previousView = "/Views/Service/ServiceHomeView.fxml";
        // set the replacedle of the view, default form to be displayed is Missing
        changereplacedle("Lost luggage form");
        // Make a new form.
        this.form = new Form();
        // Method to initialize the hashmaps
        setHashMaps();
        try {
            // Import the form options
            Map<String, ArrayList<String>> formOptions = this.form.getFormOptions();
            // Add the all the options to the comboboxes
            missingFoundComboBox.gereplacedems().addAll(formOptions.get("foundorlost"));
            colorJFXComboBox.gereplacedems().addAll(formOptions.get("colors"));
            secondColorJFXComboBox.gereplacedems().addAll(formOptions.get("colors"));
            locationJFXComboBox.gereplacedems().addAll(formOptions.get("locations"));
            airportJFXComboBox.gereplacedems().addAll(formOptions.get("airports"));
            flightJFXComboBox.gereplacedems().addAll(formOptions.get("flights"));
            typeJFXComboBox.gereplacedems().addAll(formOptions.get("luggagetypes"));
            destinationJFXComboBox.gereplacedems().addAll(formOptions.get("airports"));
            // Set default value for the type of form combobox
            missingFoundComboBox.setValue("Lost");
            this.form.setType("Lost");
        } catch (SQLException ex) {
            Logger.getLogger(ServiceInputLuggageViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // Method to change the replacedle of the current view
    public void changereplacedle(String replacedle) {
        try {
            MainViewController.getInstance().getreplacedle(replacedle);
        } catch (IOException ex) {
            Logger.getLogger(ServiceInputLuggageViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // Method to initialize all the hashmaps
    private void setHashMaps() {
        // initializing the combobox hashmap
        comboBoxes.put("missingfound", missingFoundComboBox);
        comboBoxes.put("flight", flightJFXComboBox);
        comboBoxes.put("type", typeJFXComboBox);
        comboBoxes.put("color", colorJFXComboBox);
        comboBoxes.put("secondcolor", secondColorJFXComboBox);
        comboBoxes.put("location", locationJFXComboBox);
        comboBoxes.put("airport", airportJFXComboBox);
        comboBoxes.put("destination", destinationJFXComboBox);
        // initializing the textfield hashmap
        textFields.put("name", nameJFXTextField);
        textFields.put("address", addressJFXTextField);
        textFields.put("place", placeJFXTextField);
        textFields.put("postalcode", postalcodeJFXTextField);
        textFields.put("country", countryJFXTextField);
        textFields.put("phone", phoneJFXTextField);
        textFields.put("email", emailJFXTextField);
        textFields.put("labelnumber", labelnumberJFXTextField);
        textFields.put("brand", brandJFXTextField);
        textFields.put("character", characterJFXTextField);
        textFields.put("size", sizeJFXTextField);
        textFields.put("weight", weightJFXTextField);
    }

    // Method that loops through all the fields checking whether the ones that are not allowed to be empty aren't
    public boolean checkFields() {
        boolean appropriate = true;
        // Date picker and timepicker cannot be looped through since theyre not inside an array
        // Check whether the date field has been filled in appropriately
        // Get the date, if its empty let the user know it has to be filled
        if (dateJFXDatePicker.getValue() == null || dateJFXDatePicker.getValue().toString().isEmpty()) {
            dateJFXDatePicker.setStyle("-fx-background-color: #f47142");
            appropriate = false;
        } else {
            dateJFXDatePicker.setStyle(null);
        }
        // Get the time, if its empty let the user know it has to be filled
        if (timeJFXTimePicker.getValue() == null || timeJFXTimePicker.getValue().toString().isEmpty()) {
            timeJFXTimePicker.setStyle("-fx-background-color: #f47142");
            appropriate = false;
        } else {
            timeJFXTimePicker.setStyle(null);
        }
        // Loop through the comboboxes
        for (Map.Entry<String, JFXComboBox> entry : comboBoxes.entrySet()) {
            String key = entry.getKey();
            JFXComboBox value = entry.getValue();
            // first check for the comboboxes that have to be selected in both forms
            if (key.equals("color") || key.equals("type") || key.equals("airport") || key.equals("flight")) {
                if (value.getValue() == null || value.getValue().toString().isEmpty()) {
                    value.setStyle("-fx-background-color: #f47142");
                    appropriate = false;
                } else {
                    value.setStyle(null);
                }
            }
            // check the comboboxes for the lost form, in this case only the destination is an additional combobox
            // where an option has to be selected
            if (form.getType().equals("Lost") && key.equals("destination")) {
                if (value.getValue() == null || value.getValue().toString().isEmpty()) {
                    value.setStyle("-fx-background-color: #f47142");
                    appropriate = false;
                } else {
                    value.setStyle(null);
                }
            }
        }
        // loop through the textfields
        for (Map.Entry<String, JFXTextField> entry : textFields.entrySet()) {
            String key = entry.getKey();
            JFXTextField value = entry.getValue();
            // If its a lost form, the following fields cannot be empty
            if (form.getType().equals("Lost")) {
                if (key.equals("name") || key.equals("address") || key.equals("place") || key.equals("postalcode") || key.equals("country") || key.equals("phone") || key.equals("email")) {
                    if (value.getText() == null || value.getText().isEmpty()) {
                        value.setStyle("-fx-background-color: #f47142");
                        appropriate = false;
                    } else {
                        value.setStyle(null);
                    }
                }
            }
        }
        return appropriate;
    }

    @FXML
    public // Method that will add the form to the database
    void submitForm(ActionEvent event) {
        // Check whether the fields have been filled in appropriately
        if (checkFields() == false) {
            System.out.println("form not filled in properly");
            return;
        }
        // General information
        String formtype = missingFoundComboBox.getValue().toString();
        String date = dateJFXDatePicker.getValue().toString();
        String time = timeJFXTimePicker.getValue().toString();
        String airport = airportJFXComboBox.getValue().toString();
        // Default preplacedenger information if the form is foundluggage, if its lostluggage it will
        // get check in the checkFields method.
        String name = "", address = "", place = "", postalcode = "", country = "", phone = "", email = "";
        // Luggage information
        String labelnumber = "", flight = "", type = "", brand = "", color = "", secondColor = "", size = "", characteristics = "", location = "", weight = "";
        // Get the preplacedenger information
        name = nameJFXTextField.getText();
        address = addressJFXTextField.getText();
        place = placeJFXTextField.getText();
        postalcode = postalcodeJFXTextField.getText();
        country = countryJFXTextField.getText();
        phone = phoneJFXTextField.getText();
        email = emailJFXTextField.getText();
        // Get the luggage information
        labelnumber = labelnumberJFXTextField.getText();
        type = typeJFXComboBox.getValue().toString();
        color = colorJFXComboBox.getValue().toString();
        brand = brandJFXTextField.getText();
        size = sizeJFXTextField.getText();
        characteristics = characterJFXTextField.getText();
        if (weight.isEmpty()) {
            weight = "0";
        }
        if (flightJFXComboBox.getValue() != null && !flightJFXComboBox.getValue().toString().isEmpty()) {
            flight = flightJFXComboBox.getValue().toString();
        }
        if (secondColorJFXComboBox.getValue() != null && !secondColorJFXComboBox.getValue().toString().isEmpty()) {
            secondColor = secondColorJFXComboBox.getValue().toString();
        }
        if (locationJFXComboBox.getValue() != null && !locationJFXComboBox.getValue().toString().isEmpty()) {
            location = locationJFXComboBox.getValue().toString();
        }
        if (weightJFXTextField.getText() != null && !weightJFXTextField.getText().isEmpty()) {
            weight = weightJFXTextField.getText();
        }
        // Is it found luggage? else its missing
        if ("Found".equals(formtype)) {
            // If atleast one of the following fields is not empty the preplacedenger will be added to the database
            if (!name.isEmpty() || !address.isEmpty() || !place.isEmpty() || !postalcode.isEmpty() || !email.isEmpty() || !phone.isEmpty()) {
                // Query to add the preplacedenger
                String addPreplacedengerQuery = "INSERT INTO preplacedenger VALUES(NULL ,'" + name + "', '" + address + "', '" + place + "', '" + postalcode + "', '" + country + "', '" + email + "', '" + phone + "')";
                // Execute the query to add a preplacedenger to the database
                int affectedRowsPreplacedengerQuery = MainApp.getDatabase().executeUpdateQuery(addPreplacedengerQuery);
                // select the id of the preplacedenger we just added by email address
                // TODO: has to be changed to return generated keys from prepared statement
                String selectPreplacedengerQuery = "SELECT preplacedengerId FROM preplacedenger ORDER BY preplacedengerId DESC LIMIT 1";
                // execute the query to select the recently added preplacedenger, the String we get back is the id of that user
                String preplacedengerId = MainApp.getDatabase().executeStringQuery(selectPreplacedengerQuery);
                // Query to add the missing luggage to the database
                String addFoundLuggageQuery = "INSERT INTO foundluggage VALUES(NULL, '" + date + "','" + time + "', '" + labelnumber + "', (SELECT luggageTypeId FROM luggagetype WHERE english ='" + type + "'), " + "'" + brand + "'" + ", (SELECT ralCode FROM color WHERE english = '" + color + "'), (SELECT ralCode FROM COLOR WHERE english = '" + secondColor + "'), '" + size + "', '" + weight + "', '" + characteristics + "', " + "'" + flight + "', (SELECT locationId FROM location WHERE english ='" + location + "'), '" + MainApp.currentUser.getId() + "', '" + preplacedengerId + "', NULL, (SELECT IATACode FROM destination WHERE airport =  '" + airport + "'), NULL, NULL )";
                // execute the missing luggage query
                int affectedRowsLuggageQuery = MainApp.getDatabase().executeUpdateQuery(addFoundLuggageQuery);
                this.exportPDFBtn.setDisable(false);
            } else {
                // Query to add the missing luggage to the database
                String addFoundLuggageQuery = "INSERT INTO foundluggage VALUES(NULL, '" + date + "','" + time + "', '" + labelnumber + "', (SELECT luggageTypeId FROM luggagetype WHERE english ='" + type + "'), " + "'" + brand + "'" + ", (SELECT ralCode FROM color WHERE english = '" + color + "'), (SELECT ralCode FROM COLOR WHERE english = '" + secondColor + "'), '" + size + "', '" + weight + "', '" + characteristics + "', " + "'" + flight + "', (SELECT locationId FROM location WHERE english ='" + location + "'), '" + MainApp.currentUser.getId() + "', NULL, NULL, (SELECT IATACode FROM destination WHERE airport =  '" + airport + "'), NULL, NULL  )";
                // execute the missing luggage query
                int affectedRowsLuggageQuery = MainApp.getDatabase().executeUpdateQuery(addFoundLuggageQuery);
                this.exportPDFBtn.setDisable(false);
            }
        } else {
            // Query to add the preplacedenger
            String addPreplacedengerQuery = "INSERT INTO preplacedenger VALUES(NULL ,'" + name + "', '" + address + "', '" + place + "', '" + postalcode + "', '" + country + "', '" + email + "', '" + phone + "')";
            // Execute the query to add a preplacedenger to the database
            int affectedRowsPreplacedengerQuery = MainApp.getDatabase().executeUpdateQuery(addPreplacedengerQuery);
            // select the id of the preplacedenger we just added by email address
            // TODO: has to be changed to return generated keys from prepared statement
            String selectPreplacedengerQuery = "SELECT preplacedengerId FROM preplacedenger ORDER BY preplacedengerId DESC LIMIT 1";
            // execute the query to select the recently added preplacedenger, the String we get back is the id of that user
            String preplacedengerId = MainApp.getDatabase().executeStringQuery(selectPreplacedengerQuery);
            // Query to add the missing luggage to the database
            String addMissingLuggageQuery = "INSERT INTO lostluggage VALUES(NULL, '" + date + "','" + time + "', '" + labelnumber + "', (SELECT luggageTypeId FROM luggagetype WHERE english ='" + type + "'), " + "'" + brand + "'" + ", (SELECT ralCode FROM color WHERE english = '" + color + "'), (SELECT ralCode FROM COLOR WHERE english = '" + secondColor + "'), '" + size + "', '" + weight + "', '" + characteristics + "', " + "'" + flight + "', '" + MainApp.currentUser.getId() + "', '" + preplacedengerId + "', NULL, (SELECT IATACode FROM destination WHERE airport =  '" + airport + "'), NULL )";
            // execute the missing luggage query
            int affectedRowsLuggageQuery = MainApp.getDatabase().executeUpdateQuery(addMissingLuggageQuery);
            this.exportPDFBtn.setDisable(false);
        }
    }

    // Method to export the current form to pdf
    @FXML
    public void exportPDF() throws IOException, SQLException {
        // Check if all the fields have been filled in properly
        if (checkFields() == false) {
            System.out.println("form not filled in properly");
            return;
        }
        // Fileobject
        File file = MainApp.selectFileToSave("*.pdf");
        // If fileobject has been initialized
        if (file != null) {
            // get the location to store the file
            String fileName = file.getAbsolutePath();
            formValues.put("Form Type: ", form.getType());
            formValues.put("Registration number:", form.getLastId());
            formValues.put("Employee: ", MainApp.currentUser.getFirstName() + " " + MainApp.currentUser.getLastName());
            formValues.put("Time: ", timeJFXTimePicker.getValue().toString());
            formValues.put("Date: ", dateJFXDatePicker.getValue().toString());
            formValues.put("Airport: ", airportJFXComboBox.getValue().toString());
            // If its lost then preplacedenger info goes in first
            if (form.getType().equals("Lost")) {
                formValues.put("preplacedengerinfoline", "Preplacedenger Information");
                formValues.put("Name: ", textFields.get("name").getText());
                formValues.put("Address: ", textFields.get("address").getText());
                formValues.put("Place of residence: ", textFields.get("place").getText());
                formValues.put("Postalcode: ", textFields.get("postalcode").getText());
                formValues.put("Country: ", textFields.get("country").getText());
                formValues.put("Phone: ", textFields.get("phone").getText());
                formValues.put("E-mail: ", textFields.get("email").getText());
                formValues.put("luggageinfoline", "Luggage Information");
                formValues.put("Labelnumber: ", checkTextField(textFields.get("labelnumber")));
                formValues.put("Flight: ", checkComboBox(comboBoxes.get("flight")));
                formValues.put("Destination: ", checkComboBox(comboBoxes.get("destination")));
                formValues.put("Type: ", checkComboBox(comboBoxes.get("type")));
                formValues.put("Brand: ", checkTextField(textFields.get("brand")));
                formValues.put("Color: ", checkComboBox(comboBoxes.get("color")));
                formValues.put("Second color: ", checkComboBox(comboBoxes.get("secondcolor")));
                formValues.put("Dimensions: ", checkTextField(textFields.get("size")));
                formValues.put("Weight: ", checkTextField(textFields.get("weight")));
                formValues.put("Character: ", checkTextField(textFields.get("character")));
            } else {
                formValues.put("luggageinfoline", "Luggage Information");
                formValues.put("Labelnumber: ", checkTextField(textFields.get("labelnumber")));
                formValues.put("Flight: ", checkComboBox(comboBoxes.get("flight")));
                formValues.put("Destination: ", checkComboBox(comboBoxes.get("destination")));
                formValues.put("Type: ", checkComboBox(comboBoxes.get("type")));
                formValues.put("Brand: ", checkTextField(textFields.get("brand")));
                formValues.put("Color: ", checkComboBox(comboBoxes.get("color")));
                formValues.put("Second color: ", checkComboBox(comboBoxes.get("secondcolor")));
                formValues.put("Dimensions: ", checkTextField(textFields.get("size")));
                formValues.put("Weight: ", checkTextField(textFields.get("weight")));
                formValues.put("Character: ", checkTextField(textFields.get("character")));
                formValues.put("Location: ", checkComboBox(comboBoxes.get("location")));
                formValues.put("preplacedengerinfoline", "Preplacedenger Information");
                formValues.put("Name: ", textFields.get("name").getText());
                formValues.put("Address: ", textFields.get("address").getText());
                formValues.put("Place of residence: ", textFields.get("place").getText());
                formValues.put("Postalcode: ", textFields.get("postalcode").getText());
                formValues.put("Country: ", textFields.get("country").getText());
                formValues.put("Phone: ", textFields.get("phone").getText());
                formValues.put("E-mail: ", textFields.get("email").getText());
            }
            // New pdf doreplacedent with filebath in constructor
            PdfDoreplacedent Pdf = new PdfDoreplacedent(fileName);
            // set the values for the pdf
            Pdf.setPdfValues(formValues);
            // Save the pdf
            Pdf.savePDF();
        } else {
            System.out.println("Setting a location has been cancelled");
        }
    }

    @FXML
    public void emailPDF() {
        System.out.println("emailing the PDF");
    }

    @FXML
    public // Method to switch between found/lost form
    void foundOrMissing() {
        String value = missingFoundComboBox.getValue().toString();
        if ("Found".equals(value)) {
            this.form.setType("Found");
            // Remove traveller and luggage info so they can change positions
            mainGridPane.getChildren().remove(travellerInfoGridPane);
            mainGridPane.getChildren().remove(luggageInfoGridPane);
            // Add them again
            mainGridPane.add(luggageInfoGridPane, 0, 1);
            mainGridPane.add(travellerInfoGridPane, 1, 1);
            preplacedengerInformationLbl.setText("Preplacedenger information is not required");
            // Change the replacedle of the view
            changereplacedle("Found luggage form");
            // show the location combobox
            locationJFXComboBox.setVisible(true);
        }
        if ("Lost".equals(value)) {
            this.form.setType("Lost");
            // Remove the gridpanes
            mainGridPane.getChildren().remove(travellerInfoGridPane);
            mainGridPane.getChildren().remove(luggageInfoGridPane);
            // Add them again on different positions
            mainGridPane.add(travellerInfoGridPane, 0, 1);
            mainGridPane.add(luggageInfoGridPane, 1, 1);
            preplacedengerInformationLbl.setText("Preplacedenger information");
            // Change the replacedle of the view
            changereplacedle("Lost luggage form");
            // hide the location combobox
            locationJFXComboBox.setVisible(false);
        }
    }

    // Method to check whether a combobox has been filled
    public String checkComboBox(JFXComboBox comboBox) {
        if (comboBox.getValue() != null && !comboBox.getValue().toString().isEmpty()) {
            return comboBox.getValue().toString();
        } else {
            return "";
        }
    }

    // Method to check whether the textfield has been filled
    public String checkTextField(JFXTextField textField) {
        if (textField.getText() != null && !textField.getText().isEmpty()) {
            return textField.getText();
        } else {
            return "";
        }
    }
}

13 Source : ServiceEditLostLuggageViewController.java
with MIT License
from ThijsZijdel

/**
 * FXML Controller clreplaced
 *
 * @author Thijs Zijdel - 500782165
 */
public clreplaced ServiceEditLostLuggageViewController implements Initializable, LostLuggageFields {

    // get al the jfxtextFields, areas and comboboxes
    @FXML
    private JFXTextField registrationNr;

    @FXML
    private JFXTextField luggageTag;

    @FXML
    private JFXTextField brand;

    @FXML
    private JFXTextField size;

    @FXML
    private JFXTextField weight;

    @FXML
    private JFXTextArea signatures;

    @FXML
    private JFXTextField preplacedangerId;

    @FXML
    private JFXTextField preplacedangerName;

    @FXML
    private JFXTextField address;

    @FXML
    private JFXTextField place;

    @FXML
    private JFXTextField postalCode;

    @FXML
    private JFXTextField country;

    @FXML
    private JFXTextField email;

    @FXML
    private JFXTextField phone;

    @FXML
    private JFXTextField timeLost;

    @FXML
    private JFXTextField dateLost;

    @FXML
    private JFXTextField flight;

    @FXML
    private JFXComboBox colorPicker1;

    @FXML
    private JFXComboBox colorPicker2;

    @FXML
    private JFXComboBox typePicker;

    @FXML
    private StackPane stackPane;

    @FXML
    private JFXButton saveEditings;

    // create dialog content/layout and a textflow for the body
    private final JFXDialogLayout CONTENT = new JFXDialogLayout();

    private final TextFlow ALERT_MESSAGE = new TextFlow();

    // view replacedle
    private final String replacedLE = "Edit Lost Luggage";

    private final String replacedLE_DUTCH = "Pas verloren bagage aan";

    // alert message content (changes)
    private String changedFields = "";

    private int changes = 0;

    private int changeCountDoubleCheck = 0;

    // start values of the initialized text fields
    public String[] startValues;

    // language of the application
    private final String LANGUAGE = MainApp.getLanguage();

    // conection to the main database
    private final MyJDBC DB = MainApp.getDatabase();

    // colors
    private final String UN_FOCUS_COLOR = "#ababab";

    private final String NOTICE_COLOR = "#4189fc";

    private final String ALERT_COLOR = "#e03636";

    // amount of field
    private final int AMOUNT_OF_FIELDS = 20;

    // count for the amount of preplacedengers
    int preplacedengerCount = 0;

    // click count
    private final int SINGLE_CLICK = 1;

    private final int DOUBLE_CLICK = 2;

    // the combo boxes will be converted to te following codes (before updating)
    private int ralCode1, ralCode2, typeCode;

    /**
     * Initializes the controller clreplaced that adds all the needed functionality,
     * to the: ServiceEditLostLuggageView.FXML view.
     *
     * @param url location  used to resolve relative paths for the root object
     * @param rb resources   used to localize the root object
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // for setting the resource bundle
        MainApp.currentView = "/Views/Service/ServiceEditFoundLuggageView.fxml";
        // set the view replacedle
        try {
            if (MainApp.language.equals("dutch")) {
                MainViewController.getInstance().getreplacedle(replacedLE_DUTCH);
            } else {
                MainViewController.getInstance().getreplacedle(replacedLE);
            }
        } catch (IOException ex) {
            Logger.getLogger(ServiceHomeViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        // initialize and set al the comboboxes
        initializeComboBoxes();
        // try to set the lost fields
        try {
            setLostFields(getManualLostLuggageResultSet());
        } catch (SQLException ex) {
            Logger.getLogger(ServiceEditLostLuggageViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        // get start values of the fields
        startValues = getFields();
        // otherwise there will be a grey overlay (= not clickable)
        closeStackpane();
        // set screen status
        ServiceHomeViewController.setOnMatchingView(false);
        // preplacedenger field check
        checkPreplacedengerId();
    }

    /**
     * Here are all the combo boxes set with the right data
     *
     * @void initializing
     */
    private void initializeComboBoxes() {
        // set 2 objects to get the right data for the database          //color
        ServiceGetDataFromDB colors = new ServiceGetDataFromDB("color", LANGUAGE, null);
        // types
        ServiceGetDataFromDB types = new ServiceGetDataFromDB("luggagetype", LANGUAGE, null);
        // location
        // ServiceGetDataFromDB locations = new ServiceGetDataFromDB("location", LANGUAGE, null);
        // try to get the data from the database and set it
        try {
            // get the right string list for each combo box
            ObservableList<String> colorsStringList = colors.getStringList();
            ObservableList<String> luggageStringList = types.getStringList();
            // set the string lists to the combo boxes
            colorPicker1.gereplacedems().addAll(colorsStringList);
            colorPicker2.gereplacedems().addAll(colorsStringList);
            typePicker.gereplacedems().addAll(luggageStringList);
        } catch (SQLException ex) {
            Logger.getLogger(ServiceEditLostLuggageViewController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Here will the resultSet of the found manual matching luggage be get
     * For getting the right resultSet the correct instance id will be preplaceded
     *
     * @return resultSet     resultSet for the right luggage
     * @throws java.sql.SQLException
     */
    @Override
    public ResultSet getManualLostLuggageResultSet() throws SQLException {
        ServiceDataLost detailsItem = new ServiceDataLost();
        String id = LostLuggageDetailsInstance.getInstance().currentLuggage().getRegistrationNr();
        ResultSet resultSet = detailsItem.getAllDetailsLost(id);
        return resultSet;
    }

    /**
     * Here are all the detail fields been set with the right data from:
     * The resultSet given
     *
     * @param resultSet         this will be converted to temp strings and integers
     * @throws java.sql.SQLException
     * @void no direct          the fields will be set within this method
     */
    @FXML
    @Override
    public void setLostFields(ResultSet resultSet) throws SQLException {
        // loop trough all the luggages in the resultSet
        // Note: there will be only one
        while (resultSet.next()) {
            int getRegistrationNr = resultSet.getInt("F.registrationNr");
            String getDateLost = resultSet.getString("F.dateLost");
            String getTimeLost = resultSet.getString("F.timeLost");
            String getLuggageTag = resultSet.getString("F.luggageTag");
            String getLuggageType = resultSet.getString("T." + LANGUAGE);
            String getBrand = resultSet.getString("F.brand");
            String getMainColor = resultSet.getString("c1." + LANGUAGE);
            String getSecondColor = resultSet.getString("c2." + LANGUAGE);
            String getSize = resultSet.getString("F.size");
            String getWeight = resultSet.getString("F.weight");
            String getOtherCharacteristics = resultSet.getString("F.otherCharacteristics");
            int getPreplacedengerId = resultSet.getInt("F.preplacedengerId");
            String getName = resultSet.getString("P.name");
            String getAddress = resultSet.getString("P.address");
            String getPlace = resultSet.getString("P.place");
            String getPostalcode = resultSet.getString("P.postalcode");
            String getCountry = resultSet.getString("P.country");
            String getEmail = resultSet.getString("P.email");
            String getPhone = resultSet.getString("P.phone");
            String getFlight = resultSet.getString("F.Flight");
            colorPicker1.setValue(getMainColor);
            colorPicker2.setValue(getSecondColor);
            typePicker.setValue(getLuggageType);
            registrationNr.setText(Integer.toString(getRegistrationNr));
            luggageTag.setText(getLuggageTag);
            brand.setText(getBrand);
            size.setText(getSize);
            weight.setText(getWeight);
            signatures.setText(getOtherCharacteristics);
            preplacedangerId.setText(Integer.toString(getPreplacedengerId));
            preplacedangerName.setText(getName);
            address.setText(getAddress);
            place.setText(getPlace);
            postalCode.setText(getPostalcode);
            country.setText(getCountry);
            email.setText(getEmail);
            phone.setText(getPhone);
            // locationFound.setText(getLocationFound);
            dateLost.setText(getDateLost);
            timeLost.setText(getTimeLost);
            flight.setText(getFlight);
        }
    }

    /**
     * Here will all the values of the fields be get and stored in an array
     *
     * @return String[]        all the string values of the fields
     */
    public String[] getFields() {
        String[] values = new String[AMOUNT_OF_FIELDS];
        values[0] = registrationNr.getText();
        values[1] = luggageTag.getText();
        values[2] = brand.getText();
        values[3] = size.getText();
        values[4] = weight.getText();
        values[5] = signatures.getText();
        values[6] = preplacedangerId.getText();
        values[7] = preplacedangerName.getText();
        values[8] = address.getText();
        values[9] = place.getText();
        values[10] = postalCode.getText();
        values[11] = country.getText();
        values[12] = email.getText();
        values[13] = phone.getText();
        values[14] = dateLost.getText();
        values[15] = timeLost.getText();
        values[16] = flight.getText();
        values[17] = colorPicker1.getValue().toString();
        values[18] = colorPicker2.getValue().toString();
        // values[19] = locationPicker.getValue().toString();
        values[19] = typePicker.getValue().toString();
        return values;
    }

    /**
     * This method is activated by the 'add to manual matching ' button
     * The view will be switched and the right instance be set
     *
     * @throws java.io.IOException      switching views
     * @void no direct output
     */
    @FXML
    public void manualMatch() throws IOException {
        // initialize the right id in the manual lost instance
        LostLuggage preplacedObject = LostLuggageDetailsInstance.getInstance().currentLuggage();
        LostLuggageManualMatchingInstance.getInstance().currentLuggage().setRegistrationNr(preplacedObject.getRegistrationNr());
        // set the reset status to false, no reset needed
        ServiceHomeViewController.resetMatching = false;
        // switch to the matching view
        MainApp.switchView("/Views/Service/ServiceMatchingView.fxml");
    }

    /**
     * This method is activated by the 'save/ confirm changes ' button
     * The changes will be checked and if the changeCountDoubleCheck count is 2 or higher:
     *      update the luggage and switch the view
     *
     * @throws java.sql.SQLException
     * @throws java.io.IOException      (possible) switching views
     * @void no direct output
     */
    @FXML
    public void saveEditings() throws SQLException, IOException {
        // chack changes of the fields
        checkChanges();
        if (changeCountDoubleCheck == SINGLE_CLICK) {
            saveEditings.setText("Confirm again");
        } else // is pressed two times - > confimered
        if (changeCountDoubleCheck >= DOUBLE_CLICK) {
            // reset the label of the button
            saveEditings.setText("Save changes");
            // update the luggage
            updateLuggage();
            // switch the view
            MainApp.switchView("/Views/Service/ServiceOverviewLostView.fxml");
        }
    }

    public void checkChanges() {
        // reset changedfield string and changes count
        changedFields = "";
        changes = 0;
        // string array to compare fields
        String[] newValues = getFields();
        // loop trough al field values
        for (int i = 0; i < startValues.length; i++) {
            // if start value of .. field is the same as new value
            if (startValues[i].equals(newValues[i])) {
                // use an switch to set that field to the right unFocusColor
                switch(i) {
                    case 0:
                        registrationNr.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 1:
                        luggageTag.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 2:
                        brand.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 3:
                        size.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 4:
                        weight.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 5:
                        signatures.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 6:
                        preplacedangerId.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 7:
                        preplacedangerName.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 8:
                        address.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 9:
                        place.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 10:
                        postalCode.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 11:
                        country.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 12:
                        email.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 13:
                        phone.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 14:
                        dateLost.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 15:
                        timeLost.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 16:
                        flight.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 17:
                        colorPicker1.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 18:
                        colorPicker2.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                    case 19:
                        typePicker.setUnFocusColor(Paint.valueOf(UN_FOCUS_COLOR));
                        break;
                }
            } else {
                // if the comparison is not equal, 1 changes made
                changes++;
                // use an switch to set that field to the right noticeColor
                // And add the right field to the changed field string for the alert
                switch(i) {
                    case 0:
                        registrationNr.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += "registrationNr";
                        break;
                    case 1:
                        luggageTag.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", luggageTag";
                        break;
                    case 2:
                        brand.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", brand";
                        break;
                    case 3:
                        size.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", size";
                        break;
                    case 4:
                        weight.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", weight";
                        break;
                    case 5:
                        signatures.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", signatures";
                        break;
                    case 6:
                        preplacedangerId.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", id ";
                        break;
                    case 7:
                        preplacedangerName.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", name";
                        break;
                    case 8:
                        address.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", registrationNr";
                        break;
                    case 9:
                        place.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", place";
                        break;
                    case 10:
                        postalCode.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", postal code";
                        break;
                    case 11:
                        country.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", registrationNr";
                        break;
                    case 12:
                        email.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", Email";
                        break;
                    case 13:
                        phone.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", phone";
                        break;
                    case 14:
                        dateLost.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", date";
                        break;
                    case 15:
                        timeLost.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", time";
                        break;
                    case 16:
                        flight.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", flight";
                        break;
                    case 17:
                        colorPicker1.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", main color";
                        break;
                    case 18:
                        colorPicker2.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", secondary color";
                        break;
                    case 19:
                        typePicker.setUnFocusColor(Paint.valueOf(NOTICE_COLOR));
                        changedFields += ", type";
                        break;
                    default:
                        // no more
                        break;
                }
            }
        }
        // reset start fields
        startValues = getFields();
        // if amount of changes equals zero
        // no more changes made so change count gets ++
        if (changes == 0) {
            changeCountDoubleCheck++;
        } else {
            saveEditings.setText("Save changes");
            // if there are some changes:
            // Alert this with an dialog
            alertDialog(changedFields, changes);
            // reset change count double check
            changeCountDoubleCheck = 0;
        }
    }

    /**
     * Here will the luggage be updated
     *
     *      update the luggage and switch the view
     *
     * @param changedFields
     * @param changes
     * @void no direct output, only a alert dialog
     */
    public void alertDialog(String changedFields, int changes) {
        // Remove the first , (comma) and space
        changedFields = changedFields.substring(2);
        // Clear the previous message
        CONTENT.getHeading().clear();
        ALERT_MESSAGE.getChildren().clear();
        // Set heading of dialog
        CONTENT.setHeading(new Text("Warning"));
        // Set the right text for the dialog body.
        String introAlert, outroAlert;
        if (changes == 1) {
            // singular
            introAlert = "There is " + changes + " change made. \n" + "The changed field is the following: \n\n";
            outroAlert = "\n\nPlease check and confirm it.";
        } else {
            // plural
            introAlert = "There are " + changes + " changes made. \n" + "The changed fields are the following: \n\n";
            outroAlert = "\n\nPlease check and confirm them.";
        }
        Text intro = new Text(introAlert);
        Text changed = new Text(changedFields);
        Text outro = new Text(outroAlert);
        // set text color of changed field string to red
        changed.setFill(Color.web(ALERT_COLOR));
        // combine the text parts
        ALERT_MESSAGE.getChildren().addAll(intro, changed, outro);
        // set the text parts (alert message) in the content
        CONTENT.setBody(ALERT_MESSAGE);
        // create the dialog alert with the content
        // & place het in the center of the stackpane
        JFXDialog alert = new JFXDialog(stackPane, CONTENT, JFXDialog.DialogTransition.CENTER);
        // Create the 'ok'/close button
        JFXButton button = new JFXButton("ok");
        button.setOnAction((ActionEvent event) -> {
            alert.close();
            // hide the stackpane so the fields will be clickable again
            closeStackpane();
        });
        // set action button in content for alert
        CONTENT.setActions(button);
        // Show the alert message (dialog)
        alert.show();
        // show the stackpane so the dialog will be visible
        stackPane.setVisible(true);
        // change the text on the 'save changes'  button
        saveEditings.setText("Confirm Changes");
    }

    /**
     * Here will the all the fields be updated
     * The unknown fields are also cleared
     *
     * @throws SQLException      executing multiple update query s
     * @void no direct output
     */
    public void updateLuggage() throws SQLException {
        String regisrationNr = registrationNr.getText();
        // Initializing 3 objects with the right fields to get the idCode
        // Note: To get the id the Where statement is also configured for each
        ServiceGetDataFromDB getRalCode1 = new ServiceGetDataFromDB("color", "ralCode", "WHERE `" + LANGUAGE + "`='" + colorPicker1.getValue().toString() + "'");
        ralCode1 = getRalCode1.getIdValue();
        ServiceGetDataFromDB getRalCode2 = new ServiceGetDataFromDB("color", "ralCode", "WHERE `" + LANGUAGE + "`='" + colorPicker2.getValue().toString() + "'");
        ralCode2 = getRalCode2.getIdValue();
        ServiceGetDataFromDB getType = new ServiceGetDataFromDB("luggagetype", "luggageTypeId", "WHERE `" + LANGUAGE + "`='" + typePicker.getValue().toString() + "'");
        typeCode = getType.getIdValue();
        // check all the fields that still needs an (potential) update and are empty
        // and ensure those fields are cleared properly (remove: unknown)
        checkForEmptyFields();
        // check if this field is not (still) unasigned
        if (typeCode != 0) {
            // if it is asigned (so not 0) than update that field
            // note: use of prepared statements to prevent sql injection!
            DB.executeUpdateLuggageFieldQuery("lostluggage", "luggageType", Integer.toString(typeCode), regisrationNr);
        }
        // repeat
        if (ralCode1 != 0) {
            DB.executeUpdateLuggageFieldQuery("lostluggage", "mainColor", Integer.toString(ralCode1), regisrationNr);
        }
        if (ralCode2 != 0) {
            DB.executeUpdateLuggageFieldQuery("lostluggage", "secondColor", Integer.toString(ralCode2), regisrationNr);
        }
        // validate the weight inputted
        int weightInt = isValidInt(weight.getText());
        if (weightInt != 0) {
            // if the return wasn't 0, update the weight with a prepared statment
            DB.executeUpdateLuggageFieldQuery("lostluggage", "weight", Integer.toString(weightInt), regisrationNr);
        }
        // validate the date inputted
        String dateString = isValidDate(dateLost.getText());
        if (dateString != null) {
            // if the date is not null, than the date format is good
            // but still needs checking for invalid year, month and day..
            // update the date found with a prepared statment
            DB.executeUpdateLuggageFieldQuery("lostluggage", "dateLost", dateString, regisrationNr);
        }
        // validate the time inputted
        String timeString = isValidTime(timeLost.getText());
        if (timeString != null) {
            // update the time found with a prepared statment
            DB.executeUpdateLuggageFieldQuery("lostluggage", "timeLost", timeString, regisrationNr);
        }
        // Update the luggage itself with the right data
        DB.executeUpdateLuggageQuery(luggageTag.getText(), brand.getText(), size.getText(), signatures.getText(), regisrationNr, "lostluggage");
        // check if the preplacedenger (id) is not empty
        if (!"".equals(preplacedangerId.getText()) || null != preplacedangerId.getText()) {
            // Update the preplacedenger with the right data
            DB.executeUpdatePreplacedengerQuery(preplacedangerName.getText(), address.getText(), place.getText(), postalCode.getText(), country.getText(), email.getText(), phone.getText(), preplacedangerId.getText());
        }
    }

    /**
     * Check if the preplacedenger is set or not
     * If there isn't a preplacedenger set:
     *     disable all the preplacedenger related fields
     *     so there can't be a new inserted
     *
     * @void
     */
    private void checkPreplacedengerId() {
        // if the preplacedenger id is empty or zero, disable them
        if ("".equals(preplacedangerId.getText()) || 0 == Integer.parseInt(preplacedangerId.getText())) {
            preplacedangerId.setDisable(true);
            preplacedangerName.setDisable(true);
            address.setDisable(true);
            place.setDisable(true);
            postalCode.setDisable(true);
            country.setDisable(true);
            email.setDisable(true);
            phone.setDisable(true);
        }
    }

    /**
     * When closing the alert message the stackPane isn't disabled automatic
     * So this method is for closing the stack pane by chancing it's visibility
     */
    @FXML
    public void closeStackpane() {
        stackPane.setVisible(false);
    }

    /**
     * When updating the fields there must be checked if the fields maybe contain
     * The preset: unknown message
     *
     * Note: for optimizing is there a array of fields used here.
     */
    private void checkForEmptyFields() {
        // check if one of the updated fields contains the "unknown" string
        if (size.getText().contains("unknown")) {
            size.setText("0");
        }
        if (weight.getText().contains("unknown")) {
            weight.setText("0");
        }
        if (signatures.getText().contains("unknown")) {
            signatures.setText("");
        }
        // asign fields that can be checked in an loop in an array
        JFXTextField[] fields = { luggageTag, brand, preplacedangerName, address, place, postalCode, country, email, phone, flight };
        // loop trough all the fields
        for (JFXTextField field : fields) {
            // check if it contains the unknown string
            if (field.getText().contains("unknown")) {
                // clear it
                field.setText("");
            }
        }
    }

    /**
     * When the 'view potentials ' button is clicked the potential list will be
     * Initialized by getting the right data, clear the previous list,
     * getting the instance id and preplaceding this to the data object
     *
     * @param event                     when the button is clicked
     * @throws java.io.IOException      switching views
     * @throws java.sql.SQLException    getting data from the db
     */
    @FXML
    public void viewPotentials(ActionEvent event) throws SQLException, IOException {
        // get the right data object
        ServiceDataMatch data = ServiceHomeViewController.getMATCH_DATA();
        // set the reset status to true for resetting a possible previous list
        ServiceHomeViewController.setPotentialResetStatus(true);
        // get the id of the current luggage
        ServiceHomeViewController.setPotentialResetStatus(true);
        // get the id of the current luggage
        String id = registrationNr.getText();
        // initialize the potential matches for the given id
        data.potentialMatchesForLostLuggage(id);
        // switch to the matching view
        MainApp.switchView("/Views/Service/ServiceMatchingView.fxml");
        // set the right tab, 2 = potential matching tab
        ServiceMatchingViewController.getInstance().setMatchingTab(ServiceMatchingViewController.POTENTIAL_MATCHING_TAB_INDEX);
    }
}

13 Source : MainController.java
with Apache License 2.0
from HouariZegai

public clreplaced MainController implements Initializable {

    @FXML
    private StackPane root;

    @FXML
    private JFXComboBox<String> comboNetworkName;

    @FXML
    private Label lblIpAddress;

    @FXML
    private ImageView imgQRCode;

    @FXML
    private Label lblStatus;

    public static JFXDialog aboutDialog;

    private SocketServer socketServer;

    // Available network addresses in my PC
    private static Map<String, String> networkAddresses;

    // Used to make stage draggable
    private double xOffset = 0;

    private double yOffset = 0;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // Init dialog
        try {
            Region aboutView = FXMLLoader.load(getClreplaced().getResource("/fxml/about.fxml"));
            aboutDialog = new JFXDialog(root, aboutView, JFXDialog.DialogTransition.CENTER);
        } catch (IOException e) {
            e.printStackTrace();
        }
        comboNetworkName.valueProperty().addListener(e -> {
            updateIpLbl();
            changeQRCodeImg();
        });
        /* Make stage draggable */
        root.setOnMousePressed(event -> {
            xOffset = event.getSceneX();
            yOffset = event.getSceneY();
        });
        root.setOnMouseDragged(event -> {
            App.stage.setX(event.getScreenX() - xOffset);
            App.stage.setY(event.getScreenY() - yOffset);
            App.stage.setOpacity(0.7f);
        });
        root.setOnDragDone(e -> App.stage.setOpacity(1.0f));
        root.setOnMouseReleased(e -> App.stage.setOpacity(1.0f));
        onRefresh();
    }

    @FXML
    private void onRefresh() {
        comboNetworkName.gereplacedems().clear();
        networkAddresses = NetworkUtils.getMyIPv4Addresses();
        if (!networkAddresses.isEmpty()) {
            for (String key : networkAddresses.keySet()) {
                comboNetworkName.gereplacedems().add(key);
            }
            changeQRCodeImg();
        }
    }

    @FXML
    private void onStart() {
        socketServer = new SocketServer();
        if (RegexChecker.isIP(lblIpAddress.getText())) {
            socketServer.start();
            lblStatus.setText("Connected");
        } else {
            lblStatus.setText("Disconnected");
        }
    }

    @FXML
    private void onStop() {
        socketServer.stop();
        lblStatus.setText("Disconnected");
    }

    @FXML
    private void onClose() {
        Platform.exit();
    }

    @FXML
    private void onHide() {
        App.stage.setIconified(true);
    }

    @FXML
    void onAbout() {
        aboutDialog.show();
    }

    private void changeQRCodeImg() {
        String myIP = lblIpAddress.getText();
        if (RegexChecker.isIP(myIP)) {
            Image generatedQRCode = QRCodeEngine.encode(myIP, 250, 250);
            if (generatedQRCode != null) {
                imgQRCode.setImage(generatedQRCode);
                lblStatus.setText("Ready to start");
            } else {
                lblStatus.setText("Disconnected! - Generation QRCode problem");
            }
        }
    }

    private void updateIpLbl() {
        String selectedNetworkName = networkAddresses.get(comboNetworkName.getSelectionModel().getSelectedItem());
        lblIpAddress.setText(selectedNetworkName);
    }
}

13 Source : PrayerTimesController.java
with MIT License
from HouariZegai

public clreplaced PrayerTimesController implements Initializable {

    @FXML
    private StackPane menuBar;

    @FXML
    private JFXHamburger hamburgerMenu;

    @FXML
    private JFXComboBox<String> comboCities;

    @FXML
    private Label lblDate;

    @FXML
    private Label lblTimeH, lblTimeSeparator, lblTimeM, lblTimeSeparator2, lblTimeS;

    @FXML
    private Label lblPrayerFajr, lblPrayerSunrise, lblPrayerDhuhr, lblPrayerAsr, lblPrayerMaghrib, lblPrayerIsha;

    /* Adhan part */
    @FXML
    private StackPane alarmView;

    @FXML
    private Text txtAlarmPrayer, txtAlarmCity;

    /* Settings part */
    @FXML
    private VBox settingsView;

    @FXML
    private JFXToggleButton tglRunAdhan;

    @FXML
    private JFXComboBox<String> comboAdhan;

    @FXML
    private FontIcon iconPlayAdhan;

    private HamburgerBasicCloseTransition hamburgerTransition;

    // Used to make stage draggable
    private double xOffset = 0;

    private double yOffset = 0;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initMenu();
        initDateAndClock();
        initComboCities();
        // load saved app stat
        loadSettingsLog();
        initAdhan();
        /* Make stage draggable */
        menuBar.setOnMousePressed(event -> {
            xOffset = event.getSceneX();
            yOffset = event.getSceneY();
        });
        menuBar.setOnMouseDragged(event -> {
            App.stage.setX(event.getScreenX() - xOffset);
            App.stage.setY(event.getScreenY() - yOffset);
            App.stage.setOpacity(0.7f);
        });
        menuBar.setOnDragDone(e -> App.stage.setOpacity(1.0f));
        menuBar.setOnMouseReleased(e -> App.stage.setOpacity(1.0f));
    }

    private void initDateAndClock() {
        /* Init clock (date & time) of prayer times */
        KeyFrame clockKeyFrame = new KeyFrame(Duration.ZERO, e -> {
            Date date = new Date();
            DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
            lblDate.setText(dateFormat.format(date));
            dateFormat = new SimpleDateFormat("HH:mm:ss");
            String[] time = dateFormat.format(date).split(":");
            lblTimeS.setText(time[2]);
            lblTimeM.setText(time[1]);
            lblTimeH.setText(time[0]);
            // Is it new day? => change the prayer times
            if (dateFormat.equals("00:00:00") && comboCities.getSelectionModel() != null) {
                setPrayerTimes(comboCities.getSelectionModel().getSelectedItem());
            }
            checkAdhanTime();
        });
        Timeline clock = new Timeline(clockKeyFrame, new KeyFrame(Duration.seconds(1)));
        clock.setCycleCount(Animation.INDEFINITE);
        clock.play();
        // Show/Hide animation for time separator
        KeyFrame clockSeparatorKeyFrame = new KeyFrame(Duration.ZERO, e -> {
            if (lblTimeSeparator.isVisible()) {
                lblTimeSeparator.setVisible(false);
                lblTimeSeparator2.setVisible(false);
            } else {
                lblTimeSeparator.setVisible(true);
                lblTimeSeparator2.setVisible(true);
            }
        });
        Timeline clockSeparator = new Timeline(clockSeparatorKeyFrame, new KeyFrame(Duration.millis(500)));
        clockSeparator.setCycleCount(Animation.INDEFINITE);
        clockSeparator.play();
    }

    private void initComboCities() {
        comboCities.gereplacedems().setAll(Constants.DZ_CITIES);
        comboCities.setOnAction(e -> setPrayerTimes(comboCities.getSelectionModel().getSelectedItem()));
    }

    private void initAdhan() {
        Adhan.setAdhan(comboAdhan.getSelectionModel().getSelectedItem());
    }

    private void setPrayerTimes(String city) {
        city = // format City
        city.replaceAll(" ", "-").replaceAll("é", "e").replaceAll("è", "e").replaceAll("â", "a").replaceAll("'", "-").replaceAll("ï", "i");
        // Get prayer times from web service
        PrayerTimes prayerTimes = WebService.getPrayerTimes(city);
        lblPrayerFajr.setText(prayerTimes.getFajr());
        lblPrayerSunrise.setText(prayerTimes.getSunrise());
        lblPrayerDhuhr.setText(prayerTimes.getDhuhr());
        lblPrayerAsr.setText(prayerTimes.getAsr());
        lblPrayerMaghrib.setText(prayerTimes.getMaghrib());
        lblPrayerIsha.setText(prayerTimes.getIsha());
    }

    @FXML
    private void onClose() {
        saveSettingsLog();
        // Platform.exit();
        App.stage.hide();
    }

    @FXML
    private void onHide() {
        App.stage.setIconified(true);
    }

    /* Alarm (Adhan) part */
    private void checkAdhanTime() {
        String timeNow = lblTimeH.getText() + ":" + lblTimeM.getText();
        checkTimeWithPrayer(timeNow, lblPrayerFajr, "ال-جر");
        checkTimeWithPrayer(timeNow, lblPrayerDhuhr, "الظهر");
        checkTimeWithPrayer(timeNow, lblPrayerAsr, "العصر");
        checkTimeWithPrayer(timeNow, lblPrayerMaghrib, "المغرب");
        checkTimeWithPrayer(timeNow, lblPrayerIsha, "العشاء");
    }

    private void checkTimeWithPrayer(String time, Label lblPrayerTime, String prayerName) {
        // Check if it's the time of prayer
        if (time.equals(lblPrayerTime.getText()) && Adhan.canPlay() && !Adhan.isPlaying() && tglRunAdhan.isSelected()) {
            Adhan.setCanPlay(false);
            txtAlarmCity.setText(comboCities.getSelectionModel().getSelectedItem());
            txtAlarmPrayer.setText(prayerName);
            setShowView(true, alarmView);
            Adhan.play();
        }
    }

    @FXML
    public void onCloseAlarm() {
        setShowView(false, alarmView);
        Adhan.pause();
        Adhan.launchPeriodStop();
    }

    /* Settings part */
    private void initMenu() {
        // Init settings
        /* Init show/hide menu */
        hamburgerTransition = new HamburgerBasicCloseTransition(hamburgerMenu);
        hamburgerTransition.setRate(-1);
        hamburgerMenu.addEventHandler(MouseEvent.MOUSE_CLICKED, e -> {
            if (hamburgerTransition.getRate() == -1) {
                hamburgerTransition.setRate(1);
                setShowView(true, settingsView);
            } else {
                hamburgerTransition.setRate(-1);
                setShowView(false, settingsView);
                Adhan.pause();
            }
            hamburgerTransition.play();
        });
        /* Init Adan combobox */
        List<String> adhanFilesName = Tools.getFilesNameFromFolder(Constants.RESOURCES_PATH + "adhan");
        if (adhanFilesName != null && !adhanFilesName.isEmpty())
            comboAdhan.gereplacedems().addAll(Optional.ofNullable(adhanFilesName).get());
        comboAdhan.setOnAction(e -> {
            initAdhan();
            iconPlayAdhan.setIconLiteral(FontAwesome.PLAY.getDescription());
        });
        // Init play/pause test adan
        iconPlayAdhan.setOnMouseClicked(e -> {
            if (iconPlayAdhan.getIconLiteral().equals(FontAwesome.PLAY.getDescription())) {
                Adhan.play();
                iconPlayAdhan.setIconLiteral(FontAwesome.PAUSE.getDescription());
            } else {
                Adhan.pause();
                iconPlayAdhan.setIconLiteral(FontAwesome.PLAY.getDescription());
            }
        });
    }

    @FXML
    private void onCloseMenu() {
        setShowView(false, settingsView);
        hamburgerTransition.setRate(-1);
        hamburgerTransition.play();
        Adhan.pause();
    }

    private void setShowView(boolean show, Parent view) {
        ScaleTransition scaleTransition = new ScaleTransition(Duration.millis(500), view);
        if (show) {
            view.setVisible(true);
            scaleTransition.setFromX(0);
            scaleTransition.setFromY(0);
            scaleTransition.setToX(1);
            scaleTransition.setToY(1);
        } else {
            scaleTransition.setFromX(1);
            scaleTransition.setFromY(1);
            scaleTransition.setToX(0);
            scaleTransition.setToY(0);
            scaleTransition.setOnFinished(e -> view.setVisible(false));
        }
        scaleTransition.play();
    }

    private void loadSettingsLog() {
        ResourceBundle bundle = ResourceBundle.getBundle("config.settings");
        // Make Tiaret city by default :D
        comboCities.getSelectionModel().select(Integer.parseInt(toUTF(bundle.getString("city"))));
        setPrayerTimes(comboCities.getSelectionModel().getSelectedItem());
        tglRunAdhan.setSelected(Boolean.valueOf(toUTF((bundle.getString("enableAdhan")))));
        comboAdhan.getSelectionModel().select(Integer.parseInt(toUTF((bundle.getString("adhan")))));
    }

    private void saveSettingsLog() {
        Properties prop = new Properties();
        OutputStream output = null;
        try {
            output = new FileOutputStream(Constants.RESOURCES_PATH + "config\\settings.properties");
            // Set the properties value
            prop.setProperty("city", String.valueOf(comboCities.getSelectionModel().getSelectedIndex()));
            prop.setProperty("enableAdhan", String.valueOf(tglRunAdhan.isSelected()));
            prop.setProperty("adhan", String.valueOf(comboAdhan.getSelectionModel().getSelectedIndex()));
            // Save properties to project root folder
            prop.store(output, null);
        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String toUTF(String val) {
        try {
            return new String(val.getBytes("ISO-8859-1"), "UTF-8");
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }
}

13 Source : ManageQuestionController.java
with MIT License
from HouariZegai

public clreplaced ManageQuestionController implements Initializable {

    @FXML
    public StackPane root;

    @FXML
    private Label replacedleLabel;

    @FXML
    public Label errorLabel;

    @FXML
    public JFXTextField searchField;

    @FXML
    public JFXComboBox<String> comboSearchBy;

    @FXML
    public JFXTreeTableView treeTableView;

    // Cols of table
    @FXML
    public JFXTreeTableColumn<QuestionTable, String> idCol, questionTypeCol, questionCol, answerCol;

    public static JFXDialog addQuestionDialog, editQuestionDialog;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        comboSearchBy.gereplacedems().addAll(new String[] { "Id", "Question Type", "Question", "Answer" });
        editQuestionDialog = new JFXDialog();
        initializeTable();
    }

    clreplaced QuestionTable extends RecursiveTreeObject<QuestionTable> {

        StringProperty id;

        StringProperty questionType;

        StringProperty question;

        StringProperty answer;

        public QuestionTable(int id, String questionType, String question, String answer) {
            this.id = new SimpleStringProperty(String.valueOf(id));
            this.questionType = new SimpleStringProperty(questionType);
            this.question = new SimpleStringProperty(question);
            this.answer = new SimpleStringProperty(answer);
        }
    }

    public void initializeTable() {
        idCol = new JFXTreeTableColumn<>("Id");
        idCol.setPrefWidth(50);
        idCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<QuestionTable, String> param) -> param.getValue().getValue().id);
        questionTypeCol = new JFXTreeTableColumn<>("Type");
        questionTypeCol.setPrefWidth(90);
        questionTypeCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<QuestionTable, String> param) -> param.getValue().getValue().questionType);
        questionCol = new JFXTreeTableColumn<>("Question");
        questionCol.setPrefWidth(550);
        questionCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<QuestionTable, String> param) -> param.getValue().getValue().question);
        answerCol = new JFXTreeTableColumn<>("Answer");
        answerCol.setPrefWidth(450);
        answerCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<QuestionTable, String> param) -> param.getValue().getValue().answer);
        // Fill table by data imported from data base
        updateTable();
        treeTableView.getColumns().addAll(idCol, questionTypeCol, questionCol, answerCol);
        treeTableView.setShowRoot(false);
        searchField.textProperty().addListener(e -> {
            filterSearchTable();
        });
        comboSearchBy.setOnAction(e -> {
            filterSearchTable();
        });
    }

    public void filterSearchTable() {
        treeTableView.setPredicate(new Predicate<TreeItem<QuestionTable>>() {

            @Override
            public boolean test(TreeItem<QuestionTable> user) {
                switch(comboSearchBy.getSelectionModel().getSelectedIndex()) {
                    case 0:
                        return user.getValue().id.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                    case 1:
                        return user.getValue().questionType.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                    case 2:
                        return user.getValue().question.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                    case 3:
                        return user.getValue().answer.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                    default:
                        return user.getValue().id.getValue().toLowerCase().contains(searchField.getText().toLowerCase()) || user.getValue().questionType.getValue().toLowerCase().contains(searchField.getText().toLowerCase()) || user.getValue().question.getValue().toLowerCase().contains(searchField.getText().toLowerCase()) || user.getValue().answer.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                }
            }
        });
    }

    @FXML
    public void updateTable() {
        // get data from db and inserted to the table
        errorLabel.setText("");
        ObservableList<QuestionTable> questions = FXCollections.observableArrayList();
        // Get users from DB
        List<Question> questionsDao = new QuestionDao().getQuestion();
        if (questionsDao == null) {
            errorLabel.setText("Connection Failed !");
        } else {
            for (Question question : questionsDao) {
                questions.add(new QuestionTable(question.getId(), question.getQuestionType().substring(0, 1).toUpperCase() + question.getQuestionType().substring(1), question.getQuestion(), question.getAnswer()));
            }
        }
        final TreeItem<QuestionTable> treeItem = new RecursiveTreeItem<>(questions, RecursiveTreeObject::getChildren);
        try {
            treeTableView.setRoot(treeItem);
        } catch (Exception ex) {
            System.out.println("Error catched !");
        }
    }

    @FXML
    public void btnEdit() {
        // if i click to the edit button
        errorLabel.setText("");
        // selected index
        int index = treeTableView.getSelectionModel().getSelectedIndex();
        String id = idCol.getCellData(index);
        if (id == null) {
            // System.out.println("Index is null !");
            return;
        }
        questionSelected = new Question(Integer.parseInt(id), questionTypeCol.getCellData(index), questionCol.getCellData(index), answerCol.getCellData(index));
        AnchorPane editQuestionPane = null;
        try {
            editQuestionPane = FXMLLoader.load(getClreplaced().getResource("/com/houarizegai/learnsql/resources/views/form/EditQuestionForm.fxml"));
        } catch (IOException ex) {
            // System.out.println("Catched error FXML loader!");
            Logger.getLogger(EditQuestionFormController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        editQuestionDialog = getSpecialDialog(editQuestionPane);
        editQuestionDialog.show();
    }

    @FXML
    public void btnRemove() {
        // if i click to the remove button
        errorLabel.setText("");
        String id = idCol.getCellData(treeTableView.getSelectionModel().getSelectedIndex());
        if (id == null) {
            System.out.println("Index is null !");
            return;
        }
        JFXDialogLayout content = new JFXDialogLayout();
        Text headerText = new Text("Confirmation");
        Text contentText = new Text("Are you sure to delete this question ?");
        headerText.setStyle("-fx-font-size: 19px");
        contentText.setStyle("-fx-font-size: 18px");
        content.setHeading(headerText);
        content.setBody(contentText);
        JFXDialog dialog = new JFXDialog(root, content, JFXDialog.DialogTransition.CENTER);
        JFXButton btnOk = new JFXButton("Yes");
        btnOk.setOnAction(e -> {
            int status = new QuestionDao().deleteQuestion(id);
            System.out.println("status : " + status);
            if (status == -1) {
                errorLabel.setText("Connection Failed !");
            } else {
                Notifications.create().replacedle("You Successfuly removed question !").graphic(new ImageView(new Image("/com/houarizegai/learnsql/resources/images/icons/valid.png"))).hideAfter(Duration.millis(2000)).position(Pos.BOTTOM_RIGHT).darkStyle().show();
                updateTable();
            }
            dialog.close();
        });
        JFXButton btnNo = new JFXButton("No");
        btnOk.setPrefSize(120, 40);
        btnNo.setPrefSize(120, 40);
        btnOk.setStyle("-fx-font-size: 18px");
        btnNo.setStyle("-fx-font-size: 18px");
        content.setActions(btnOk, btnNo);
        StackPane stackpane = new StackPane();
        dialog.getStylesheets().add("/com/houarizegai/learnsql/resources/css/main.css");
        btnNo.setOnAction(e -> {
            dialog.close();
        });
        dialog.show();
    }

    @FXML
    public void btnAdd() {
        errorLabel.setText("");
        AnchorPane addQuestionPane = null;
        try {
            addQuestionPane = FXMLLoader.load(getClreplaced().getResource("/com/houarizegai/learnsql/resources/views/form/AddQuestionForm.fxml"));
            addQuestionDialog = getSpecialDialog(addQuestionPane);
            addQuestionDialog.show();
        } catch (IOException ex) {
            Logger.getLogger(ManageAccountController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public JFXDialog getSpecialDialog(AnchorPane content) {
        JFXDialog dialog = new JFXDialog(root, content, JFXDialog.DialogTransition.CENTER);
        dialog.setOnDialogClosed((event) -> {
            System.out.println("Preplaceded ..!");
            updateTable();
        });
        return dialog;
    }
}

13 Source : ManageAccountController.java
with MIT License
from HouariZegai

public clreplaced ManageAccountController implements Initializable {

    @FXML
    public StackPane root;

    @FXML
    private Label replacedleLabel;

    @FXML
    public Label errorLabel;

    @FXML
    public JFXTextField searchField;

    @FXML
    public JFXComboBox<String> combo;

    @FXML
    public JFXTreeTableView treeTableView;

    // Cols of table
    @FXML
    public JFXTreeTableColumn<UserTable, String> idCol, usernameCol, firstNameCol, lastNameCol, dateOfBirthCol, emailCol, userTypeCol, sectionCol, groupCol;

    public static JFXDialog addUserDialog, editUserDialog;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        combo.gereplacedems().addAll(new String[] { "Id", "Username", "First Name", "Last Name", "Date of birth", "Email", "Type", "Section", "Group" });
        initializeTable();
    }

    clreplaced UserTable extends RecursiveTreeObject<UserTable> {

        StringProperty id;

        StringProperty username;

        StringProperty firstName;

        StringProperty lastName;

        StringProperty dateOfBirth;

        StringProperty email;

        StringProperty studentOrTeacher;

        StringProperty section;

        StringProperty group;

        public UserTable(int id, String username, String firstName, String lastName, Date dateOfBirth, String email, boolean isTeacher, int section, int group) {
            this.id = new SimpleStringProperty(String.valueOf(id));
            this.username = new SimpleStringProperty(username);
            this.firstName = new SimpleStringProperty(firstName);
            this.lastName = new SimpleStringProperty(lastName);
            this.dateOfBirth = new SimpleStringProperty(dateOfBirth.toString());
            this.email = new SimpleStringProperty(email);
            this.studentOrTeacher = new SimpleStringProperty((isTeacher) ? "Teacher" : "Student");
            this.section = new SimpleStringProperty(String.valueOf(section));
            this.group = new SimpleStringProperty(String.valueOf(group));
        }
    }

    public void initializeTable() {
        idCol = new JFXTreeTableColumn<>("Id");
        idCol.setPrefWidth(50);
        idCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<UserTable, String> param) -> param.getValue().getValue().id);
        usernameCol = new JFXTreeTableColumn<>("Username");
        usernameCol.setPrefWidth(150);
        usernameCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<UserTable, String> param) -> param.getValue().getValue().username);
        firstNameCol = new JFXTreeTableColumn<>("First Name");
        firstNameCol.setPrefWidth(200);
        firstNameCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<UserTable, String> param) -> param.getValue().getValue().firstName);
        lastNameCol = new JFXTreeTableColumn<>("Last Name");
        lastNameCol.setPrefWidth(150);
        lastNameCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<UserTable, String> param) -> param.getValue().getValue().lastName);
        dateOfBirthCol = new JFXTreeTableColumn<>("Date Of Birth");
        dateOfBirthCol.setPrefWidth(100);
        dateOfBirthCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<UserTable, String> param) -> param.getValue().getValue().dateOfBirth);
        emailCol = new JFXTreeTableColumn<>("Email");
        emailCol.setPrefWidth(200);
        emailCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<UserTable, String> param) -> param.getValue().getValue().email);
        userTypeCol = new JFXTreeTableColumn<>("Type");
        userTypeCol.setPrefWidth(95);
        userTypeCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<UserTable, String> param) -> param.getValue().getValue().studentOrTeacher);
        sectionCol = new JFXTreeTableColumn<>("Section");
        sectionCol.setPrefWidth(100);
        sectionCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<UserTable, String> param) -> param.getValue().getValue().section);
        groupCol = new JFXTreeTableColumn<>("Group");
        groupCol.setPrefWidth(100);
        groupCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<UserTable, String> param) -> param.getValue().getValue().group);
        // Fill table by data imported from data base
        updateTable();
        treeTableView.getColumns().addAll(idCol, usernameCol, firstNameCol, lastNameCol, dateOfBirthCol, emailCol, userTypeCol, sectionCol, groupCol);
        treeTableView.setShowRoot(false);
        // this line bellow to select multi rows
        // treeTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        searchField.textProperty().addListener(e -> {
            filterSearchTable();
        });
        combo.setOnAction(e -> {
            filterSearchTable();
        });
    }

    public void filterSearchTable() {
        treeTableView.setPredicate(new Predicate<TreeItem<UserTable>>() {

            @Override
            public boolean test(TreeItem<UserTable> user) {
                switch(combo.getSelectionModel().getSelectedIndex()) {
                    case 0:
                        return user.getValue().id.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                    case 1:
                        return user.getValue().username.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                    case 2:
                        return user.getValue().firstName.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                    case 3:
                        return user.getValue().lastName.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                    case 4:
                        return user.getValue().dateOfBirth.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                    case 5:
                        return user.getValue().email.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                    case 6:
                        return user.getValue().studentOrTeacher.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                    case 7:
                        return user.getValue().section.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                    case 8:
                        return user.getValue().group.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                    default:
                        return user.getValue().id.getValue().toLowerCase().contains(searchField.getText().toLowerCase()) || user.getValue().username.getValue().toLowerCase().contains(searchField.getText().toLowerCase()) || user.getValue().firstName.getValue().toLowerCase().contains(searchField.getText().toLowerCase()) || user.getValue().lastName.getValue().toLowerCase().contains(searchField.getText().toLowerCase()) || user.getValue().dateOfBirth.getValue().toLowerCase().contains(searchField.getText().toLowerCase()) || user.getValue().email.getValue().toLowerCase().contains(searchField.getText().toLowerCase()) || user.getValue().studentOrTeacher.getValue().toLowerCase().contains(searchField.getText().toLowerCase()) || user.getValue().section.getValue().toLowerCase().contains(searchField.getText().toLowerCase()) || user.getValue().group.getValue().toLowerCase().contains(searchField.getText().toLowerCase());
                }
            }
        });
    }

    @FXML
    public void updateTable() {
        // get data from db and inserted to the table
        errorLabel.setText("");
        ObservableList<UserTable> users = FXCollections.observableArrayList();
        // Get users from DB
        List<User> usersDao = new UserDao().getUsers();
        if (usersDao == null) {
            errorLabel.setText("Connection Failed !");
        } else {
            for (User user : usersDao) {
                users.add(new UserTable(user.getId(), user.getUsername(), user.getFirstName().substring(0, 1).toUpperCase() + user.getFirstName().substring(1), user.getLastName().toUpperCase(), user.getDateOfBirth(), user.getEmail(), user.getIsTeacher(), user.getSection(), user.getGroup()));
            }
        }
        final TreeItem<UserTable> treeItem = new RecursiveTreeItem<>(users, RecursiveTreeObject::getChildren);
        try {
            treeTableView.setRoot(treeItem);
        } catch (Exception ex) {
            System.out.println("Error catched !");
        }
    }

    @FXML
    public void editUser() {
        // if i click to the edit button
        errorLabel.setText("");
        // selected index
        int index = treeTableView.getSelectionModel().getSelectedIndex();
        String id = idCol.getCellData(index);
        if (id == null) {
            return;
        }
        userSelected = new User();
        userSelected.setId(Integer.parseInt(id));
        userSelected.setUsername(usernameCol.getCellData(index));
        userSelected.setFirstName(firstNameCol.getCellData(index));
        userSelected.setLastName(lastNameCol.getCellData(index));
        userSelected.setDateOfBirth(Date.valueOf(dateOfBirthCol.getCellData(index)));
        userSelected.setEmail(emailCol.getCellData(index));
        userSelected.setIsTeacher(userTypeCol.getCellData(index).toLowerCase().equals("teacher"));
        if (userTypeCol.getCellData(index).toLowerCase().equals("student")) {
            userSelected.setSection(Integer.parseInt(sectionCol.getCellData(index)) - 1);
            userSelected.setGroup(Integer.parseInt(groupCol.getCellData(index)) - 1);
        }
        AnchorPane editUserPane = null;
        try {
            editUserPane = FXMLLoader.load(getClreplaced().getResource("/com/houarizegai/learnsql/resources/views/form/EditUserForm.fxml"));
        } catch (IOException ex) {
            Logger.getLogger(ManageAccountController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        editUserDialog = getSpecialDialog(editUserPane);
        editUserDialog.show();
    }

    @FXML
    public void removeUser() {
        // if i click to the remove button
        errorLabel.setText("");
        String id = idCol.getCellData(treeTableView.getSelectionModel().getSelectedIndex());
        if (id == null) {
            System.out.println("Index is null !");
            return;
        }
        JFXDialogLayout content = new JFXDialogLayout();
        Text headerText = new Text("Confirmation");
        Text contentText = new Text("Are you sure to delete this user ?");
        headerText.setStyle("-fx-font-size: 19px");
        contentText.setStyle("-fx-font-size: 18px");
        content.setHeading(headerText);
        content.setBody(contentText);
        JFXDialog dialog = new JFXDialog(root, content, JFXDialog.DialogTransition.CENTER);
        JFXButton btnOk = new JFXButton("Yes");
        btnOk.setOnAction(e -> {
            int status = new UserDao().deleteUser(id);
            System.out.println("status : " + status);
            if (status == -1) {
                errorLabel.setText("Connection Failed !");
            } else {
                // Notifications notification = Notifications.create()
                // .replacedle("You Successfuly removed user !")
                // .graphic(new ImageView(new Image("/com/houarizegai/learnsql/resources/images/icons/valid.png")))
                // .hideAfter(Duration.millis(2000))
                // .position(Pos.BOTTOM_RIGHT);
                // notification.darkStyle();
                // notification.show();
                updateTable();
            }
            dialog.close();
        });
        JFXButton btnNo = new JFXButton("No");
        btnOk.setPrefSize(120, 40);
        btnNo.setPrefSize(120, 40);
        btnOk.setStyle("-fx-font-size: 18px");
        btnNo.setStyle("-fx-font-size: 18px");
        content.setActions(btnOk, btnNo);
        StackPane stackpane = new StackPane();
        dialog.getStylesheets().add("/com/houarizegai/learnsql/resources/css/main.css");
        btnNo.setOnAction(e -> {
            dialog.close();
        });
        dialog.show();
    }

    @FXML
    public void addUser() {
        errorLabel.setText("");
        AnchorPane addUserPane = null;
        try {
            addUserPane = FXMLLoader.load(getClreplaced().getResource("/com/houarizegai/learnsql/resources/views/form/AddUserForm.fxml"));
        } catch (IOException ex) {
            Logger.getLogger(ManageAccountController.clreplaced.getName()).log(Level.SEVERE, null, ex);
        }
        addUserDialog = getSpecialDialog(addUserPane);
        addUserDialog.show();
    }

    public JFXDialog getSpecialDialog(AnchorPane content) {
        JFXDialog dialog = new JFXDialog(root, content, JFXDialog.DialogTransition.CENTER);
        dialog.setOnDialogClosed((event) -> {
            updateTable();
        });
        return dialog;
    }
}

See More Examples