I have an arraylist of Point. I want to draw lines out the points. Here is what I have done.
for (int i = 0; i < arrPoint.size(); i++) {
Point startPoint = arrPoint.get(i);
Point endPoint = null;
if (i == arrPoint.size()) {
endPoint = arrPoint.get(0);
} else {
endPoint = arrPoint.get(i + 1);
}
Line line = new Line();
line.setStartX(startPoint.getCoordinateX());
line.setEndX(endPoint.getCoordinateX());
line.setStartY(startPoint.getCoordinateY());
line.setEndY(endPoint.getCoordinateY());
box.getChildren().add(line);
}
My Point cass is like
public class Point {
private double coordinateX;
private double coordinateY;
public Point(double coordinateX, double coordinateY) {
this.coordinateX = coordinateX;
this.coordinateY = coordinateY;
}
public void setCoordinateX(double coordinateX) {
this.coordinateX = coordinateX;
}
public void setCoordinateY(double coordinateY) {
this.coordinateY = coordinateY;
}
public double getCoordinateX() {
return coordinateX;
}
public double getCoordinateY() {
return coordinateY;
}
}
My code is displayed blank. I am new to JavaFx. Can I get any help?
You need to have the points before you can loop over the points to draw.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Draw line");
Group g = new Group();
Scene scene = new Scene(g, 550, 550,Color.web("0x0000FF",1.0));
ObservableList<Point> arrPoint = FXCollections.observableArrayList();
Point point1 = new Point(100, 200);
Point point2 = new Point(300, 400);
arrPoint.addAll(point1, point2);
for (int i = 0; i < arrPoint.size()-1; i++) {
Point startPoint = arrPoint.get(i);
Point endPoint = null;
if (i == arrPoint.size()) {
endPoint = arrPoint.get(0);
} else {
endPoint = arrPoint.get(i + 1);
}
Line line = new Line();
line.setStartX(startPoint.getCoordinateX());
line.setEndX(endPoint.getCoordinateX());
line.setStartY(startPoint.getCoordinateY());
line.setEndY(endPoint.getCoordinateY());
g.getChildren().add(line);
}
primaryStage.setScene(scene);
primaryStage.show();
}
}
I hope it can help you some.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I try to add a method that let a cell get alive if it's clicked by the left mouse button but I don't know how. I tried to add a MouseClickListener but I couldn't connect it to my code. I'm new to JavaFx so it's pretty hard to overview all the functions and how to use them. Every other function of my code works perfectly so far. I hope that anyone of you know how to implement this method. Here is my code:
import com.google.gson.reflect.TypeToken;
import javafx.application.Application;
import javafx.animation.AnimationTimer;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.google.gson.Gson;
import javax.swing.*;
public class conway extends Application {
private static final int width = 500;
private static final int height = 500;
private static final int cellsize = 10;
private static Gson gson = new Gson();
private static class Life{
private final int reihe;
private final int zeile;
private Boolean[][] rules;
private int[][] grid;
private Random random=new Random();
private final GraphicsContext graphics;
public Life(int reihe, int zeile, GraphicsContext graphics){
this.reihe =reihe;
this.zeile =zeile;
this.graphics=graphics;
grid=new int[reihe][zeile];
this.rules = new Boolean[][]{{false, false, false, true, false, false, false, false, false, false},
{false, false, true, true, false, false, false, false, false, false}};
}
public void init(){
for(int i = 0; i< reihe; i++){
for(int j = 0; j< zeile; j++){
grid[i][j]=random.nextInt(2);
}
}
draw();
}
private void draw(){
graphics.setFill(Color.LAVENDER);
graphics.fillRect(0,0,width,height);
for(int i=0; i<grid.length;i++){
for(int j=0; j<grid[i].length; j++){
if(grid[i][j]==1){
graphics.setFill(Color.gray(0.5,0.5));
graphics.fillRect(i*cellsize, j*cellsize,cellsize,cellsize);
graphics.setFill(Color.PURPLE);
graphics.fillRect((i*cellsize)+1, (j*cellsize)+1, cellsize-2, cellsize-2);
}
else{
graphics.setFill(Color.gray(0.5,0.5));
graphics.fillRect(i*cellsize,j*cellsize,cellsize, cellsize);
graphics.setFill(Color.WHITE);
graphics.fillRect((i*cellsize)+1,(j*cellsize)+1,cellsize-2,cellsize-2);
}
}
}
}
private int countNeighbors(int i, int j){
int sum=0;
int iStart=i==0?0:-1;
int iEnd=i==grid.length - 1 ? 0:1;
int jStart=j==0?0:-1;
int jEnd=j==grid[0].length - 1 ? 0:1;
for (int k=iStart; k<=iEnd;k++){
for(int l=jStart;l<=jEnd;l++){
sum+=grid[i+k][l+j];
}
}
sum-=grid[i][j];
return sum;
}
public void tick(){
int[][] next=new int[reihe][zeile];
for(int i = 0; i< reihe; i++){
for(int j = 0; j< zeile; j++){
int nachbar= countNeighbors(i,j);
if(rules[grid[i][j]][nachbar] == true){
next[i][j] = 1;
}
}
}
grid=next;
draw();
}
public void safe() throws IOException {
JsonArray to_safe = new JsonArray();
Path pfad = Paths.get("C:\\Users\\Frodo\\IdeaProjects\\gameoflife\\only_safe_file_for_now.json");
if(Files.exists(pfad) == false) {
Files.createFile(pfad);
}
for(int i = 0; i<grid.length; i++){
JsonArray helper = new JsonArray();
for (int j = 0; j<grid[0].length; j++){
helper.add(grid[i][j]);
}
to_safe.add(helper);
}
Files.writeString(pfad, gson.toJson(to_safe));
}
public void load() throws IOException{
int saved_grid[][];
Path pfad = Paths.get("C:\\Users\\Frodo\\IdeaProjects\\gameoflife\\only_safe_file_for_now.json");
if(Files.exists(pfad) == false) {
return;
}
else {
String array_string = Files.readString(pfad);
saved_grid = gson.fromJson(array_string, new TypeToken<int[][]>(){}.getType());
if (saved_grid.length == 0) {
return;
}
}
grid = saved_grid;
draw();
}
}
public static void main(String[] args) {
launch();
}
public void start(Stage primaryStage) {
VBox root = new VBox(10);
Scene scene = new Scene(root, width, height + 100);
final Canvas canvas = new Canvas(width, height);
final boolean[] leftclick = new boolean[1];
leftclick[0] =false;
scene.setOnMouseClicked(e->{
if(e.getButton().equals(MouseButton.PRIMARY)){
if(leftclick[0]){
leftclick[0] =false;
}
else leftclick[0] =true;
}
});
Button reset = new Button("Reset");
Button step = new Button("Step");
Button run = new Button("Run");
Button stop = new Button("Stop");
Button safe_state = new Button("Safe");
Button load_button = new Button("Load");
Button terminate = new Button("Terminate");
root.getChildren().addAll(canvas, new HBox(10, reset, step, run, stop, safe_state, load_button, terminate));
primaryStage.setScene(scene);
primaryStage.show();
int rows = (int) Math.floor(height / cellsize);
int cols = (int) Math.floor(width / cellsize);
GraphicsContext graphics = canvas.getGraphicsContext2D();
Life life = new Life(rows, cols, graphics);
life.init();
AnimationTimer Animation = new AnimationTimer() {
private long lastUpdate=0;
#Override
public void handle(long now) {
if ((now - lastUpdate) >= TimeUnit.MILLISECONDS.toNanos(100)) {
life.tick();
lastUpdate = now;
}
}
};
reset.setOnAction(l -> life.init());
run.setOnAction(l -> Animation.start());
step.setOnAction(l -> life.tick());
stop.setOnAction(l -> Animation.stop());
safe_state.setOnAction(l-> {
try {
life.safe();
} catch (IOException e) {
e.printStackTrace();
}
});
load_button.setOnAction(l -> {
try {
life.load();
} catch (IOException e) {
e.printStackTrace();
}
});
terminate.setOnAction(l -> {
Stage stage = (Stage) terminate.getScene().getWindow();
stage.close();
});
}
}
Something in this direction should do the trick:
canvas.addEventHandler(MouseEvent.MOUSE_CLICKED,
new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
// is left click
if (t == MouseEvent.BUTTON1) {
grid[rows][cols] = 1;
draw();
}
}
});
I have two classes ViewTaskTest and ControllerTaskTest. The view has two buttons, one to create a random point and the other to start the controller. After the start, the controller will place 10 random points to the chart inside the view. But the points are visible only at the end. I want to see the points being placed one by one. I know, that I have to use somehow the Task-functions and I am struggling to understand this concept.
This is the ViewTaskTest-class:
package View;
import Controller.ControllerTaskTest;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.chart.Axis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.ScatterChart;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ViewTaskTest{
ScatterChart<Number, Number> scatterChart;
XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>();
Axis<Number> xAxis = new NumberAxis(0, 10, 2); ;
Axis<Number> yAxis = new NumberAxis(0, 10, 2); ;
Button buttonAddRandomPoint = new Button("Add random point");
Button buttonStartControllerTest = new Button("Start controller");
private final int MAIN_WINDOW_HEIGHT = 800;
private final int MAIN_WINDOW_WIDTH = 800;
ControllerTaskTest controller;
public ViewTaskTest() {
}
public void setController(ControllerTaskTest controller) {
this.controller = controller;
}
public void fillStage(Stage stage) {
stage.setTitle("QuickPID");
stage.setMinHeight(MAIN_WINDOW_HEIGHT);
stage.setMinWidth(MAIN_WINDOW_WIDTH);
stage.setMaxHeight(MAIN_WINDOW_HEIGHT);
stage.setMaxWidth(MAIN_WINDOW_WIDTH);
Scene sceneOne = new Scene(new Group());
scatterChart = new ScatterChart<Number, Number>(xAxis, yAxis);
scatterChart.getData().add(series);
// add a random point
buttonAddRandomPoint.setOnAction(e -> {
Double x = new Double(0.0);
Double y = new Double(0.0);
try{
x = Math.random() * 10;
y = Math.random() * 10;
series.getData().add(new XYChart.Data<Number, Number>(x, y));
} catch (Exception ex) {
System.out.println("Error");
}
});
buttonStartControllerTest.setOnAction(e -> {
controller.startAddingPoints();
});
VBox vboxButtons = new VBox(5);
HBox hboxMain = new HBox(5);
vboxButtons.getChildren().addAll(buttonAddRandomPoint, buttonStartControllerTest);
vboxButtons.setAlignment(Pos.BOTTOM_LEFT);
vboxButtons.setPadding(new Insets(10));
hboxMain.getChildren().addAll(scatterChart, vboxButtons);
sceneOne.setRoot(hboxMain);
stage.setScene(sceneOne);
}
public void addRandomPointFromController(Double x, Double y) {
System.out.println("starting view task");
Task<Integer> task = new Task<Integer>() {
#Override protected Integer call() throws Exception {
series.getData().add(new XYChart.Data<Number, Number>(x, y));
return 0;
}
};
task.run();
}
}
Here is the ControllerTestTask-Class:
package Controller;
import View.ViewTaskTest;
import javafx.concurrent.Task;
public class ControllerTaskTest {
ViewTaskTest view;
public ControllerTaskTest() {
}
public void setView(ViewTaskTest view) {
this.view = view;
}
public void startAddingPoints() {
System.out.println("starting controller task");
Task<Integer> task = new Task<Integer>() {
#Override protected Integer call() throws Exception {
for(int i = 0; i < 10; i++) {
Double x = Math.random() * 10;
Double y = Math.random() * 10;
view.addRandomPointFromController(x, y);
System.out.println("Adding point x = " + x + " and y = " + y);
Thread.sleep(100);
}
return 0;
}
};
task.run();
}
}
Here is the main-class:
package Test;
import Controller.ControllerTaskTest;
import View.ViewTaskTest;
import javafx.application.Application;
import javafx.stage.Stage;
public class Test extends Application{
private ViewTaskTest view= new ViewTaskTest();
private ControllerTaskTest controller = new ControllerTaskTest();
public static void main(String[] args) {
launch();
}
#Override
public void start(Stage stage) throws Exception {
view.setController(controller);
controller.setView(view);
stage.show();
view.fillStage(stage);
}
}
Some please explain me what I am doing wrong. I am experimenting with the Thread-funcitons but I cant solve my problem.
This question already has answers here:
JavaFX launch another application
(3 answers)
Closed 4 years ago.
I've got an app made in javafx and another class with menu in this project. In this menu I've got two buttons and one works (exit buuton) and I want buttonStart to open my Main class. How to launch it?
Button buttonStart = new Button("START GAME");
Button buttonExit = new Button("EXIT");
buttonExit.setOnMouseClicked(event -> System.exit(0));
My menu:
package pl.main;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Menu extends Application {
private BorderPane layout;
private Scene scene;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage window) throws Exception {
layout = new BorderPane();
scene = new Scene(layout, 720, 480);
HBox hbox = new HBox();
hbox.setPadding(new Insets(15, 12, 15, 12));
hbox.setSpacing(10);
hbox.setStyle("-fx-background-color: #F9A825;");
Button buttonStart = new Button("START GAME");
buttonStart.setPrefSize(100, 20);
buttonStart.setStyle("-fx-background-color: #E65100;");
Button buttonExit = new Button("EXIT");
buttonExit.setPrefSize(100, 20);
buttonExit.setStyle("-fx-background-color: #E65100;");
buttonExit.setOnMouseClicked(event -> System.exit(0));
hbox.getChildren().addAll(buttonStart, buttonExit);
layout.setCenter(hbox);
window.setScene(scene);
window.show();
}
}
Class which I wanna launch:
package pl.main;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import java.util.ArrayList;
import java.util.HashMap;
public class Main extends Application {
private HashMap<KeyCode, Boolean> keys = new HashMap<KeyCode, Boolean>();
private ArrayList<Node> blocks = new ArrayList<Node>();
private Pane appRoot = new Pane();
private Pane gameRoot = new Pane();
private Pane uiRoot = new Pane();
private Node player;
private Point2D playerGoDown = new Point2D(0, 0);
private Point2D playerGoRight = new Point2D(0, 0);
private boolean canJump = true;
private int levelWidth;
private void initContent() {
Rectangle background = new Rectangle(720, 480);
// BackgroundFill(Color.WHITE);
levelWidth = LevelData.LEVEL1[0].length();
for (int i = 0; i < LevelData.LEVEL1.length; i++) {
String map = LevelData.LEVEL1[i] + LevelData.LEVEL2[i]+ LevelData.LEVEL1[i]+ LevelData.LEVEL2[i]+ LevelData.LEVEL1[i]+ LevelData.LEVEL2[i];
String line = map;
for (int j = 0; j < line.length(); j++) {
switch (line.charAt(j)) {
case '0':
break;
case '1':
Node block = createEntity(j * 30, i * 30, 30, 30, Color.ORANGE);
blocks.add(block);
break;
}
}
}
player = createEntity(0, 350, 40, 40, Color.YELLOW);
// a ????????????
player.translateXProperty().addListener((a, old, newValue) -> {
int offset = newValue.intValue();
//if (offset > 360 && offset < levelWidth - 360) {
gameRoot.setLayoutX(-(offset - 360));
//}
});
appRoot.getChildren().addAll(background, gameRoot, uiRoot);
}
private void update() {
if (isPressed(KeyCode.W) && player.getTranslateY() >= 0) {
jumpPlayer();
}
if (playerGoDown.getY() < 10) {
playerGoDown = playerGoDown.add(0, 1);
}
movePlayerY((int) playerGoDown.getY());
if (player.getTranslateX() <= levelWidth - 5) {
// movePlayerX(5);
movePlayerRight();
}
if (playerGoRight.getX() < 0) {
playerGoRight = playerGoRight.add(0, 1);
}
movePlayerX((int) playerGoRight.getX());
}
private void movePlayerX(int value) {
boolean movingRight = value > 0;
for (int i = 0; i < Math.abs(value); i++) {
for (Node block : blocks) {
if (player.getBoundsInParent().intersects(block.getBoundsInParent())) {
if (movingRight) {
if (player.getTranslateX() + 40 == block.getTranslateX()) {
return;
}
} else {
if (player.getTranslateX() == block.getTranslateX() + 60) {
return;
}
}
}
}
player.setTranslateX(player.getTranslateX() + (movingRight ? 1 : -1));
}
}
private void movePlayerY(int value) {
boolean movingDown = value > 0;
for (int i = 0; i < Math.abs(value); i++) {
for (Node block : blocks) {
if (player.getBoundsInParent().intersects(block.getBoundsInParent())) {
if (movingDown) {
if (player.getTranslateY() + 40 == block.getTranslateY()) {
canJump = true;
return;
}
} else {
if (player.getTranslateY() == block.getTranslateY() + 60) {
return;
}
}
}
}
player.setTranslateY(player.getTranslateY() + (movingDown ? 1 : -1));
}
}
private void jumpPlayer() {
if (canJump) {
playerGoDown = playerGoDown.add(0, -10);
canJump = false;
}
}
private void movePlayerRight() {
playerGoRight = playerGoRight.add(10, 0);
}
private Node createEntity(int x, int y, int w, int h, Color color) {
Rectangle entity = new Rectangle(w, h);
entity.setTranslateX(x);
entity.setTranslateY(y);
entity.setFill(color);
gameRoot.getChildren().add(entity);
return entity;
}
private boolean isPressed(KeyCode key) {
return keys.getOrDefault(key, false);
}
#Override
public void start(Stage primaryStage) throws Exception {
initContent();
Scene scene = new Scene(appRoot);
scene.setOnKeyPressed(event -> keys.put(event.getCode(), true));
scene.setOnKeyReleased(event -> keys.put(event.getCode(), false));
primaryStage.setTitle("Jetpack gameplay");
primaryStage.setScene(scene);
primaryStage.show();
primaryStage.setResizable(false);
AnimationTimer timer = new AnimationTimer() {
#Override
public void handle(long now) {
update();
}
};
timer.start();
}
public static void main(String[] args) {
launch(args);
}
}
In future I wanna change current Main.java into ordinary class because now I have two classes which works independently.
If you want to go on another page, you have to load the game scene.
Look at Scene class in JavaDoc.
Once you have your scene, you just have to add an ActionEvent to your button that will display your page.
I have an Array of labels and I want to add an onMouseClicked Event. I tried many ways. my last attempt was adding the mouse event inside of the For Loop block where I created the array of labels. But it still doesnt work. Could you guys please give me some help or advice...
This is my class Calculations, where I am trying to make this mouse event work: I surrounded the important part with hashtags and wrote a comment as well.
package application;
import javafx.scene.control.Label;
public class Calculations {
public Label[] test() {
Label label = new Label();
Label lbs[] = new Label[20*20];
//##################################################################
for (int i = 0 ; i < 400; i++) {
lbs[i] = new Label();
lbs[i].setOnMouseClicked(e -> { // <-- I tried this way,
label.setText("X"); // but it doesnt work
});
//##################################################################
}
lbs[10].setText("x");
return lbs;
}
}
My Main class: the part where the method from the above is called is surrounded in hashtags:
package application;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.RowConstraints;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
GridPane grid = new GridPane();
Scene scene = new Scene(grid, (20 * 20), (20 * 20));
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
for(int i = 0; i < 20; i++) {
ColumnConstraints column = new ColumnConstraints(20);
grid.getColumnConstraints().add(column);
}
for(int i = 0; i < 20; i++) {
RowConstraints row = new RowConstraints(20);
grid.getRowConstraints().add(row);
}
//##################################################################
Calculations c = new Calculations();
int count = 0;
for (int x = 0; x < c.test().length/20; x++){
for (int y = 0; y < c.test().length/20; y++){
grid.add(c.test()[count], x, y);
count++;
}
}
//##################################################################
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
I have a Question how can i create this in Java with live update percentage
<div class="meter">
<span id="bar1" style="width: 50%">test</span>
<span id="bar2" style="width: 50%">test</span>
</div>
You can see its a Bar (meter) lets say 1000px and two bars in it. If someone Vote for Team one bar1 is 100% and bar2 0% so in meter there is only bar1.
I try it with JavaFX 8 Rectangle that chang dynamicly width, but donst work becuase it dosnt update.
Main.java
package application;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.NickAlreadyInUseException;
import application.TwitchBot.Test;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextArea;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.scene.paint.Paint;
public class Main extends Application implements Test{
//local interface stuff
TextArea output = new TextArea();
Rectangle bar1 = new Rectangle();
Rectangle bar2 = new Rectangle();
double MID = 315;
Stage secondStage = new Stage();
Pane BarPane = new Pane();
Scene Bar = new Scene(BarPane, 650, 150, Color.GREEN);
#Override
public void start(Stage primaryStage) throws NickAlreadyInUseException, IOException, IrcException {
//Stage 1
StackPane root = new StackPane();
Scene scene = new Scene(root, 300, 250);
output.setEditable(false);
root.getChildren().add(output);
output.appendText("/// WELCOME TO THE TWITCH BOT PREALPHA ///");
primaryStage.setTitle("Twitch Bot");
primaryStage.setScene(scene);
primaryStage.show();
//create Stage2
BarPane.setStyle("-fx-background-color:#00FF00");
BarPane.setPrefSize(200,200);
//BAR 1
Rectangle bar1 = new Rectangle();
bar1.setX(10);
bar1.setY(50);
bar1.setWidth(MID);
bar1.setHeight(50);
bar1.setFill(Color.BLUE);
//Bar 2
Rectangle bar2 = new Rectangle();
bar2.setX(MID);
bar2.setY(50);
bar2.setWidth(650-MID-10);
bar2.setHeight(50);
bar2.setFill(Color.RED);
BarPane.getChildren().addAll(bar1,bar2);
secondStage.setTitle("Second Stage");
secondStage.setScene(Bar);
secondStage.show();
//Start BOT
TwitchBot bot = new TwitchBot();
bot.interfaceCallback = this;
bot.setVerbose(true);
bot.connect("irc.twitch.tv", 6667, "oauth:XXXXXXX");
bot.joinChannel("#XXXXXXX");
}
public void stop(){
System.exit(0);
}
public static void main(String[] args){
launch(args);
}
#Override
public void printScreen(String message) {
Platform.runLater(new Runnable(){
#Override
public void run() {
output.appendText("\n");
output.appendText(message);
secondStage.show();
}
});
}
#Override
public void setPercent(double Team1, double Team2) {
MID = ((650*Team1)/100)-10;
Platform.runLater(new Runnable(){
#Override
public void run() {
System.out.println(MID);
bar1.setWidth(MID);
bar2.setX(MID);
bar2.setWidth(650-MID-10);
}
});
}
#Override
public void setTeamnames(String Team1, String Team2) {
Platform.runLater(new Runnable(){
#Override
public void run() {
}
});
}
}
TwitchBot.java
package application;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Properties;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.jibble.pircbot.*;
public class TwitchBot extends PircBot {
// Count Votes
double VoteT1 = 0;
double VoteT2 = 0;
double TotalVotes = 0;
double T1percent = 0;
double T2percent = 0;
// User Arry (Every user can vote 1 time
String users[] = new String[0];
// Files
File configFile = new File("config.properties");
String team1 = "team1.txt";
String team2 = "team2.txt";
String teamnames = "teams.txt";
// Write Channel
String Channel = "#XXXXX";
// Name
String BotName = "DotaLanBot";
// Default Keywords
String Voting = "!voteing"; //Vote Statistics
// Default Properties
String Team1 = "none";
String Team2 = "none";
String Power = "XXX";
public Test interfaceCallback;
public interface Test{
public void printScreen(String message);
public void setPercent(double Team1, double Team2);
public void setTeamnames(String Team1, String Team2);
}
public TwitchBot() {
loadSettings();
this.setName("dotalanbot");
sendMessage(Channel, "Hi I'm your Bot");
//writeInfile(teamnames, Team1 + " vs " + Team2);
T1percent = 50;
T2percent = 50;
}
public void onMessage(String channel, String sender, String login,String hostname, String message) {
//Chat ausgabe in Textfeld
interfaceCallback.printScreen(sender+": "+message);
if (message.equalsIgnoreCase("!win " + Team1)) {
if (check(sender)) {
System.out.println("vote team1");
System.out.println(sender);
VoteT1++;
TotalVotes++;
sendMessage(Channel, "Vote for " + Team1);
T1percent = calcPercent(VoteT1);
T2percent = calcPercent(VoteT2);
interfaceCallback.setPercent(T1percent,T2percent);
// users(sender);
}
}
if (message.equalsIgnoreCase("!win " + Team2)) {
if (check(sender)) {
System.out.println("vote team1");
System.out.println(sender);
VoteT2++;
TotalVotes++;
sendMessage(Channel, "Vote for " + Team2);
T1percent = calcPercent(VoteT1);
T2percent = calcPercent(VoteT2);
interfaceCallback.setPercent(T1percent,T2percent);
//users(sender);
}
}
if (message.equalsIgnoreCase(Voting)) {
System.out.println(Team1 + ":" + VoteT1 + " Votes");
System.out.println(Team2 + ":" + VoteT2 + " Votes");
System.out.println("Total Votes:" + TotalVotes);
sendMessage(Channel, Team1 + ":" + VoteT1 + " Votes || " + Team2
+ ":" + VoteT2 + " Votes || " + "Total Votes:"
+ TotalVotes);
}
if (message.equalsIgnoreCase("!resetvote")) {
if (sender.equalsIgnoreCase(Power)) {
sendMessage(Channel, "Voteing Reset");
resetvote();
}
}
if (message.equalsIgnoreCase("!test")) {
sendMessage(Channel, "Test");
}
if(message.length()>9){
if ((message.substring(0, 9)).equalsIgnoreCase("!setteam1" )) {
if (sender.equalsIgnoreCase(Power)) {
sendMessage(Channel, "Team 1 set to = "+message.substring(10));
Team1 = message.substring(10);
}
}
if ((message.substring(0, 9)).equalsIgnoreCase("!setteam2" )) {
if (sender.equalsIgnoreCase(Power)) {
sendMessage(Channel, "Team 2 set to = "+message.substring(10));
Team2 = message.substring(10);
}
}
}
}
//reset Voteing
private void resetvote(){
//writeInfile(teamnames, Team1 + " vs " + Team2);
T1percent = 50;
T2percent = 50;
interfaceCallback.setPercent(T1percent,T2percent);
String users[] = new String[0];
saveSettings();
}
// write user to array
private void users(String user) {
String[] temp = new String[users.length + 1];
temp[temp.length - 1] = user;
users = temp;
}
// Check if user votes before
private boolean check(String user) {
for (int i = 0; i < users.length; i++) {
if (user.equalsIgnoreCase(users[i])) {
return false;
}
}
return true;
}
// CALS PERCENT
private double calcPercent(double calc) {
double result = (calc / TotalVotes) * 100;
return result;
}
// SETTINGS STUFF
private void saveSettings() {
// wirte Prop
try {
Properties props = new Properties();
props.setProperty("Team1", Team1);
props.setProperty("Team2", Team2);
props.setProperty("Power", Power);
FileWriter writer = new FileWriter(configFile);
props.store(writer, "settings");
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
} catch (IOException ex) {
// I/O error
}
}
private void loadSettings() {
// Read
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
Team1 = props.getProperty("Team1");
Team2 = props.getProperty("Team2");
Power = props.getProperty("Power");
reader.close();
} catch (FileNotFoundException ex) {
// file does not exist
} catch (IOException ex) {
// I/O Error
}
}
}
The Rectangles you add to the scene graph (via BarPane.getChildren().addAll(...)) are not the same ones you reference outside the start(...) method. Hence when you update them in setPercent(...) with bar1.setWidth(...) and bar2.setWidth(...) you are not updating the Rectangles that are displayed.
The problem is that you declare the instance variables a the beginning of the class definition with
Rectangle bar1 = new Rectangle();
Rectangle bar2 = new Rectangle();
and then in the start(...) method, you declare local variables with the same names:
#Override
public void start(Stage primaryStage) {
// ...
Rectangle bar1 = new Rectangle();
// ...
Rectangle bar2 = new Rectangle();
// ...
}
Since you have declared them again here, they are not the same variables.
To fix this, just remove the declaration in the start(...) method, i.e.:
#Override
public void start(Stage primaryStage) {
// ...
bar1 = new Rectangle();
// ...
bar2 = new Rectangle();
// ...
}
It is probably a good idea to remove the initialization at the top of the class too. That way if you did make the error you made, you would be notified as soon as you tried to access them, with a NullPointerException. So:
public class Main extends Application implements Test{
//...
Rectangle bar1 ;
Rectangle bar2 ;
// ...
#Override
public void start(Stage primaryStage) {
// ...
bar1 = new Rectangle();
// ...
bar2 = new Rectangle();
// ...
}
// ...
}