Request fix functionality - javafx

MY TASK : Write a JavaFX GUI application that allows the user to pick a set of pizza toppings using a set of check boxes. Assuming each topping cost 50 cents, and a plain pizza costs $10, display the cost of the pizza. Note that, once a topping is checked or unchecked, the cost of pizza should update automatically.
FIX REQUEST : my pizza cost calculator fails to add cost for topping properly
For example, Extracheese checked and unchecked resulted in below base price $10 (ie; $7)
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.scene.transform.Scale;
import javafx.stage.Stage;
import javafx.scene.text.Text;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
class PizzaCost extends VBox {
private CheckBox ExtraCheeseCheckBox;
private CheckBox GreenPepperCheckBox;
private Label TotalPizzaCost;
public double pizzaCost = 10.0;
public PizzaCost(){
Font font = new Font(13);
ExtraCheeseCheckBox = new CheckBox("Extra Cheese");
ExtraCheeseCheckBox.setOnAction(this::processCheckBoxAction);
GreenPepperCheckBox = new CheckBox("GreenPepper");
GreenPepperCheckBox.setOnAction(this::processCheckBoxAction);
TotalPizzaCost = new Label(pizzaCost +"");
TotalPizzaCost.setFont(font);
HBox options = new HBox(ExtraCheeseCheckBox,GreenPepperCheckBox);
getChildren().addAll(options,TotalPizzaCost);
}
public void processCheckBoxAction (ActionEvent event){
if (ExtraCheeseCheckBox.isSelected()){
pizzaCost += 0.5;
}
else {
pizzaCost -= 0.5;
}
TotalPizzaCost.setText(pizzaCost+"");
}
}

The following code works for me. The pizza cost never goes below $10.
import java.text.NumberFormat;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class PizzaCost extends Application {
private static final double TOPPING_COST = 0.5d;
private static final NumberFormat COST_FORMAT = NumberFormat.getCurrencyInstance();
private static final String PIZZA_COST = "Pizza Cost: ";
private double pizzaCost = 10.0d;
private Label totalPizzaCostLabel;
#Override
public void start(Stage primaryStage) throws Exception {
CheckBox extraCheesCheckBox = getCheckBox("Extra Cheese");
CheckBox greenPepperCheckBox = getCheckBox("Green Pepper");
HBox hBox = new HBox(20.0d, extraCheesCheckBox, greenPepperCheckBox);
totalPizzaCostLabel = new Label(PIZZA_COST + COST_FORMAT.format(pizzaCost));
totalPizzaCostLabel.setFont(new Font(13.0d));
VBox root = new VBox(20.0d, hBox, totalPizzaCostLabel);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(40.0d));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setTitle("Pizza Cost");
primaryStage.show();
}
private CheckBox getCheckBox(String text) {
CheckBox cb = new CheckBox(text);
cb.setOnAction(this::processCheckBoxAction);
return cb;
}
private void processCheckBoxAction(ActionEvent event) {
CheckBox cb = (CheckBox) event.getSource();
if (cb.isSelected()) {
pizzaCost += TOPPING_COST;
}
else {
pizzaCost -= TOPPING_COST;
}
totalPizzaCostLabel.setText(PIZZA_COST + COST_FORMAT.format(pizzaCost));
}
public static void main(String[] args) {
launch(args);
}
}

Related

KeyValue class gives error in javafx? how i fix it

KeyValue class gives error in javafx? I also implements all the abstract method but still face issue?
package at_collection;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.util.Duration;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
public class Scene1Controller implements Initializable {
#FXML
private StackPane parent;
#FXML
private AnchorPane child1;
#FXML
private Button btn1;
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
#FXML
private void load1(ActionEvent event) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Scene2.fxml"));
Scene scene = btn1.getScene();
root.translateYProperty().set(scene.getHeight());
parent.getChildren().add(root);
Timeline timeline = new Timeline();
KeyValue kv = new KeyValue(root.translateYProperty(), 0, Interpolator.EASE_IN); // Here is the problem
KeyFrame kf = new KeyFrame(Duration.seconds(1), kv);
timeline.getKeyFrames().add(kf);
timeline.setOnFinished(t -> {
parent.getChildren().remove(child1);
});
timeline.play();
}
}
The stack trace is not print. Because of the compile-time error. i'm actually implements this "https://www.youtube.com/watch?v=cqskg3DYH8g"
Here is the output of this code
This is because of the Wrong Import "import javax.xml.crypto.dsig.keyinfo.KeyValue"
Import this one "import javafx.animation.KeyValue;"

Java fx event handler

