I have a program that searches an observable list and displays all of the matching cases on the table. The search works fine, but I am only able to run this part of the program once. The search button stops responding after the program has returned to displaying the full observable list.
I have a separate class(Search.class) that handles all of the logic for searching the observable list.
The code for the search button and text field are below:
partSearchBtn.setOnAction(searchPartEvent ->{
ObservableList<Part> searchPartDisplay = FXCollections.observableArrayList();
String searchQuery = partSearchField.getText();
try{
searchPartDisplay = Search.searchPartByNumber(Integer.parseInt(searchQuery));
partTable.setItems(searchPartDisplay);
partSearchBtn.setText("Clear");
partSearchBtn.setOnAction(clearSearchEvent ->{
partSearchBtn.setText("Search");
partTable.setItems(Inventory.partBin);
});
} catch(NumberFormatException hasText){
searchPartDisplay = Search.searchPartByText(searchQuery);
partTable.setItems(searchPartDisplay);
partSearchBtn.setText("Clear");
partSearchBtn.setOnAction(clearSearchEvent ->{
partSearchBtn.setText("Search");
partTable.setItems(Inventory.partBin);
});
}
});
What changes would I need to make to re-run the search process?
Or should I turn this into a method as part of my Search class that I can reuse?
The search logic is below:
package inventorymngmnt;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class Search {
public static ObservableList<Part> searchPartByNumber(int inNum){
ObservableList<Part> searchBin = FXCollections.observableArrayList();
for(Part e: Inventory.partBin){
boolean typeCaseIn = (e.getClass() == Inhouse.class);
if(typeCaseIn == true){
Inhouse testIn = (Inhouse) e;
if(inNum == testIn.getMachineID())
searchBin.add(e);
}
if((inNum == e.getPartID()) || (inNum == e.getInstock()) || (inNum == e.getMax())
|| (inNum == e.getMin()) || ((double)inNum == e.getPrice())
|| (Integer.toString(inNum).contains(e.getName()))){
searchBin.add(e);
}
}
return searchBin;
}
public static ObservableList<Part> searchPartByText(String inString){
ObservableList<Part> searchBin = FXCollections.observableArrayList();
for(Part e: Inventory.partBin){
boolean typeCaseOut = (e.getClass() == Outsourced.class);
if(typeCaseOut == true){
Outsourced testOut = (Outsourced) e;
if(inString.equals(testOut.getCompanyName())){
searchBin.add(e);
}
}
if(inString.equals(e.getName())){
searchBin.add(e);
}
}
return searchBin;
}
public static ObservableList<Part> searchProdByNumber(int inNum){
ObservableList<Part> searchProd = FXCollections.observableArrayList();
for(Part e: Inventory.partBin){
boolean typeCaseIn = (e.getClass() == Inhouse.class);
if(typeCaseIn == true){
Inhouse testIn = (Inhouse) e;
if(inNum == testIn.getMachineID())
searchProd.add(e);
}
if((inNum == e.getPartID()) || (inNum == e.getInstock()) || (inNum == e.getMax())
|| (inNum == e.getMin()) || ((double)inNum == e.getPrice())
|| (Integer.toString(inNum).equals(e.getName()))){
searchProd.add(e);
}
}
return searchProd;
}
public static ObservableList<Part> searchProdByText(String inString){
ObservableList<Part> searchProd = FXCollections.observableArrayList();
for(Part e: Inventory.partBin){
boolean typeCaseOut = (e.getClass() == Outsourced.class);
if(typeCaseOut == true){
Outsourced testOut = (Outsourced) e;
if(inString.equals(testOut.getCompanyName())){
searchProd.add(e);
}
}
if(inString.equals(e.getName())){
searchProd.add(e);
}
}
return searchProd;
}
}
It doesn't work, because when you clear the search, the action on the button is still set to clear the search...
Consider a different strategy entirely. You can use a FilteredList as the list for the table. Then just toggle the predicate on the list:
Predicate<Part> noFilter = part -> true;
FilteredList<Part> filteredParts = new FilteredList<>(Inventory.partBin, noFilter);
partTable.setItems(filteredParts);
partSearchBtn.setOnAction(searchPartEvent -> {
if (filteredParts.getPredicate()==noFilter) {
String searchQuery = partSearchField.getText();
try {
int searchNumber = Integer.parseInt(searchQuery);
filteredParts.setPredicate(part -> Search.filterByNumber(part, searchNumber));
} catch (NumberFormatException exc) {
filteredParts.setPredicate(part -> Search.filterByText(part, searchQuery));
}
} else {
filteredParts.setPredicate(noFilter);
}
});
partSearchButton.textProperty().bind(Bindings
.when(filteredParts.predicateProperty().isEqualTo(noFilter))
.then("Search")
.otherwise("Clear"));
and
public class Search {
public static boolean filterByNumber(Part part, int number) {
if (part.getClass() == Inhouse.class) {
Inhouse testIn = (Inhouse) part ;
if (testIn.getMachineID() == number) {
return true ;
}
}
if((number == part.getPartID()) || (number == part.getInstock()) || (number == part.getMax())
|| ( number == part.getMin()) || ((double) number == part.getPrice())
|| (Integer.toString(number).contains(part.getName()))){
return true ;
}
return false ;
}
public static boolean filterByText(Part part, String text) {
//similarly...
}
}
Related
This question already has answers here:
What is the recommended way to make a numeric TextField in JavaFX?
(24 answers)
Restricting a TextField input to hexadecimal values in Java FX
(3 answers)
Closed 3 years ago.
I have a credit card page in my java fx program. I am trying to make it so that the inputs only allow numbers. At the moment it only gives an error if the fields are empty. But no error occurs if text is included?
I have tried changing it from String to integer, but that doesn't work.
public void thankyoupage(ActionEvent actionEvent) throws IOException {
String cardno = cardtf.getText();
String expdate1 = expirytf1.getText();
String expdate2 = expirytf2.getText();
String cvvnum = cvvtf.getText();
if (cardno.equals("") || expdate1.equals("") ||
expdate2.equals("") || cvvnum.equals("")) {
Alert alert = new Alert(Alert.AlertType.WARNING, "Enter Full Details", ButtonType.OK);
alert.showAndWait();
} else{
Window mainWindow = confirmbut.getScene().getWindow();
Parent newRoot = FXMLLoader.load(getClass().getResource("Thankyou.fxml"));
mainWindow.getScene().setRoot(newRoot);
}
}
Any links or changes would be nice.
You should attach a TextFormatter to your TextField. I have attached a sample on using Decimals - since you are using money, this might make the most sense.
On your text field you simply add the TextFormatter - this will prevent entry of anything other than what you allow.
//For Example
moneyTextField.setTextFormatter(new DecimalTextFormatter(0, 2));
--Below is the control code.
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.function.UnaryOperator;
import javafx.scene.control.TextFormatter;
import javafx.util.StringConverter;
public class DecimalTextFormatter extends TextFormatter<Number> {
private static DecimalFormat format = new DecimalFormat("#.0;-#.0");
public DecimalTextFormatter(int minDecimals, int maxDecimals) {
super(getStringConverter(minDecimals, maxDecimals), 0, getUnaryOperator(maxDecimals, true,-1));
}
public DecimalTextFormatter(int minDecimals, int maxDecimals, boolean allowsNegative) {
super(getStringConverter(minDecimals, maxDecimals), 0, getUnaryOperator(maxDecimals, allowsNegative,-1));
}
public DecimalTextFormatter(int minDecimals, int maxDecimals, boolean allowsNegative , int maxNoOfDigitsBeforeDecimal) {
super(getStringConverter(minDecimals, maxDecimals), 0, getUnaryOperator(maxDecimals, allowsNegative, maxNoOfDigitsBeforeDecimal));
}
private static StringConverter<Number> getStringConverter(int minDecimals, int maxDecimals) {
return new StringConverter<Number>() {
#Override
public String toString(Number object) {
if (object == null) {
return "";
}
String format = "0.";
for (int i = 0; i < maxDecimals; i++) {
if (i < minDecimals) {
format = format + "0";
} else {
format = format + "#";
}
}
format = format + ";-" + format;
DecimalFormat df = new DecimalFormat(format);
String formatted = df.format(object);
return formatted;
}
#Override
public Number fromString(String string) {
try {
if (string == null) {
return null;
}
return format.parse(string);
} catch (ParseException e) {
return null;
}
}
};
}
private static UnaryOperator<javafx.scene.control.TextFormatter.Change> getUnaryOperator(int maxDecimals,
boolean allowsNegative, int noOfDigitsBeforeDecimal) {
return new UnaryOperator<TextFormatter.Change>() {
#Override
public TextFormatter.Change apply(TextFormatter.Change change) {
if (!allowsNegative && change.getControlNewText().startsWith("-")) {
return null;
}
if (change.getControlNewText().isEmpty()) {
return change;
}
ParsePosition parsePosition = new ParsePosition(0);
Object object = format.parse(change.getControlNewText(), parsePosition);
if (change.getCaretPosition() == 1) {
if (change.getControlNewText().equals(".")) {
return change;
}
}
if (object == null || parsePosition.getIndex() < change.getControlNewText().length()) {
return null;
} else {
if(noOfDigitsBeforeDecimal != -1)
{
int signum = new BigDecimal(change.getControlNewText()).signum();
int precision = new BigDecimal(change.getControlNewText()).precision();
int scale = new BigDecimal(change.getControlNewText()).scale();
int val = signum == 0 ? 1 : precision - scale;
if (val > noOfDigitsBeforeDecimal) {
return null;
}
}
int decPos = change.getControlNewText().indexOf(".");
if (decPos > 0) {
int numberOfDecimals = change.getControlNewText().substring(decPos + 1).length();
if (numberOfDecimals > maxDecimals) {
return null;
}
}
return change;
}
}
};
}
}
You have to use regular expressions to validate fields. You can learn more about regular expression here https://regexr.com/
String cardno = cardtf.getText();
if (cardno.equals("") || expdate1.equals("") || expdate2.equals("") || cvvnum.equals("")) {
Alert alert = new Alert(Alert.AlertType.WARNING, "Enter Full Details", ButtonType.OK);
alert.showAndWait();
}else if (cardno.matches("/^[A-Za-z ]+$/")){
Alert alert = new Alert(Alert.AlertType.WARNING, "It Can not contain letters", ButtonType.OK);
alert.showAndWait();
}else{
//Else Part
}
Here is a piece of code that should help you doing the trick by checking at every input if the text contains only numbers an a maximum of one "," as the decimal separator.
There is already a post showing how to do this.
Post
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TextField;
public class NumberField extends TextField {
public NumberField () {
initSpellListener();
}
public final void initSpellListener() {
this.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
if (!newValue.matches("\\d*")) {
this.setText(newValue.replaceAll("[^\\d,]", ""));/*The comma here "[^\\d,]" can be changed with the dot*/
StringBuilder aus = new StringBuilder();
aus.append(this.getText());
boolean firstPointFound = false;
for (int i = 0; i < aus.length(); i++) {
if (aus.charAt(i) == ',') {/*Change the , with . if you want the . to be the decimal separator*/
if (!firstPointFound) {
firstPointFound = true;
} else {
aus.deleteCharAt(i);
}
}
}
newValue = aus.toString();
this.setText(newValue);
} else {
this.setText(newValue);
}
});
}}
[As soon as I find the post I will credit this code.]
if (!newValue.matches("\\d*"))
this part of the code checks with a regex expression if the new string value doesn't contain only numbers, and then with this code
this.setText(newValue.replaceAll("[^\\d,]", ""));
it replaces all the non-digit or comma chars.
Finally the for-loop checks if only exists one comma ad if other are found they are deleted.
To help you with regex writing here is a very useful site : Online regex
Then you can use this object as a normal TextField:
#FMXL
private NumberField nf;
I'm trying to make an autocomplete combobox in javafx and im almost done but every time i try to submit and clear selection so the user can choose another choice , all the items get hidden except the one he chose last time
// this the class that i used turn a normal combobox to an autocomplete one
public class AutoCompleteComboBoxListener<T> implements EventHandler<KeyEvent> {
private ComboBox<T> comboBox;
private ObservableList<T> data;
private boolean moveCaretToPos = false;
private int caretPos;
public AutoCompleteComboBoxListener(final ComboBox<T> comboBox) {
this.comboBox = comboBox;
data = comboBox.getItems();
this.comboBox.setEditable(true);
this.comboBox.setOnKeyReleased(AutoCompleteComboBoxListener.this);
this.showOnFocus();
}
#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;
}
if (event.getCode() == KeyCode.RIGHT || event.getCode() == KeyCode.LEFT
|| event.isControlDown() || event.getCode() == KeyCode.HOME
|| event.getCode() == KeyCode.END || event.getCode() == KeyCode.TAB) {
return;
}
System.out.println(caretPos);
comboBox.hide();
if(event.getCode() == KeyCode.BACK_SPACE) {
moveCaretToPos = true;
caretPos = comboBox.getEditor().getCaretPosition();
} else if(event.getCode() == KeyCode.DELETE) {
moveCaretToPos = true;
caretPos = comboBox.getEditor().getCaretPosition();
}
ObservableList<T> list = FXCollections.observableArrayList();
for (int i=0; i<data.size(); i++) {
if(data.get(i).toString().toLowerCase().startsWith(
AutoCompleteComboBoxListener.this.comboBox
.getEditor().getText().toLowerCase())) {
list.add(data.get(i));
}
}
String t = comboBox.getEditor().getText();
comboBox.setItems(list);
comboBox.getEditor().setText(t);
if(!moveCaretToPos) {
caretPos = -1;
}
moveCaret(t.length());
if(!list.isEmpty()) {
comboBox.show();
String editorText;
editorText=comboBox.getEditor().getText();
list.sort((a, b) -> Integer.compare(a.toString().length(), b.toString().length()));
comboBox.getSelectionModel().selectFirst();
comboBox.getEditor().setText(editorText);
moveCaret(comboBox.getSelectionModel().getSelectedItem().toString().length());
}
if (event.getCode()==KeyCode.ENTER){
comboBox.hide();
comboBox.getEditor().setText(comboBox.getSelectionModel().getSelectedItem().toString());
}
}
private void moveCaret(int textLength) {
if(caretPos == -1)
comboBox.getEditor().positionCaret(textLength);
else
comboBox.getEditor().positionCaret(caretPos);
moveCaretToPos = false;
}
public void showOnFocus(){
this.comboBox.focusedProperty().addListener((obs, oldVal, newVal) ->
this.comboBox.show());
}
}
// and this is what the submit button does the the comboboxes
button.setOnAction(e-> {
combo1.getSelectionModel().clearSelection();
combo1.getSelectionModel().clearSelection();
});
I have two nodes of wso2-am analytics server (2.6.0) which is Wso2 Stream processors. I see following error on passive node of cluster. The active node is fine and I don't see any error. Analytics result has no impact for users who is viewing data on API Publisher or Store. however there is an error in passive node.
please advise what is causing following issue..
2019-02-26 17:06:09,513] ERROR {org.wso2.carbon.stream.processor.core.ha.tcp.EventSyncServer} - Error occurred while processing eventByteBufferQueue null java.nio.BufferUnderflowException
Just meet the same issue, here is my problem and solution.
1) Using the WSO2 SP HA deployment.
2) When Event come in active node and according the source mapping of the streaming, some fields are NULL
3) Active Node would like sync this event to passive node
4) passive node pick up the event data from the 'eventByteBufferQueue' to meet the standby-take over mechanism
5) passive node cannot parse the data from active node and reports error exception.
the root cause is SP only support NULL String by default, when NULL with LONG, INTEGER.. the error occurred. but for me, Long fields have NULL is the normal case, you can change data type to string.
here is my solution:
org.wso2.carbon.stream.processor.core_2.0.478.jar
Add logic to support NULL
BinaryMessageConverterUtil.java for sending event data from active node
public final class BinaryMessageConverterUtil {
public static int getSize(Object data) {
if (data instanceof String) {
return 4 + ((String) data).length();
} else if (data instanceof Integer) {
return 4;
} else if (data instanceof Long) {
return 8;
} else if (data instanceof Float) {
return 4;
} else if (data instanceof Double) {
return 8;
} else if (data instanceof Boolean) {
return 1;
} else if (data == null) {
return 0;
}else {
//TODO
return 4;
}
}
public static EventDataMetaInfo getEventMetaInfo(Object data) {
int eventSize;
Attribute.Type attributeType;
if (data instanceof String) {
attributeType = Attribute.Type.STRING;
eventSize = 4 + ((String) data).length();
} else if (data instanceof Integer) {
attributeType = Attribute.Type.INT;
eventSize = 4;
} else if (data instanceof Long) {
attributeType = Attribute.Type.LONG;
eventSize = 8;
} else if (data instanceof Float) {
attributeType = Attribute.Type.FLOAT;
eventSize = 4;
} else if (data instanceof Double) {
attributeType = Attribute.Type.DOUBLE;
eventSize = 8;
} else if (data instanceof Boolean) {
attributeType = Attribute.Type.BOOL;
eventSize = 1;
} else if (data == null){
attributeType = Attribute.Type.OBJECT;
eventSize = 0; //'no content between the HA nodes for NULL fields'
} else {
//TODO
attributeType = Attribute.Type.OBJECT;
eventSize = 1;
}
return new EventDataMetaInfo(eventSize, attributeType);
}
public static void assignData(Object data, ByteBuffer eventDataBuffer) throws IOException {
if (data instanceof String) {
eventDataBuffer.putInt(((String) data).length());
eventDataBuffer.put((((String) data).getBytes(Charset.defaultCharset())));
} else if (data instanceof Integer) {
eventDataBuffer.putInt((Integer) data);
} else if (data instanceof Long) {
eventDataBuffer.putLong((Long) data);
} else if (data instanceof Float) {
eventDataBuffer.putFloat((Float) data);
} else if (data instanceof Double) {
eventDataBuffer.putDouble((Double) data);
} else if (data instanceof Boolean) {
eventDataBuffer.put((byte) (((Boolean) data) ? 1 : 0));
} else if (data == null){
//put nothing into he Buffer
} else {
eventDataBuffer.putInt(0);
}
}
public static String getString(ByteBuf byteBuf, int size) throws UnsupportedEncodingException {
byte[] bytes = new byte[size];
byteBuf.readBytes(bytes);
return new String(bytes, Charset.defaultCharset());
}
public static String getString(ByteBuffer byteBuf, int size) throws UnsupportedEncodingException {
byte[] bytes = new byte[size];
byteBuf.get(bytes);
return new String(bytes, Charset.defaultCharset());
}
}
SiddhiEventConverter.java for processing event data at passive node
static Object[] toObjectArray(ByteBuffer byteBuffer,
String[] attributeTypeOrder) throws UnsupportedEncodingException {
if (attributeTypeOrder != null) {
Object[] objects = new Object[attributeTypeOrder.length];
for (int i = 0; i < attributeTypeOrder.length; i++) {
switch (attributeTypeOrder[i]) {
case "INT":
objects[i] = byteBuffer.getInt();
break;
case "LONG":
objects[i] = byteBuffer.getLong();
break;
case "STRING":
int stringSize = byteBuffer.getInt();
if (stringSize == 0) {
objects[i] = null;
} else {
objects[i] = BinaryMessageConverterUtil.getString(byteBuffer, stringSize);
}
break;
case "DOUBLE":
objects[i] = byteBuffer.getDouble();
break;
case "FLOAT":
objects[i] = byteBuffer.getFloat();
break;
case "BOOL":
objects[i] = byteBuffer.get() == 1;
break;
case "OBJECT":
//for NULL fields
objects[i] = null;
break;
default:
// will not occur
}
}
return objects;
} else {
return null;
}
}
Base Article:
[https://community.oracle.com/thread/2552039?start=0&tstart=0][1]
I extend the solution from the oracle community with the event filters in the constructor for a better user ergonomics.
The JavaFX TimeTextField provides all functions needed for time handling.
Unfortunately it's missing in the JavaFX Standard in Java8, where a time handling field is a must in my point of view as in other technologies it is possible.
The thread in the oracle community is not as frequent as I expect it, please test it and try to improve it! We need it...
Features:
- only numeric keys are accepted.
- validation for a given time format
- (my improvement) when the last number of a block like hours or minutes was reached, the cursor jumps to the next block.
package test;
import java.util.regex.Pattern;
import javafx.beans.binding.Bindings;
import javafx.application.Application;
import javafx.beans.binding.IntegerBinding;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.property.ReadOnlyIntegerWrapper;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.IndexRange;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TimeTextFieldTest extends Application {
#Override
public void start(Stage primaryStage) {
VBox root = new VBox(5);
root.setPadding(new javafx.geometry.Insets(5));
Label hrLabel = new Label();
Label minLabel = new Label();
Label secLabel = new Label();
TimeTextField timeTextField = new TimeTextField();
hrLabel.textProperty().bind(Bindings.format("Hours: %d", timeTextField.hoursProperty()));
minLabel.textProperty().bind(Bindings.format("Minutes: %d", timeTextField.minutesProperty()));
secLabel.textProperty().bind(Bindings.format("Seconds: %d", timeTextField.secondsProperty()));
root.getChildren().addAll(timeTextField, hrLabel, minLabel, secLabel);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public static class TimeTextField extends TextField {
enum Unit {
HOURS, MINUTES, SECONDS
};
private final Pattern timePattern;
private final ReadOnlyIntegerWrapper hours;
private final ReadOnlyIntegerWrapper minutes;
private final ReadOnlyIntegerWrapper seconds;
public TimeTextField() {
this("00:00:00");
this.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent inputevent) {
int c = TimeTextField.this.getCaretPosition();
if (c <= 7) {
if (!"1234567890:".contains(inputevent.getCharacter().toLowerCase())) {
inputevent.consume();
}
} else {
inputevent.consume();
}
}
});
this.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent inputevent) {
boolean withMinutes = false;
if (TimeTextField.this.getText() != null && TimeTextField.this.getText().length() >= 5
&& TimeTextField.this.getText().indexOf(":") == 2) {
withMinutes = true;
}
boolean withSeconds = false;
if (TimeTextField.this.getText() != null && TimeTextField.this.getText().length() == 8
&& TimeTextField.this.getText().lastIndexOf(":") == 5) {
withSeconds = true;
}
int c = TimeTextField.this.getCaretPosition();
if (((c == 2 && withMinutes) || (c == 5 && withSeconds))
&& (inputevent.getCode() != KeyCode.LEFT && inputevent.getCode() != KeyCode.BACK_SPACE)) {
TimeTextField.this.forward();
inputevent.consume();
}
}
});
}
public TimeTextField(String time) {
super(time);
// timePattern = Pattern.compile("\\d\\d:\\d\\d:\\d\\d");
timePattern = Pattern.compile("([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]");
if (!validate(time)) {
throw new IllegalArgumentException("Invalid time: " + time);
}
hours = new ReadOnlyIntegerWrapper(this, "hours");
minutes = new ReadOnlyIntegerWrapper(this, "minutes");
seconds = new ReadOnlyIntegerWrapper(this, "seconds");
hours.bind(new TimeTextField.TimeUnitBinding(Unit.HOURS));
minutes.bind(new TimeTextField.TimeUnitBinding(Unit.MINUTES));
seconds.bind(new TimeTextField.TimeUnitBinding(Unit.SECONDS));
}
public ReadOnlyIntegerProperty hoursProperty() {
return hours.getReadOnlyProperty();
}
public int getHours() {
return hours.get();
}
public ReadOnlyIntegerProperty minutesProperty() {
return minutes.getReadOnlyProperty();
}
public int getMinutes() {
return minutes.get();
}
public ReadOnlyIntegerProperty secondsProperty() {
return seconds.getReadOnlyProperty();
}
public int getSeconds() {
return seconds.get();
}
#Override
public void appendText(String text) {
// Ignore this. Our text is always 8 characters long, we cannot
// append anything
}
#Override
public boolean deleteNextChar() {
boolean success = false;
// If there's a selection, delete it:
final IndexRange selection = getSelection();
if (selection.getLength() > 0) {
int selectionEnd = selection.getEnd();
this.deleteText(selection);
this.positionCaret(selectionEnd);
success = true;
} else {
// If the caret preceeds a digit, replace that digit with a zero
// and move the caret forward. Else just move the caret forward.
int caret = this.getCaretPosition();
if (caret % 3 != 2) { // not preceeding a colon
String currentText = this.getText();
setText(currentText.substring(0, caret) + "0" + currentText.substring(caret + 1));
success = true;
}
this.positionCaret(Math.min(caret + 1, this.getText().length()));
}
return success;
}
#Override
public boolean deletePreviousChar() {
boolean success = false;
// If there's a selection, delete it:
final IndexRange selection = getSelection();
if (selection.getLength() > 0) {
int selectionStart = selection.getStart();
this.deleteText(selection);
this.positionCaret(selectionStart);
success = true;
} else {
// If the caret is after a digit, replace that digit with a zero
// and move the caret backward. Else just move the caret back.
int caret = this.getCaretPosition();
if (caret % 3 != 0) { // not following a colon
String currentText = this.getText();
setText(currentText.substring(0, caret - 1) + "0" + currentText.substring(caret));
success = true;
}
this.positionCaret(Math.max(caret - 1, 0));
}
return success;
}
#Override
public void deleteText(IndexRange range) {
this.deleteText(range.getStart(), range.getEnd());
}
#Override
public void deleteText(int begin, int end) {
// Replace all digits in the given range with zero:
StringBuilder builder = new StringBuilder(this.getText());
for (int c = begin; c < end; c++) {
if (c % 3 != 2) { // Not at a colon:
builder.replace(c, c + 1, "0");
}
}
this.setText(builder.toString());
}
#Override
public void insertText(int index, String text) {
// Handle an insert by replacing the range from index to
// index+text.length() with text, if that results in a valid string:
StringBuilder builder = new StringBuilder(this.getText());
builder.replace(index, index + text.length(), text);
final String testText = builder.toString();
if (validate(testText)) {
this.setText(testText);
}
this.positionCaret(index + text.length());
}
#Override
public void replaceSelection(String replacement) {
final IndexRange selection = this.getSelection();
if (selection.getLength() == 0) {
this.insertText(selection.getStart(), replacement);
} else {
this.replaceText(selection.getStart(), selection.getEnd(), replacement);
}
}
#Override
public void replaceText(IndexRange range, String text) {
this.replaceText(range.getStart(), range.getEnd(), text);
}
#Override
public void replaceText(int begin, int end, String text) {
if (begin == end) {
this.insertText(begin, text);
} else {
// only handle this if text.length() is equal to the number of
// characters being replaced, and if the replacement results in
// a valid string:
if (text.length() == end - begin) {
StringBuilder builder = new StringBuilder(this.getText());
builder.replace(begin, end, text);
String testText = builder.toString();
if (validate(testText)) {
this.setText(testText);
}
this.positionCaret(end);
}
}
}
private boolean validate(String time) {
if (!timePattern.matcher(time).matches()) {
return false;
}
String[] tokens = time.split(":");
assert tokens.length == 3;
try {
int hours = Integer.parseInt(tokens[0]);
int mins = Integer.parseInt(tokens[1]);
int secs = Integer.parseInt(tokens[2]);
if (hours < 0 || hours > 23) {
return false;
}
if (mins < 0 || mins > 59) {
return false;
}
if (secs < 0 || secs > 59) {
return false;
}
return true;
} catch (NumberFormatException nfe) {
// regex matching should assure we never reach this catch block
assert false;
return false;
}
}
private final class TimeUnitBinding extends IntegerBinding {
final Unit unit;
TimeUnitBinding(Unit unit) {
this.bind(textProperty());
this.unit = unit;
}
#Override
protected int computeValue() {
// Crazy enum magic
String token = getText().split(":")[unit.ordinal()];
return Integer.parseInt(token);
}
}
}
}
Using Java, is it possible to write a recursive method to find an element in a binary search tree? I say no because of the nature of recursive re-tracing back unless I implemented incorrectly? I have been searching the internet and all i can find is an iterative version. Here is my method:
public boolean findValueRecursively(BSTNode node, int value){
boolean isFound = false;
BSTNode currentNode = node;
if (value == currentNode.getData()){
isFound = true;
return isFound;
} else if (value < currentNode.getData()){
findValueRecursively(currentNode.getLeftNode(), value);
} else{
findValueRecursively(currentNode.getRightNode(), value);
}
return isFound;
}
// Node data structure
public class BSTNode
{
private BSTNode leftNode;
private BSTNode rightNode;
private int data;
public BSTNode(int value, BSTNode left, BSTNode right){
this.leftNode = left;
this.rightNode = right;
this.data = value;
}
}
public static void main(String[] args){
BST bst = new BST();
// initialize the root node
BSTNode bstNode = new BSTNode(4, null, null);
bst.insert(bstNode, 2);
bst.insert(bstNode, 5);
bst.insert(bstNode, 6);
bst.insert(bstNode, 1);
bst.insert(bstNode, 3);
bst.insert(bstNode, 7);
if (bst.findValueRecursively(bstNode, 7)){
System.out.println("element is found! ");
} else{
System.out.println("element is not found!");
}
}
I get the print as "element is not found".
Any help/tips or suggestions, more than welcome.
Thanks in advance!
A recursive version:
public boolean findValueRecursively(Node node, int value){
if(node == null) return false;
return
node.data == value ||
findValueRecursively(leftNode, value) ||
findValueRecursively(rightNode, value);
}
A recursive version that returns a reference to the node found:
public BinaryNode find(BinaryNode node, int value) {
// Finds the node that contains the value and returns a reference to the node.
// Returns null if value does not exist in the tree.
if (node == null) return null;
if (node.data == value) {
return node;
} else {
BinaryNode left = find(node.leftChild, value);
BinaryNode right = find(node.rightChild, value);
if (left != null) {
return left;
}else {
return right;
}
}
}
I believe your isFound = false; is what is always getting returned.
It should be like this:
isFound= findValueRecursively(currentNode.getLeftNode(), value);
public TreeNode<E> binarySearchTree(TreeNode<E> node, E data){
if(node != null) {
int side = node.getData().compareTo(data);
if(side == 0) return node;
else if(side < 0) return binarySearchTree(node.getRightChild(), data);
else if(side > 0 ) return binarySearchTree(node.getLeftChild(), data);
}
return null;
}
That will return a reference to the node, which is a little more useful IRL. You can change it to return a boolean though.