I am new to JavaFX.
Please have a look at attached image where i want to restrict drawing on button.
And please also suggest me for printing to printer.
(In swing, it is possible with PrintJob and Toolkit class)
Below is my code :
public class PrintScribble extends Application {
private short last_x = 0, last_y = 0; // last click posistion
private Vector lines = new Vector(256, 256); // store the scribble
private Properties printprefs = new Properties(); // store user preferences
private Path path;
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("PrintScribble");
Group root = new Group();
Scene scene = new Scene(root, 400, 400);
BorderPane bp = new BorderPane();
bp.setPadding(new Insets(10, 10, 10, 10));
bp.setMinWidth(scene.getWidth());
Button b = new Button("Print");
bp.setRight(b);
root.getChildren().add(bp);
b.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Printer call");
//print();
}
});
path = new Path();
scene.setOnMouseClicked(mouseHandler);
scene.setOnMouseDragged(mouseHandler);
scene.setOnMouseEntered(mouseHandler);
scene.setOnMouseExited(mouseHandler);
scene.setOnMouseMoved(mouseHandler);
scene.setOnMousePressed(mouseHandler);
scene.setOnMouseReleased(mouseHandler);
root.getChildren().add(path);
primaryStage.setScene(scene);
primaryStage.show();
}
EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getEventType() == MouseEvent.MOUSE_PRESSED) {
path.getElements()
.add(new MoveTo(mouseEvent.getX(), mouseEvent.getY()));
} else if (mouseEvent.getEventType() == MouseEvent.MOUSE_DRAGGED) {
path.getElements()
.add(new LineTo(mouseEvent.getX(), mouseEvent.getY()));
}
}
};
/**
* The main method. Create a PrintScribble() object and away we go!
*/
public static void main(String[] args) {
launch(args);
}
}
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getEventType() == MouseEvent.MOUSE_PRESSED) {
path.getElements()
.add(new MoveTo(mouseEvent.getX(), mouseEvent.getY()));
} else if (mouseEvent.getEventType() == MouseEvent.MOUSE_DRAGGED) {
path.getElements()
.add(new LineTo(mouseEvent.getX(), mouseEvent.getY()));
}
// Here is an answer
path.toBack();
}
Related
I am trying to code a program that takes in user input in one scene to set the background color in the second scene. Everything works except the background does not change the color, it stays white. Does anyone know why this could be happening?
public class Project extends Application {
Scene scene1, scene2;
final int WIDTH = 600;
final int HEIGHT = 600;
Label labelLightOrDark;
TextField tfLightOrDark;
private GridPane createTextFieldPane() {
GridPane gPane = new GridPane();
labelLightOrDark = new Label("Is it light or dark? ");
tfLightOrDark = new TextField();
gPane.add(labelLightOrDark, 0, 2);
gPane.add(tfLightOrDark, 1, 2);
return gPane;
}
#Override
public void start(Stage primaryStage) {
//first scene
Button btGenerate = new Button("Generate My Background!");
GridPane gPane = createTextFieldPane();
gPane.add(btGenerate, 0, 6);
Scene scene1 = new Scene(gPane, 600, 600);
//second scene
Button btReturn = new Button("Try Again!");
btReturn.setOnAction((ActionEvent event2) -> {
primaryStage.setScene(scene1);});
Pane root = new Pane();
String bColor = tfLightOrDark.getText();
if (bColor.equalsIgnoreCase("light")) {
root.setStyle("-fx-background-color: lightblue;");}
else if (bColor.equalsIgnoreCase("dark")) {
root.setStyle("-fx-background-color: darkblue;");}
root.getChildren().add(btReturn);
Scene scene2 = new Scene(root, 600, 600);
btGenerate.setOnAction((ActionEvent event) -> {
primaryStage.setScene(scene2);
});
primaryStage.setTitle("Create Your Own Background!");
primaryStage.setScene(scene1);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
I believe the problem has to do with my if, else if statements because when I comment out these lines it does set the background of the second scene to light blue.
//if (bColor.equalsIgnoreCase("light")) {
root.setStyle("-fx-background-color: lightblue;");}
//else if (bColor.equalsIgnoreCase("dark")) {
//root.setStyle("-fx-background-color: darkblue;");}
Everything is OK, but keep a ref to whats clicked. Here is the code.
Scene scene1, scene2;
final int WIDTH = 600;
final int HEIGHT = 600;
Label labelLightOrDark;
TextField tfLightOrDark;
private GridPane createTextFieldPane() {
GridPane gPane = new GridPane();
labelLightOrDark = new Label("Is it light or dark? ");
tfLightOrDark = new TextField();
gPane.add(labelLightOrDark, 0, 2);
gPane.add(tfLightOrDark, 1, 2);
return gPane;
}
#Override
public void start(Stage primaryStage) {
//first scene
Button btGenerate = new Button("Generate My Background!");
GridPane gPane = createTextFieldPane();
gPane.add(btGenerate, 0, 6);
Scene scene1 = new Scene(gPane, 600, 600);
//second scene
Button btReturn = new Button("Try Again!");
btReturn.setOnAction((ActionEvent event2) -> {
primaryStage.setScene(scene1);
});
Pane root = new Pane();
root.getChildren().add(btReturn);
Scene scene2 = new Scene(root, 600, 600);
btGenerate.setOnAction((ActionEvent event) -> {
primaryStage.setScene(scene2);
if (tfLightOrDark.getText().contains("light")) {
root.setStyle("-fx-background-color: lightblue;");
}
else if (tfLightOrDark.getText().contains("dark")) {
root.setStyle("-fx-background-color: darkblue;");
}
});
primaryStage.setTitle("Create Your Own Background!");
primaryStage.setScene(scene1);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The problem with the code is you are checking for the value in the text field before the scenegraph is rendered. You need to move the if-else logic to button onAction.
btGenerate.setOnAction((ActionEvent event) -> {
String bColor = tfLightOrDark.getText();
if (bColor.equalsIgnoreCase("light")) {
root.setStyle("-fx-background-color: lightblue;");
} else if (bColor.equalsIgnoreCase("dark")) {
root.setStyle("-fx-background-color: darkblue;");
}
primaryStage.setScene(scene2);
});
I want to add an image to an array. When I use Node it works, but when I use the same way to add images it does not appear when I run it. Here is my code:
public class PlatForm extends Application {
List<ImageView> platFormList = new ArrayList<>();
private Pane layout;
private Scene scene;
private AnimationTimer platFormTimer;
#Override
public void start(Stage primaryStage) throws Exception {
layout = new Pane();
scene = new Scene(layout,800,500);
primaryStage.setScene(scene);
primaryStage.show();
platFormTimer = new AnimationTimer() {
#Override
public void handle(long now) {
uploadPlatForm();
}
};
platFormTimer.start();
}
public void uploadPlatForm(){
for(ImageView platform : platFormList)
platform.setTranslateX(platform.getTranslateX() + Math.random() * 10);
if (Math.random() < 0.075) {
platFormList.add(newPlatForm());
}
}
private ImageView newPlatForm(){
ImageView platFormImg =
new ImageView(
new Image(getClass().getResourceAsStream("/image/platform.png")
)
);
layout.getChildren().add(platFormImg);
platFormImg.setTranslateY((int)(Math.random() * 14) * 40);
return platFormImg;
}
}
I have a blank javafx.stage.Stage with no icons minimize, maximize, and close stage.initStyle(StageStyle.UNDECORATED);. I want to create them myself, because on the line with them will make more Buttons. Because I use an empty style for the Stage, I need to set a resizable borders for my window. There are standard ways to do this? Because to create them as a BorderPane and customize the dragging of the mouse is cumbersome.
altered from a project of mine
This is how it looks
when maximised
package Project
Main.class
public class Main extends Application {
double dragX,dragY;
#Override
public void start(Stage primaryStage) {
try {
primaryStage.initStyle(StageStyle.TRANSPARENT);
HBox hbox = new HBox(10.0);
hbox.setPrefHeight(70);
hbox.setFillHeight(true);
BackgroundFill bf = new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1), null);
hbox.setBackground(new Background(bf));
AnchorPane ap = new AnchorPane();
ResponsiveButton min = new ResponsiveButton("Minimise");
min.noDefaultFill = true;
min.setBorder(Border.EMPTY);
min.setBackground(new Background(new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1), null)));
//min.setPrefSize(32.0,32.0);
min.setAlignment(Pos.CENTER);
min.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
primaryStage.setIconified(true);
}
});
ResponsiveButton max = new ResponsiveButton("Maximise");
max.setBorder(Border.EMPTY);
max.setBackground(new Background(new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1), null)));
//max.setPrefSize(32.0,32.0);
max.noDefaultFill = true;
max.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
if(primaryStage.isMaximized()){
primaryStage.setMaximized(false);
}else{
primaryStage.setMaximized(true);
}
}
});
ResponsiveButton logout = new ResponsiveButton("Close me");
logout.noDefaultFill = true;
logout.setBorder(Border.EMPTY);
logout.setBackground(new Background(new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1), null)));
//logout.setPrefSize(32.0,32.0);
logout.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
primaryStage.close();
}
});
Label label = new Label();
label.setText("Custom Stage");
label.setTextFill(Color.WHITESMOKE);
//label.setAlignment(Pos.CENTER);
label.setPadding(new Insets(0.0,0.0,0.0,18.0));
label.setFont(Font.font("Tahoma", FontWeight.BOLD, 25));
HBox.setHgrow(label, Priority.ALWAYS);
hbox.setAlignment(Pos.CENTER);
hbox.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
if(!primaryStage.isMaximized()){
dragX = primaryStage.getX() - mouseEvent.getScreenX();
dragY = primaryStage.getY() - mouseEvent.getScreenY();
hbox.setCursor(Cursor.MOVE);
}
}
});
hbox.setOnMouseReleased(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
if(!primaryStage.isMaximized()){
hbox.setCursor(Cursor.HAND);
BackgroundFill bf = new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1), null);
hbox.setBackground(new Background(bf));
}
}
});
hbox.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
if(!primaryStage.isMaximized()){
primaryStage.setX(mouseEvent.getScreenX() + dragX);
primaryStage.setY(mouseEvent.getScreenY() + dragY);
BackgroundFill bf = new BackgroundFill(Color.BLANCHEDALMOND, new CornerRadii(1), null);
hbox.setBackground(new Background(bf));
}
}
});
hbox.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
if(!primaryStage.isMaximized()){
if (!mouseEvent.isPrimaryButtonDown()) {
hbox.setCursor(Cursor.HAND);
}
}
}
});
hbox.setOnMouseExited(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
if (!mouseEvent.isPrimaryButtonDown()) {
hbox.setCursor(Cursor.DEFAULT);
}
}
});
HBox hbox2 = new HBox(10.0);
HBox.setHgrow(hbox2, Priority.ALWAYS);
hbox2.getChildren().addAll(min,max,logout);
hbox.getChildren().addAll(label,hbox2);
hbox2.setAlignment(Pos.CENTER_RIGHT);
AnchorPane.setTopAnchor(hbox, 0.0);AnchorPane.setLeftAnchor(hbox, 5.0);AnchorPane.setRightAnchor(hbox, 0.0);
AnchorPane.setBottomAnchor(ap , 0.0);AnchorPane.setTopAnchor(ap , 40.0);
AnchorPane.setLeftAnchor(ap , 5.0); AnchorPane.setRightAnchor(ap , 0.0);
ap .setPrefSize(500, 560);
AnchorPane main = new AnchorPane();
main.getChildren().addAll(hbox,ap);
Scene sc = new Scene(main,500,500);
sc.setRoot(main);
Pane p = new Pane();
AnchorPane.setTopAnchor(p, 80.0);
AnchorPane.setLeftAnchor(p, 60.0);
Group root = new Group();
p.setPrefSize(400, 400);
p.setBackground(new Background(new BackgroundFill(Color.GOLD,
null, null)));
root.getChildren().add(p);
ap.getChildren().add(p);
primaryStage.setScene(sc);
primaryStage.setTitle("Custom window");
primaryStage.show();
BubbledLabel bl1 = new BubbledLabel(BubbleSpec.FACE_LEFT_CENTER);
bl1.relocate(10, 50);
bl1.setText("I love this new Custom stage");
bl1.setBackground(new Background(new BackgroundFill(Color.VIOLET,
null, null)));
BubbledLabel bl2 = new BubbledLabel(BubbleSpec.FACE_RIGHT_CENTER);
bl2.relocate(310, 100);
bl2.setText("We all love it");
bl2.setBackground(new Background(new BackgroundFill(Color.LIGHTPINK,
null, null)));
BubbledLabel bl3 = new BubbledLabel(BubbleSpec.FACE_LEFT_CENTER);
bl3.relocate(10, 150);
bl3.setText("Nikitoslav is going love it");
bl3.setBackground(new Background(new BackgroundFill(Color.YELLOWGREEN,
null, null)));
BubbledLabel bl4 = new BubbledLabel(BubbleSpec.FACE_RIGHT_CENTER);
bl4.relocate(165, 200);
bl4.setText("hmmm.. you have you asked him???");
bl4.setBackground(new Background(new BackgroundFill(Color.GREENYELLOW,
null, null)));
BubbledLabel bl5 = new BubbledLabel(BubbleSpec.FACE_LEFT_CENTER);
bl5.relocate(10, 250);
bl5.setText("yea! yea! ");
bl5.setBackground(new Background(new BackgroundFill(Color.YELLOWGREEN,
null, null)));
BubbledLabel bl6 = new BubbledLabel(BubbleSpec.FACE_RIGHT_CENTER);
bl6.relocate(250, 300);
bl6.setText("Oh really!!? oh stop it!!");
bl6.setBackground(new Background(new BackgroundFill(Color.GREENYELLOW,
null, null)));
p.getChildren().addAll(bl1,bl2,bl3,bl4,bl5,bl6);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
If you just copy the codes here, change ResponsiveButton to Button and remove the Anchorpaneap` and its children, its classes are not added, but if you download the package project there is no problem.
Is this link a possible solution for what you require? How to bind stage resizing with resizing of components?
it is also possible that this link could work for you as well:
JavaFX: autoresize stage after adding child to root parent
The main line of code from the second link is
stage.sizeToScene();
I make resizable borders with mouse cursor position listener, it's work, I have not much time for optimized code:
public class Resize {
double eY = 0;
double eX = 0;
double eStrtY = 0;
double eStrtX = 0;
double sceneStrtY = 0;
double sceneStrtX = 0;
double minW = 600;
double minH = 600;
double w = 0;
public Resize(Stage stage, double w) {
Scene scene = stage.getScene();
AnchorPane root = (AnchorPane)scene.getRoot();
this.w = w;
root.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
eStrtY = e.getSceneY();
eStrtX = e.getSceneX();
sceneStrtY = e.getSceneY();
sceneStrtX = e.getSceneX();
}
});
root.setOnMouseMoved(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
// double w = 8;
double X = event.getSceneX();
double Y = event.getSceneY();
double sW = scene.getWidth();
double sH = scene.getHeight();
if(((X<w)&&(Y<w))||((X<2*w)&&(Y<w))||((Y<2*w)&&(X<w))) {
scene.setCursor(Cursor.NW_RESIZE);
eY = stage.getY();
eX = stage.getX();
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
if(((eStrtX<w)&&(eStrtY<w))||((eStrtX<2*w)&&(eStrtY<w))||((eStrtY<2*w)&&(eStrtX<w))) {
if(stage.getHeight()+(eY-e.getScreenY())>minH) {
stage.setY(e.getScreenY());
stage.setHeight(stage.getHeight()+(eY-e.getScreenY()));
eY = e.getScreenY();
}
if(stage.getWidth()+(eX-e.getScreenX())>minW) {
stage.setX(e.getScreenX());
stage.setWidth(stage.getWidth()+(eX-e.getScreenX()));
eX = e.getScreenX();
}
}
}
});
}
else
if(((X>sW-w)&&(Y<w))||((X>sW-2*w)&&(Y<w))||((X>sW-w)&&(Y<2*w))) {
scene.setCursor(Cursor.NE_RESIZE);
eY = stage.getY();
eX = stage.getX() + stage.getWidth();
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
if(((eStrtX>sW-w)&&(eStrtY<w))||((eStrtX>sW-2*w)&&(eStrtY<w))||((eStrtX>sW-w)&&(eStrtY<2*w))) {
if(stage.getHeight()+(eY-e.getScreenY())>minH) {
stage.setY(e.getScreenY());
stage.setHeight(stage.getHeight()+(eY-e.getScreenY()));
eY = e.getScreenY();
}
if(stage.getWidth()-(eX-e.getScreenX())>minW) {
stage.setWidth(stage.getWidth()-(eX-e.getScreenX()));
eX = e.getScreenX();
}
}
}
});
}
else
if(((X>sW-w)&&(Y>sH-w))||((X>sW-2*w)&&(Y>sH-w))||((X>sW-w)&&(Y>sH-2*w))) {
scene.setCursor(Cursor.SE_RESIZE);
eY = stage.getY() + stage.getHeight();
eX = stage.getX() + stage.getWidth();
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
if(((eStrtX>sW-w)&&(eStrtY>sH-w))||((eStrtX>sW-2*w)&&(eStrtY>sH-w))||((eStrtX>sW-w)&&(eStrtY>sH-2*w))) {
if(stage.getHeight()-(eY-e.getScreenY())>minH) {
stage.setHeight(stage.getHeight()-(eY-e.getScreenY()));
eY = e.getScreenY();
}
if(stage.getWidth()-(eX-e.getScreenX())>minW) {
stage.setWidth(stage.getWidth()-(eX-e.getScreenX()));
eX = e.getScreenX();
}
}
}
});
}
else
if(((X<w)&&(Y>sH-w))||((X<2*w)&&(Y>sH-w))||((X<w)&&(Y>sH-2*w))) {
scene.setCursor(Cursor.SW_RESIZE);
eY = stage.getY() + stage.getHeight();
eX = stage.getX();
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
if(((eStrtX<w)&&(eStrtY>sH-w))||((eStrtX<2*w)&&(eStrtY>sH-w))||((eStrtX<w)&&(eStrtY>sH-2*w))) {
if(stage.getHeight()-(eY-e.getScreenY())>minH) {
stage.setHeight(stage.getHeight()-(eY-e.getScreenY()));
eY = e.getScreenY();
}
if(stage.getWidth()+(eX-e.getScreenX())>minW) {
stage.setX(e.getScreenX());
stage.setWidth(stage.getWidth()+(eX-e.getScreenX()));
eX = e.getScreenX();
}
}
}
});
}
else
if(Y<w) {
scene.setCursor(Cursor.V_RESIZE);
eY = stage.getY();
eX = stage.getX() + stage.getWidth();
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
if((eStrtY<w)&&(stage.getHeight()+(eY-e.getScreenY())>minH)) {
stage.setY(e.getScreenY());
stage.setHeight(stage.getHeight()+(eY-e.getScreenY()));
eY = e.getScreenY();
}
}
});
}
else
if(Y>sH-w) {
scene.setCursor(Cursor.V_RESIZE);
eY = stage.getY() + stage.getHeight();
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
if((eStrtY>sH-w)&&(stage.getHeight()-(eY-e.getScreenY())>minH)) {
stage.setHeight(stage.getHeight()-(eY-e.getScreenY()));
eY = e.getScreenY();
}
}
});
}
else
if(X<w) {
scene.setCursor(Cursor.H_RESIZE);
eX = stage.getX();
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
if((eStrtX<w)&&(stage.getWidth()+(eX-e.getScreenX())>minW)) {
stage.setX(e.getScreenX());
stage.setWidth(stage.getWidth()+(eX-e.getScreenX()));
eX = e.getScreenX();
}
}
});
}
else
if(X>sW-w) {
scene.setCursor(Cursor.H_RESIZE);
eX = stage.getX() + stage.getWidth();
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
if((eStrtX>sW-w)&&(stage.getWidth()-(eX-e.getScreenX())>minW)) {
stage.setWidth(stage.getWidth()-(eX-e.getScreenX()));
eX = e.getScreenX();
}
}
});
}
else
if((X>w)&&(X<sW-w)&&(Y>w)&&(Y<25)) {
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
if((eStrtX>w)&&(eStrtX<sW-w-25*3)&&(eStrtY>w)&&(eStrtY<w+25)) {
stage.setX(e.getScreenX()-sceneStrtX);
stage.setY(e.getScreenY()-sceneStrtY);
}
}
});
}
else
scene.setCursor(Cursor.DEFAULT);
}
});
root.setOnMouseReleased(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
eY = e.getScreenY();
eX = e.getScreenX();
}
});
}
Hey I'm a begginer at java and i've only been doing this for a short period of time, anyways for my final project in java basics i need to make a simple calculator with a gui, i thought it won't be that hard but i was kinda wrong :P i have managed to do the most (i think) but am stuck atm with the event handling for the operations and setting the value to calculate, here is my code and could you please give me suggestions or tips on how to do it :D
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.WritableObjectValue;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class Calculator extends Application {
private DoubleProperty value = new SimpleDoubleProperty();
#Override
public void start(Stage primaryStage) {
FlowPane pane = new FlowPane();
pane.setAlignment(Pos.CENTER);
pane.setPadding(new Insets ( 30 , 20 , 30 , 20));
pane.setHgap(5);
pane.setVgap(5);
pane.setMinWidth(400);
pane.setPrefWidth(400);
pane.setMaxWidth(400);
TextField Rezultat = new TextField();
Rezultat.setEditable(false);
Rezultat.setAlignment(Pos.CENTER);
Rezultat.setMinSize(336, 40);
Rezultat.textProperty().bind(Bindings.format("%.0f" , value));
pane.getChildren().add(Rezultat);
Button sedmica = new Button("7");
Button osmica = new Button("8");
Button devetka = new Button("9");
Button plus = new Button("+");
sedmica.setMinSize(80, 80);
osmica.setMinSize(80, 80);
devetka.setMinSize(80, 80);
plus.setMinSize(80, 80);
pane.getChildren().add(sedmica);
sedmicaHandler handler7 = new sedmicaHandler();
sedmica.setOnAction(handler7);
pane.getChildren().add(osmica);
osmicaHandler handler8 = new osmicaHandler();
osmica.setOnAction(handler8);
pane.getChildren().add(devetka);
devetkaHandler handler9 = new devetkaHandler();
devetka.setOnAction(handler9);
pane.getChildren().add(plus);
plusHandler handlerplus = new plusHandler();
plus.setOnAction(handlerplus);
Button cetvorka = new Button("4");
Button petica = new Button("5");
Button sestica = new Button("6");
Button minus = new Button("-");
cetvorka.setMinSize(80, 80);
petica.setMinSize(80, 80);
sestica.setMinSize(80, 80);
minus.setMinSize(80, 80);
pane.getChildren().add(cetvorka);
cetvorkaHandler handler4 = new cetvorkaHandler();
cetvorka.setOnAction(handler4);
pane.getChildren().add(petica);
peticaHandler handler5 = new peticaHandler();
petica.setOnAction(handler5);
pane.getChildren().add(sestica);
sesticaHandler handler6 = new sesticaHandler();
sestica.setOnAction(handler6);
pane.getChildren().add(minus);
minusHandler handlerminus = new minusHandler();
minus.setOnAction(handlerminus);
Button trica = new Button("3");
Button dvica = new Button("2");
Button jedinica = new Button("1");
Button puta = new Button("*");
trica.setMinSize(80, 80);
dvica.setMinSize(80, 80);
jedinica.setMinSize(80, 80);
puta.setMinSize(80, 80);
pane.getChildren().add(jedinica);
jedinicaHandler handler1 = new jedinicaHandler();
jedinica.setOnAction(handler1);
pane.getChildren().add(dvica);
dvicaHandler handler2 = new dvicaHandler();
dvica.setOnAction(handler2);
pane.getChildren().add(trica);
tricaHandler handler3 = new tricaHandler();
trica.setOnAction(handler3);
pane.getChildren().add(puta);
putaHandler handlerputa = new putaHandler();
puta.setOnAction(handlerputa);
Button nula = new Button("0");
Button jednako = new Button("=");
Button podijeljeno = new Button("/");
Button EE = new Button ("EE");
nula.setMinSize(80, 80);
jednako.setMinSize(80, 80);
podijeljeno.setMinSize(80, 80);
EE.setMinSize(80, 80);
pane.getChildren().add(EE);
EEHandler handlerEE = new EEHandler();
EE.setOnAction(handlerEE);
pane.getChildren().add(nula);
nulaHandler handler0 = new nulaHandler();
nula.setOnAction(handler0);
pane.getChildren().add(jednako);
jednakoHandler handlerjednako = new jednakoHandler();
jednako.setOnAction(handlerjednako);
pane.getChildren().add(podijeljeno);
podijeljenoHandler handlerpodijeljeno = new podijeljenoHandler();
podijeljeno.setOnAction(handlerpodijeljeno);
Scene scene = new Scene(pane);
primaryStage.setTitle("Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main (String[] args) {
Application.launch(args);
}
}
class nulaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
value.set(0);
}
}
class jedinicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("1");
}
}
class dvicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("2");
}
}
class tricaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("3");
}
}
class cetvorkaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("4");
}
}
class peticaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("5");
}
}
class sesticaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("6");
}
}
class sedmicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("7");
}
}
class osmicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("8");
}
}
class devetkaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("9");
}
}
class plusHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("+");
}
}
class minusHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("-");
}
}
class putaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("*");
}
}
class podijeljenoHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("/");
}
}
class jednakoHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("=");
}
}
class EEHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("EE");
}
}
My handlers are just basic ones, they print the number into the console so you can disregard them, i saw some examples with the value.set commands should i go with them or ? please help deadline is in 2 weeks. Thanks a lot
I will not do the homework for you, but just a few tips:
variable-names should start with a lowercase letter (TextField rezultat, not Rezultat)
think about what exactly you expect to happen when you press the buttons:
what should your calculator do, if you press 5 '-' '+' 55. should it subtract or add 55 from 5)
do you want to calculate more than one operation? (5+5+5+5/5)
what about decimal numbers? (you can not fill them in, at your current design)
And you do nearly the same thing for every button.(or at least for 10 buttons you have the same logic)
you can create your application in a loop:
public class Calculator extends Application {
private TextField textField = new TextField();
#Override
public void start(Stage primaryStage) {
List<String> buttons = Arrays.asList("7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", "=", "/", "EE");
FlowPane pane = new FlowPane();
pane.setAlignment(Pos.CENTER);
pane.setPadding(new Insets(30, 20, 30, 20));
pane.setHgap(5);
pane.setVgap(5);
pane.setMinWidth(400);
pane.setPrefWidth(400);
pane.setMaxWidth(400);
textField.setEditable(false);
textField.setAlignment(Pos.CENTER);
textField.setMinSize(336, 40);
// Rezultat.textProperty().bind(Bindings.format("%.0f", value));
pane.getChildren().add(textField);
for (String button : buttons) {
Button b = new Button(button);
b.setMinSize(80, 80);
pane.getChildren().add(b);
b.setOnAction((e) -> doSomething(b.getText()));
}
Scene scene = new Scene(pane);
primaryStage.setTitle("Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
private void doSomething(String text) {
if (text.equalsIgnoreCase("=")) {
// Calc
}
else if (text.equalsIgnoreCase("EE")) {
// EE
} else if (text.equalsIgnoreCase("+") || text.equalsIgnoreCase("-") || text.equalsIgnoreCase("*") || text.equalsIgnoreCase("/")) {
// + - * /
}
// ....
else {
// numeric
textField.appendText(text);
}
}
public static void main(String[] args) {
Application.launch(args);
}
}
public class View extends Application{
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage){
primaryStage.setTitle("Calculator");
GridPane root = new GridPane();
Label textBox1 = new Label("Text1");
root.add(textBox1, 0, 0, 5, 1);
Label textBox2 = new Label("Text2");
root.add(textBox2, 0, 1, 5, 1);
textBox1.setId("lblTextBox1");
textBox2.setId("lblTextBox2");
Button btn0 = new Button("0");
Button btn1 = new Button("1");
Button btn2 = new Button("2");
Button btn3 = new Button("3");
Button btn4 = new Button("4");
Button btn5 = new Button("5");
Button btn6 = new Button("6");
Button btn7 = new Button("7");
Button btn8 = new Button("8");
Button btn9 = new Button("9");
btn0.setId("btn0");
btn1.setId("btn1");
btn2.setId("btn2");
btn3.setId("btn3");
btn4.setId("btn4");
btn5.setId("btn5");
btn6.setId("btn6");
btn7.setId("btn7");
btn8.setId("btn8");
btn9.setId("btn9");
Button btnDot = new Button(".");
Button btnPlus = new Button("+");
Button btnMinus = new Button("-");
Button btnTimes = new Button("*");
Button btnDivide = new Button("/");
Button btnEquals = new Button("=");
Button btnMC = new Button("MC");
Button btnMR = new Button("MR");
Button btnMS = new Button("MS");
Button btnMPlus = new Button("M+");
Button btnMMinus = new Button("M-");
Button btnBack = new Button("<=");
Button btnCE = new Button("CE");
Button btnC = new Button("C");
Button btnPlusOrMinus = new Button("+/-");
Button btnSqrt = new Button("sqrt");
Button btnPercentage= new Button("%");
Button btn1OverX = new Button("1/x");
btnPlus.setId("btnPlus");
btnTimes.setId("btnTimes");
btnDot.setId("btnDot");
btnEquals.setId("btnEquals");
btnC.setId("btnClear");
btn0.setMaxHeight(Double.MAX_VALUE);
btn0.setMaxWidth(Double.MAX_VALUE);
btn1.setMaxHeight(Double.MAX_VALUE);
btn1.setMaxWidth(Double.MAX_VALUE);
btn2.setMaxHeight(Double.MAX_VALUE);
btn2.setMaxWidth(Double.MAX_VALUE);
btn3.setMaxHeight(Double.MAX_VALUE);
btn3.setMaxWidth(Double.MAX_VALUE);
btn4.setMaxHeight(Double.MAX_VALUE);
btn4.setMaxWidth(Double.MAX_VALUE);
btn5.setMaxHeight(Double.MAX_VALUE);
btn5.setMaxWidth(Double.MAX_VALUE);
btn6.setMaxHeight(Double.MAX_VALUE);
btn6.setMaxWidth(Double.MAX_VALUE);
btn7.setMaxHeight(Double.MAX_VALUE);
btn7.setMaxWidth(Double.MAX_VALUE);
btn8.setMaxHeight(Double.MAX_VALUE);
btn8.setMaxWidth(Double.MAX_VALUE);
btn9.setMaxHeight(Double.MAX_VALUE);
btn9.setMaxWidth(Double.MAX_VALUE);
btnEquals.setMaxHeight(Double.MAX_VALUE);
btnEquals.setMaxWidth(Double.MAX_VALUE);
btnMC.setMaxHeight(Double.MAX_VALUE);
btnMC.setMaxWidth(Double.MAX_VALUE);
btnMMinus.setMaxHeight(Double.MAX_VALUE);
btnMMinus.setMaxWidth(Double.MAX_VALUE);
btnPlusOrMinus.setMaxHeight(Double.MAX_VALUE);
btnPlusOrMinus.setMaxWidth(Double.MAX_VALUE);
btnPercentage.setMaxHeight(Double.MAX_VALUE);
btnPercentage.setMaxWidth(Double.MAX_VALUE);
btnSqrt.setMaxHeight(Double.MAX_VALUE);
btnSqrt.setMaxWidth(Double.MAX_VALUE);
btn1OverX.setMaxHeight(Double.MAX_VALUE);
btn1OverX.setMaxWidth(Double.MAX_VALUE);
btnPlus.setMaxHeight(Double.MAX_VALUE);
btnPlus.setMaxWidth(Double.MAX_VALUE);
btnMinus.setMaxHeight(Double.MAX_VALUE);
btnMinus.setMaxWidth(Double.MAX_VALUE);
btnTimes.setMaxHeight(Double.MAX_VALUE);
btnTimes.setMaxWidth(Double.MAX_VALUE);
btnDivide.setMaxHeight(Double.MAX_VALUE);
btnDivide.setMaxWidth(Double.MAX_VALUE);
btnCE.setMaxHeight(Double.MAX_VALUE);
btnCE.setMaxWidth(Double.MAX_VALUE);
btnC.setMaxHeight(Double.MAX_VALUE);
btnC.setMaxWidth(Double.MAX_VALUE);
btnDot.setMaxHeight(Double.MAX_VALUE);
btnDot.setMaxWidth(Double.MAX_VALUE);
root.add(btnMC,0,1);
root.add(btnMR,1,1);
root.add(btnMS,2,1);
root.add(btnMPlus,3,1);
root.add(btnMMinus,4,1);
root.add(btnBack,0,2);
root.add(btnCE,1,2);
root.add(btnC,2,2);
root.add(btnPlusOrMinus,3,2);
root.add(btnSqrt,4,2);
root.add(btn7,0,3);
root.add(btn8,1,3);
root.add(btn9,2,3);
root.add(btnDivide,3,3);
root.add(btnPercentage,4,3);
root.add(btn4,0,4);
root.add(btn5,1,4);
root.add(btn6,2,4);
root.add(btnTimes,3,4);
root.add(btn1OverX,4,4);
root.add(btn1,0,5);
root.add(btn2,1,5);
root.add(btn3,2,5);
root.add(btnMinus,3,5);
root.add(btnEquals,4,5,1,2);
root.add(btn0,0,6,2,1);
root.add(btnDot,2,6);
root.add(btnPlus,3,6);
root.setVgap(5);
root.setHgap(5);
root.setPadding(new Insets(5,5,5,5));
primaryStage.setScene(new Scene(root));
primaryStage.show();
Controller controller = new Controller(primaryStage.getScene());
}
}
public class Model {
SimpleDoubleProperty totalResult = new SimpleDoubleProperty(0);
SimpleDoubleProperty curNumber = new SimpleDoubleProperty(0);
SimpleStringProperty stringDisplayed = new SimpleStringProperty();
String operatorPressed = "";
Boolean isDecimal = false;
int decimalCouter = 0;
public void plusOperator(){
calculate();
operatorPressed = "+";
}
public void calculate(){
switch (operatorPressed){
case "+" :
totalResult.set(totalResult.get()+ curNumber.get());
stringDisplayed.set(stringDisplayed.get()+" + " +curNumber.get());
break;
case "*" :
totalResult.set(totalResult.get()*curNumber.get());
stringDisplayed.set(stringDisplayed.get()+" * " +curNumber.get());
break;
default:
totalResult.set(curNumber.get());
stringDisplayed.set(curNumber.get()+"");
}
curNumber.set(0);
operatorPressed = "";
isDecimal = false;
decimalCouter = 0;
}
public void multiplyOperator(){
calculate();
operatorPressed = "*";
}
public void equalsOperator(){
calculate();
curNumber.setValue(totalResult.get());
totalResult.set(0);
}
public void clearOperator(){
totalResult.setValue(0);
curNumber.setValue(0);
stringDisplayed.set("");
decimalCouter = 0;
isDecimal = false;
}
public void pressedNumber(int number){
if(!isDecimal){
curNumber.setValue(curNumber.get()*10+number);
}
else{
decimalCouter++;
Double tempCurrentNum = curNumber.get();
tempCurrentNum = tempCurrentNum*Math.pow(10,decimalCouter);
tempCurrentNum = tempCurrentNum+number;
tempCurrentNum = tempCurrentNum*Math.pow(10,-decimalCouter);
curNumber.set(tempCurrentNum);
}
}
public void dotOperator(){
isDecimal = true;
}
}
public class Controller {
Model newModel = new Model();
Controller(Scene scene){
Button btnPlus, btnTimes, btnEquals, btnClear, btnDot;
Label textBox1, textBox2;
for(int ii=0;ii<=9;ii++){
Button button = (Button)scene.lookup("#btn"+ii);
int finalIi = ii;
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
pressedNumber(finalIi);
}
});
}
btnPlus = (Button)scene.lookup("#btnPlus");
btnTimes = (Button)scene.lookup("#btnTimes");
btnEquals = (Button)scene.lookup("#btnEquals");
btnDot = (Button)scene.lookup("#btnDot");
btnClear = (Button)scene.lookup("#btnClear");
textBox1 = (Label)scene.lookup("#lblTextBox1");
textBox2 = (Label)scene.lookup("#lblTextBox2");
btnPlus.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
plusOperator();
}
});
btnTimes.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
multiplyOperator();
}
});
btnEquals.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
equalsOperator();
}
});
btnClear.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
clearOperator();
}
});
btnDot.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
dotOperator();
}
});
textBox1.textProperty().bind(newModel.stringDisplayed);
textBox2.textProperty().bind(newModel.curNumber.asString());
}
public void pressedNumber(int number){
newModel.pressedNumber(number);
}
public void plusOperator(){
newModel.plusOperator();
}
public void multiplyOperator(){
newModel.multiplyOperator();
}
public void equalsOperator(){
newModel.equalsOperator();
}
public void clearOperator(){
newModel.clearOperator();
}
public void dotOperator(){
newModel.dotOperator();
}
}
what should I do to change barchart color.
Can anyone give me a clue on:
How to set a color to linecharts?
How to set a css class to series?
public class hmw3 extends Application {
#Override public void start(Stage stage) throws Exception{
stage.setTitle("HİSTOGRAM");
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis(0,50,10);
final BarChart<String,Number> bc =
new BarChart<String,Number>(xAxis,yAxis);
bc.setTitle("HİSTOGRAM");
final VBox verticalbox = new VBox();
final HBox horizontalbox = new HBox();
final Button draw = new Button("DRAW");
CheckBox red = new CheckBox("RED");
red.setSelected(true);
CheckBox blue = new CheckBox("BLUE");
final TextField textfield = new TextField();
horizontalbox.setAlignment(Pos.BOTTOM_RIGHT);
horizontalbox.setSpacing(46);
String filename = textfield.getText();
XYChart.Series series1 = new XYChart.Series();
bc.setPrefSize(800, 600);
horizontalbox.getChildren().addAll(draw, red, blue,textfield);
verticalbox.getChildren().addAll(bc, horizontalbox);
horizontalbox.setPadding(new Insets(10, 10, 10, 50));
Scene scene = new Scene(new Group());
((Group)scene.getRoot()).getChildren().add(verticalbox);
stage.setScene(scene);
stage.show();
//Setting the button on action if its clicked
draw.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
hmw34.occur(textfield.getText(), series1);
bc.getData().add(series1);
bc.setLegendVisible(false);
} catch (FileNotFoundException e) {
System.out.println("Error : No such file");
}
}
});
// rengini düzenleyecek.
/** if (red.isSelected())
bc.setStyle("-fx-bar-fill: #000080;"); // red box checked
else if (blue.isSelected())
bc.setStyle("-fx-bar-fill: #b22222;");// The Blue check box checked*/
}
public static void main(String[] args) {
launch(args);
}
}
datad.nodeProperty().addListener(new ChangeListener<Node>() {
#Override
public void changed(ObservableValue<? extends Node> ov, Node oldNode, Node newNode) {
newNode.setStyle("-fx-bar-fill: red;");
}
});
Among the different possibility I tried, the solution of Mevlana Ayas with "setStyle" method is the only one that works.
Assuming "color" is a string describing the desired color.
For example:
String color = "hsb(0,0,0)";
String opaqueColor = "hsb(0,0,0,0.2)";
For ScatterChart,LineChart,AreaChart, add the following listener on each Data added to the serie:
data.nodeProperty().addListener(new ChangeListener<Node>() {
#Override
public void changed(ObservableValue<? extends Node> ov, Node oldNode, final Node node) {
if (node != null ) {
node.setStyle(String.format("-fx-background-color: %s;", color));
}
}
}
For lineChart:
serie.nodeProperty().addListener((ObservableValue<? extends Node> o, Node old, Node node) -> {
if (node != null) {
if (node instanceof Path) {
node.setStyle(String.format("-fx-stroke: %s;", chartSerie.color));
}
});
For areaChart:
serie.nodeProperty().addListener((ObservableValue<? extends Node> o, Node old, Node node) -> {
if (node != null) {
if (node instanceof Group) {
// AreaChart, assuming FILL is FIRST child and LINE is SECOND child
Group group = (Group) node;
Path fill = (Path) group.getChildren().get(0);
fill.setStyle(String.format("-fx-fill: %s;", chartSerie.opaqueColor));
Path line = (Path) group.getChildren().get(1);
line.setStyle(String.format("-fx-stroke: %s;", chartSerie.color));
}
}
});