Why my code is not running? How am I going to display an image on the interface when clicked "add image"?
import javafx.stage.Stage;
import javafx.scene.*;
import javafx.application.Application;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
public class GUIProject extends Application{
/**
* #param args the command line arguments
*/
public void start (Stage stage) throws Exception
{
Pane bPane = new Pane();
Button btOK = new Button("OK");
OKAction OKact = new OKAction();
btOK.setOnAction(OKact);
Button addImage = new Button("Add Image");
isAdd addimage = new isAdd();
addImage.setOnAction(addimage);
//bPane.getChildren().add(btOK);
bPane.getChildren().add(addImage);
Scene scene = new Scene(bPane);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
// TODO code application logic here
Application.launch(args);
}
}
import java.io.FileInputStream;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
public class Pane extends StackPane {
public void addImage() throws Exception
{
Image logo = new Image(new FileInputStream("logo.jpg"));
ImageView logoView = new ImageView(logo);
this.getChildren().add(logoView);
}
}
import java.io.FileInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
class isAdd implements EventHandler<ActionEvent>{
public void handle(ActionEvent event)
{
try {
Pane.displayImage();
}
catch (Exception ex) {
System.out.println("Error");;
}
}
}
It keep showing static method cannot with non-static method, how can I solve that?
Is there any website can learn javafx event handler?

Error of UDP server in javaFx

I made the source code of UDP server. the task of code shows figure when it received data via UDP communication. I used thread to receive data from other PC via UDP communication.
I use udp test tool from the other PC to check the code.
But, when startup my jar of source code in first, then the udp test tool can't bind the port .
what is the problem of my source code?
(In case that I set different values as the bind's port and send port in other PC's udp test tool,then my source code shows successfully the figure.)
package javafxapplication15;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBuilder;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.FlowPaneBuilder;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBoxBuilder;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.stage.Stage;
import javafx.stage.StageBuilder;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.LabelBuilder;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFieldBuilder;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.TextAlignment;
import javafx.util.Duration;
import sun.misc.HexDumpEncoder;
public class JavaFXApplication15 extends Application {
public DatagramSocket receivesocket;
public DatagramPacket receivepacket;
public DatagramSocket sendsocket;
public DatagramPacket sendpacket;
public InetSocketAddress remoteAdress;
public Label label;
public Label label_IP;
public Label label_IP_in;
public TextField tx_IP;
public Label label_SENDPORT;
public Label label_SENDPORT_in;
public Label label_RECEIVEPORT;
public Label label_RECEIVEPORT_in;
public Label label_status;
public TextField tx_SENDPORT;
public TextField tx_RECEIVEPORT;
public Button bt_co;
public Button bt1;
public Button bt2;
public Button bt_play ;
public ObservableList<String> play_num=null;
public ComboBox<String> comboBox;
private String message;
private XYChart.Series series;
private Timeline timer;
private ProgressIndicator indicator;
private static String s = null;
private static String IP = "192.168.101.30";
private static Integer RECEIVEPORT = 8084;
public double time_counter=0.0;
public double torque_receive_value=0.0;
public byte[] torque_Hex;
private String text;
private byte[] buf;
#Override
public void start(Stage stage) throws Exception{
/* timer */
timer = new Timeline(new KeyFrame(Duration.millis(1000), new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event) {
time_counter = time_counter+1;
}
}));
timer.setCycleCount(Timeline.INDEFINITE);
timer.play();
/* Figure*/
stage.setTitle("Line Chart Sample");
//defining the axes
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Time [s]");
yAxis.setLabel("Force [N]");
//creating the chart
final LineChart<Number,Number> lineChart =
new LineChart<Number,Number>(xAxis,yAxis);
lineChart.setTitle("Receive Data");
//defining a series
series = new XYChart.Series();
series.setName("Torque");
series.getData().add(new XYChart.Data(0.0,0.0));
lineChart.getData().add(series);
VBox root = VBoxBuilder.create().spacing(25).children(lineChart).build();
Scene scene = new Scene(root);
recieve_UDP();
stage = StageBuilder.create().width(640).height(640).scene(scene).title("").build();
stage.show();
}
private void recieve_UDP() throws SocketException, IOException {
ScheduledService<Boolean> ss = new ScheduledService<Boolean>()
{
#Override
protected Task<Boolean> createTask()
{
Task<Boolean> task = new Task<Boolean>()
{
#Override
protected Boolean call() throws Exception
{
receivesocket = null;
byte[] receiveBuffer = new byte[1024];
receivepacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
receivesocket = new DatagramSocket(RECEIVEPORT);
receivesocket.receive(receivepacket);
message = new String(receivepacket.getData(),0, receivepacket.getLength());
torque_Hex = receivepacket.getData();
System.out.println(message);
if(message != "Status:Wait"){
Platform.runLater( () ->label_status.setText("Status:Done"));
/* show Figure */
Platform.runLater( () -> series.getData().add(new XYChart.Data(time_counter,Double.parseDouble( message))));
}
receivesocket.close();
return true;
};
};
return task;
}
};
ss.start();
}
public static void main(String[] args) {
launch(args);
}
}

