import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.paint.Color;
import javafx.scene.control.Toggle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
public class ConverterApp extends Application {
private void resetUI(TextField tf1, TextField tf2, Text t){
tf1.setText("");
tf2.setText("");
t.setText("");
tf1.setEditable(true);
tf2.setEditable(false);
}
@Override
public void start(Stage stage) {
TextField tfFeet = new TextField();
TextField tfMeter = new TextField();
Button btnConvert = new Button("Convert");
Button btnClear = new Button("Clear");
ToggleGroup group = new ToggleGroup();
RadioButton rbFeet = new RadioButton("Feet to Meters");
RadioButton rbMeter = new RadioButton("Meters to Feet");
rbFeet.setToggleGroup(group);
rbMeter.setToggleGroup(group);
btnClear.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
rbFeet.setSelected(!true);
rbFeet.setSelected(true);
}
});
Text lbError = new Text();
btnConvert.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
lbError.setText("");
final double FACTOR = 3.2808399;
try{
if(rbFeet == group.getSelectedToggle()){
tfMeter.setText(String.valueOf(new Double(tfFeet.getText())/FACTOR));
} else {
tfFeet.setText(String.valueOf(new Double(tfMeter.getText())*FACTOR));
}
}catch(NumberFormatException ex){
lbError.setText("Error: "+ex.getMessage());
}
}
});
group.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> ov, Toggle prev, Toggle cur) {
if(rbFeet == group.getSelectedToggle()){
resetUI(tfFeet,tfMeter,lbError);
} else if(rbMeter == group.getSelectedToggle()){
resetUI(tfMeter,tfFeet,lbError);
}
}
});
rbFeet.setSelected(true);
lbError.setFill(Color.RED);
GridPane gridPane = new GridPane();
gridPane.setPadding(new Insets(5, 5, 5, 5));
gridPane.setVgap(5);
gridPane.setHgap(5);
gridPane.setAlignment(Pos.CENTER);
gridPane.addRow(0, rbFeet, rbMeter);
gridPane.addRow(1, new Text("Feet"), tfFeet);
gridPane.addRow(2, new Text("Meter"), tfMeter);
gridPane.addRow(3, btnConvert, btnClear);
gridPane.setColumnSpan(lbError,2);
gridPane.addRow(4, lbError);
stage.setTitle("Converter Application");
stage.setScene(new Scene(gridPane,300,160));
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Download
Comments
Post a Comment