ControlsFx Decoration on a Label

I would like to apply ControlsFx decorations in a TableCell and as such would like to apply them to a Label.
This following does NOT apply the decoration to the Label. Should it?
import org.controlsfx.control.decoration.Decorator;
import org.controlsfx.control.decoration.GraphicDecoration;
import org.controlsfx.validation.decoration.GraphicValidationDecoration;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
public class LabelDecoration extends Application {
private static final Image REQUIRED_IMAGE = new Image(GraphicValidationDecoration.class.getResource("/impl/org/controlsfx/control/validation/required-indicator.png").toExternalForm()); //$NON-NLS-1$
#Override
public void start(Stage primaryStage) throws Exception {
Label label = new Label("Test");
Node requiredDecoration = new ImageView( REQUIRED_IMAGE );
Decorator.addDecoration( label, new GraphicDecoration( requiredDecoration, Pos.TOP_LEFT ));
primaryStage.setScene( new Scene( label, 100, 100 ));
primaryStage.show();
}
public static void main(String[] args) {
launch( args );
}
}
The Decorator tries to install a DecorationPane into the scene, which does not exist yet in your case.
Wrap the line Decorator.addDecoration(...) in a Platform.runLater(...) and it will work.

Create a webview from a button in JavaFX

I have the following simple code where I have an horizontal block where there are two buttons, the remain part is empty. Now, I would like to view a Webview inside the free part after the user press the "current" button. I already did something similar but I wasn't able to manage the layout because it was a Jframe + JavaFX. I thought to re-build totally in JavaFx , for this reason I want to put the webview in a jfxPanel(I think it's the best solution, any other suggest is really appreciate). I should see the webview when I press the button , in this case current, for this reason I create an handle. So, How can I do it?
Thanks in advance
import java.util.ArrayList;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Hyperlink;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Launcher extends Application {
public static void main(String[] args) {
launch(Launcher.class, args);
}
Button buttonCurrent;
static HBox web;
static MyBrowser browser_lau;
public void start(Stage stage) {
BorderPane border = new BorderPane();
HBox hbox = addHBox();
border.setTop(hbox);
Scene scene = new Scene(border);
stage.setScene(scene);
stage.setTitle("Layout Sample");
stage.show();
buttonCurrent.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
final JFXPanel jfxPanel = new JFXPanel();
//border.setStyle("-fx-background-color: #ff0000;");
}
});
}
public HBox addHBox() {
HBox hbox = new HBox();
hbox.setPadding(new Insets(15, 12, 15, 12));
hbox.setSpacing(10); // Gap between nodes
hbox.setStyle("-fx-background-color: #336699;");
buttonCurrent = new Button("Current");
buttonCurrent.setPrefSize(100, 20);
Button buttonProjected = new Button("Projected");
buttonProjected.setPrefSize(100, 20);
hbox.getChildren().addAll(buttonCurrent, buttonProjected);
return hbox;
}
}
}
Here is some sample code to get you started, it creates a couple of WebViews and toggles between them depending upon a radio button selection.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class CountThePeople extends Application {
private static final String CURRENT_URL =
"http://www.census.gov/popclock/";
private static final String PROJECTED_URL =
"http://www.sciencedaily.com/releases/2015/08/150810110634.htm";
#Override
public void start(final Stage stage) throws Exception {
WebView current = new WebView();
current.getEngine().load(CURRENT_URL);
WebView projected = new WebView();
projected.getEngine().load(PROJECTED_URL);
StackPane viewHolder = new StackPane();
ToggleGroup choice = new ToggleGroup();
RadioButton currentRadio = new RadioButton("Current");
currentRadio.setToggleGroup(choice);
RadioButton projectedRadio = new RadioButton("Projected");
projectedRadio.setToggleGroup(choice);
choice.selectedToggleProperty().addListener((observable, oldValue, newValue) -> {
if (projectedRadio == newValue) {
viewHolder.getChildren().setAll(projected);
} else {
viewHolder.getChildren().setAll(current);
}
});
choice.selectToggle(currentRadio);
VBox layout = new VBox(10, currentRadio, projectedRadio, viewHolder);
layout.setPadding(new Insets(10));
stage.setTitle("World Population");
stage.setScene(new Scene(layout));
stage.show();
}
public static void main(String[] args) throws Exception {
launch(args);
}
}

Resources