I am trying to make a cashier program that prints the chosen products with the price on a separate screen. I'm almost there but can't figure out how to do the last part.
When i choose my products i get these returns:
[Ljava.lang.String;#3774e19
instead of like:
Pizza Margherita - (eur)6.-
This is my code:
public class Main extends Application {
int screenWidth = 500;
int screenHeight = 300;
int pizzaCounter = 0;
int totalPrice = 0;
double korting = 1.0;
int buttonCounter = 0;
int count = 0;
Text pizzaCounterText = new Text();
final StackPane root = new StackPane();
final StackPane root2 = new StackPane();
public static final ObservableList data = FXCollections.observableArrayList();
ListView<String> receipt = new ListView<>(data);
Button[] buttons = new Button[8];
String[] producten = new String[8];
String[] totaal = new String[200];
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Kassa");
TextArea textArea = new TextArea();
VBox vbox = new VBox(textArea);
receipt.setEditable(false);
receipt.setStyle("-fx-font-size:20.0;");
root2.getChildren().add(receipt);
HBox hbox = new HBox();
Button discount = new Button("10% korting");
Button afrekenen = new Button("Afrekenen!");
discount.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (korting == 1) {
korting = 0.9;
} else {
korting = 1;
}
}
});
afrekenen.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
primaryStage.setScene(new Scene(root2, screenWidth, screenHeight));
primaryStage.show();
}
});
hbox.getChildren().addAll(discount, afrekenen);
Scene scene = new Scene(vbox, -310, -40);
primaryStage.setScene(scene);
primaryStage.show();
pizzaCounterText.setText("Items bought: " + Integer.toString(pizzaCounter) + "\nTotal: " + Integer.toString(totalPrice) + ",--");
producten[0] = "Pizza Margherita-6";
producten[1] = "Pizza Funghi-10";
producten[2] = "Pizza Prociutto-8";
producten[3] = "Pizza Hawaii-11";
producten[4] = "Pizza Shoarma-12";
producten[5] = "Pizza Salami-10";
producten[6] = "Cola Regular-2";
producten[7] = "Cola Zero-2";
// maakt de buttons
for (int i = 0; i < 8; i++) {
String[] parts = producten[i].split("-");
buttons[i] = createButton(i, parts[0], Integer.parseInt(parts[1]));
}
root.setAlignment(TOP_LEFT);
pizzaCounterText.setTranslateX(screenWidth - 300);
pizzaCounterText.setTranslateY(screenHeight - 40);
vbox.setTranslateX(screenWidth - 500);
vbox.setTranslateY(screenHeight - 40);
hbox.setTranslateX(screenWidth - 350);
hbox.setTranslateY(screenHeight - 90);
root.getChildren().add(hbox);
root.getChildren().add(vbox);
root.getChildren().add(pizzaCounterText);
primaryStage.setScene(new Scene(root, screenWidth, screenHeight));
primaryStage.show();
}
public Button createButton(int index, String name, int price) {
Button btn = new Button();
btn.setText(name);
btn.setMinWidth(100);
int column = buttonCounter % 3;
int row = buttonCounter / 3;
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
totalPrice += price;
pizzaCounter++;
do {
totaal[count] = name;
count++;
data.add(producten);
} while (bonActive());
pizzaCounterText.setText("Items bought: " + Integer.toString(pizzaCounter) + "\nTotal: " + Double.toString(totalPrice * korting));
System.out.println(Arrays.deepToString(totaal));
}
});
btn.setTranslateX(50 + 150 * column);
btn.setTranslateY(35 + 50 * row);
root.getChildren().add(btn);
buttonCounter++;
return btn;
}
public boolean bonActive() {
return false;
}
public void bon() {
for (int i = 0; i < totaal.length; i++) {
System.out.println(totaal[i]);
}
}
}
You are adding on the ObservableList data every time the array String[] producten so it's displaying this object. I think what you want to do is something like :
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
totalPrice += price;
pizzaCounter++;
do {
totaal[count] = name;
count++;
data.add(name + " " + price);
} while (bonActive());
pizzaCounterText.setText("Items bought: " + Integer.toString(pizzaCounter) + "\nTotal: " + Double.toString(totalPrice * korting));
System.out.println(Arrays.deepToString(totaal));
}
});
But I think you should do some Pojo like :
static class Pizza {
String name;
int price;
public Pizza(String name, int price) {
this.name = name;
this.price = price;
}
#Override
public String toString() {
return "Pizza{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
And also have a strong type on your generic object : ObservableList<Pizza> data = FXCollections.observableArrayList();
Related
i have to found out the plane that is most loaded in relation to it's capacity.
I create a formula inside my Plane class :
import java.util.ArrayList;
import java.util.List;
public class Plane {
private String name;
private int sitPLaces;
private int capacity;
List<Passanger> passangers = new ArrayList<>();
List<Baggage> baggage = new ArrayList<>();
public Plane(String name, int sitPLaces, int capacity) {
this.name = name;
this.sitPLaces = sitPLaces;
this.capacity = capacity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSitPLaces() {
return sitPLaces;
}
public void setSitPLaces(int sitPLaces) {
this.sitPLaces = sitPLaces;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
#Override
public String toString() {
return "Plane{" +
"name='" + name + '\'' +
", sitPLaces=" + sitPLaces +
", capacity=" + capacity +
'}';
}
public void addPassanger(Passanger newPassanger) {
if (capacity < passangers.size()) {
// System.out.println("No space for more passangers");
} else {
// System.out.println("Welcome to board!");
}
passangers.add(newPassanger);
}
//todo you need sum of weight baggages and passengers to compare it
public void addBaggage(Baggage newBaggage) {
baggage.add(newBaggage);
}
public int getKgPassanger() {
int totalKg = 0;
for (int i = 0; i < passangers.size(); i++) {
totalKg += passangers.get(i).getWeight();
}
return totalKg;
}
public int getKgBaggage() {
int totalKg = 0;
for (int i = 0; i < baggage.size(); i++) {
totalKg += baggage.get(i).getWeigh();
}
return totalKg;
}
public int getCombinedKg(){
return getKgBaggage() + getKgPassanger();
}
public int getHowManyPassangersAreIn() {
return passangers.size();
}
}
That helps me to get the sum of Passangers Kg and Baggages Kg - now i know i have to compare the sum of those with the Capacity and return the most laoded to it's capacity (in my situation
should be Plane ({"Plane plane2 = new Plane("Flig", 200, 2000)"})
Here is my Main class:
import java.util.List;
public class Main {
public static void main(String[] args) {
Plane plane1 = new Plane("Beoing", 350, 3000);
plane1.addPassanger(new Passanger("Victor", 100));
plane1.addPassanger(new Passanger("Stefan", 100));
plane1.addBaggage(new Baggage("Kipling", 100));
plane1.addBaggage(new Baggage("Kipling", 100));
Plane plane2 = new Plane("Flig", 200, 2000);
plane2.addPassanger(new Passanger("Mihai", 100));
plane2.addPassanger(new Passanger("Rudy", 100));
plane2.addPassanger(new Passanger("Rudy", 100));
plane2.addBaggage(new Baggage("Kipling", 100));
plane2.addBaggage(new Baggage("Kipling", 100));
plane2.addBaggage(new Baggage("Kipling", 100));
Plane plane3 = new Plane("Aly", 400, 2500);
plane3.addPassanger(new Passanger("Vlad", 100));
plane3.addPassanger(new Passanger("Vali", 100));
plane3.addPassanger(new Passanger("Ionut", 100));
plane3.addPassanger(new Passanger("Ionut", 100));
plane3.addBaggage(new Baggage("Kipling", 100));
plane3.addBaggage(new Baggage("Kipling", 100));
plane3.addBaggage(new Baggage("Kipling", 100));
plane3.addBaggage(new Baggage("Kipling", 100));
List<Plane> planeList = List.of(plane1, plane2, plane3);
Plane mostLoadedinRelation = getMostLoadedinRelation(planeList);
System.out.println("This plane its loaded most in relation to it's capacity: " + mostLoadedinRelation);
}
I made an for() but i do not get the result i need, and i assume that here i am not comparing the right things .
public static Plane getMostLoadedinRelation(List<Plane> planeList) {
Plane closest = planeList.get(0);
for (int i = 0; i < planeList.size(); ++i) {
if (planeList.get(i).getCombinedKg() < planeList.get(i).getCapacity()) {
closest = planeList.get(i);
}
}
return closest;
}
Is it possible to help me by giving me a hint ?
Thanks,
So I'm making a game where the enemies follow the player and the player kills them. How do I make the enemies' ImageViews follow the player.
I have tried some if sentences but I actually have no idea. I also searched everywhere but I only find other people doing it with Swing and I get really confused with a lot of things. I use Javafx btw.
public class Main extends Application{
private static final int HEIGHT = 720;
private static final int WIDTH = 1280;
Scene scene;
BorderPane root, htpLayout;
VBox buttons, paragraphs, images;
Button startButton, htpButton, htpReturnButton, leaderboardButton, exitButton;
Text gameName, paragraph1, paragraph2, paragraph3;
Pane gameLayout;
ImageView background;
Game game = new Game();
Player player = new Player();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage window) throws Exception {
root = new BorderPane();
background = new ImageView("stick mob slayer background.png");
background.fitWidthProperty().bind(window.widthProperty());
background.fitHeightProperty().bind(window.heightProperty());
root.getChildren().add(background);
htpLayout = new BorderPane();
buttons = new VBox(15);
scene = new Scene(root, WIDTH, HEIGHT);
scene.getStylesheets().add("mobslayer/style.css");
gameName = new Text("Mob Slayer Unlimited");
gameName.setFont(Font.font("Complex", 50));
gameName.setFill(Color.WHITE);
root.setAlignment(gameName, Pos.CENTER_LEFT);
root.setTop(gameName);
startButton = new Button("Start Game");
startButton.setOnAction(e -> window.setScene(game.getScene()));
htpButton = new Button("How To Play");
htpButton.setOnAction(e -> scene.setRoot(htpLayout));
leaderboardButton = new Button("Leaderboard");
exitButton = new Button("Exit");
exitButton.setOnAction(e -> Platform.exit());
buttons.getChildren().addAll(startButton, htpButton, leaderboardButton, exitButton);
root.setCenter(buttons);
buttons.setAlignment(Pos.CENTER);
paragraphs = new VBox(30);
paragraph1 = new Text("Objektive\nNär spelet börjar kommer huvudkaraktären möta monster.\n"
+ "Ju längre in i spelet du kommer, ju fler och svårare monster dyker upp.\n"
+ "Ditt mål är att överleva så länge som möjligt.");
paragraph1.setFont(Font.font("Dubai", 13));
paragraph1.setFill(Color.BLACK);
paragraph2 = new Text("Movement\nAlla monster dras imot dig, så du måste akta dig.\n"
+ "Detta gör du med hjälp av piltangenterna.");
paragraph2.setFont(Font.font("Dubai", 13));
paragraph2.setFill(Color.BLACK);
paragraph3 = new Text("Special Effects\nDu kan också attackera tillbaka med en lätt attack(c)\n"
+ "eller med en specialattack(space) som dödar alla monster på skärmen.\n"
+ "Du kan dasha(x) för att röra dig snabbare åt ett håll.");
paragraph3.setFont(Font.font("Dubai", 13));
paragraph3.setFill(Color.BLACK);
paragraphs.getChildren().addAll(paragraph1, paragraph2, paragraph3);
htpReturnButton = new Button("Return");
htpReturnButton.setOnAction(e->scene.setRoot(root));
htpLayout.setBottom(htpReturnButton);
htpLayout.setAlignment(htpReturnButton,Pos.TOP_CENTER);
images = new VBox(30);
// Image image1 = new Image(new FileInputStream("resources\\cod zombies.jpg"));
// final ImageView image11 = new ImageView(image1);
// image11.setFitHeight(100);
// image11.setFitWidth(100);
// image11.setPreserveRatio(true);
//
// Image image2 = new Image(new FileInputStream("resources\\arrowkeys.png")) ;
// final ImageView image22 = new ImageView(image2);
// image22.setFitHeight(100);
// image22.setFitWidth(100);
// image22.setPreserveRatio(true);
//
// Image image3 = new Image(new FileInputStream("resources\\keys.png")) ;
// final ImageView image33 = new ImageView(image3);
// image33.setFitHeight(100);
// image33.setFitWidth(100);
// image33.setPreserveRatio(true);
//
// images.getChildren().addAll(image11, image22, image33);
//
paragraphs.setAlignment(Pos.TOP_LEFT);
htpLayout.setLeft(paragraphs);
htpLayout.setRight(images);
window.setTitle("Mob Slayer Unlimited");
window.setScene(scene);
window.setResizable(false);
window.show();
}
}
public class Game {
private static final int HEIGHT = 720;
private static final int WIDTH = 1280;
private Scene scene;
Pane root;
Text health, stamina, wave, kills;
int waveCounter = 1, killCounter = 0;
Button restartButton, pauseButton;
Line limitUp;
Player player = new Player();
Enemies enemy = new Enemies();
public Game() {
health = new Text(50, 30, "HP: " + player.getHealth());
health.setFont(Font.font("BankGothic Lt BT", 30));
health.setFill(Color.WHITE);
stamina = new Text(50, 80, "STAMINA: " + player.getStamina());
stamina.setFont(Font.font("BankGothic Lt BT", 30));
stamina.setFill(Color.WHITE);
wave = new Text(1050, 30, "WAVE: " + waveCounter);
wave.setFont(Font.font("BankGothic Lt BT", 30));
wave.setFill(Color.WHITE);
kills = new Text(1050, 80, "KILLS: " + killCounter);
kills.setFont(Font.font("BankGothic Lt BT", 30));
kills.setFill(Color.WHITE);
restartButton = new Button("RESTART");
restartButton.setFont(Font.font("BankGothic Lt BT", 30));
restartButton.setOnAction(e -> restart());
restartButton.setLayoutX(350);
restartButton.setLayoutY(20);
pauseButton = new Button("PAUSE");
pauseButton.setFont(Font.font("BankGothic Lt BT", 30));
pauseButton.setOnAction(e -> restart());
pauseButton.setLayoutX(650);
pauseButton.setLayoutY(20);
limitUp = new Line(0, 100, 1280, 100);
limitUp.setStroke(Color.WHITE);
root = new Pane(player.getSlayer(), limitUp, player.getSlayerHitbox(), health, stamina, wave, kills, restartButton, pauseButton, enemy.getEnemy());
root.setStyle("-fx-background-color: black");
enemy.enemyMovement();
movePlayerTo(WIDTH / 2, HEIGHT / 2);
scene = new Scene(root, WIDTH, HEIGHT);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
switch (event.getCode()) {
case W: player.goUp = true; break;
case S: player.goDown = true; break;
case A: player.goLeft = true; break;
case D: player.goRight = true; break;
case K: player.running = true; break;
}
}
});
scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
switch (event.getCode()) {
case W: player.goUp = false; break;
case S: player.goDown = false; break;
case A: player.goLeft = false; break;
case D: player.goRight = false; break;
case K: player.running = false; break;
}
}
});
AnimationTimer timer = new AnimationTimer() {
#Override
public void handle(long now) {
int dx = 0, dy = 0;
if (player.goUp) dy -= 2;
if (player.goDown) dy += 2;
if (player.goRight) dx += 2;
if (player.goLeft) dx -= 2;
if (player.running) { dx *= 2; dy *= 2; }
enemy.enemyMovement();
movePlayerBy(dx, dy);
}
};
timer.start();
}
public Scene getScene() {
return scene;
}
// I took this methods for movement from Github
public void movePlayerBy(int dx, int dy) {
if (dx == 0 && dy == 0) return;
final double cx = player.getSlayer().getBoundsInLocal().getWidth() / 2;
final double cy = player.getSlayer().getBoundsInLocal().getHeight() / 2;
double x = cx + player.getSlayer().getLayoutX() + dx;
double y = cy + player.getSlayer().getLayoutY() + dy;
movePlayerTo(x, y);
}
public void movePlayerTo(double x, double y) {
final double cx = player.getSlayer().getBoundsInLocal().getWidth() / 2;
final double cy = player.getSlayer().getBoundsInLocal().getHeight() / 2;
if (x - cx >= 0 &&
x + cx <= WIDTH &&
y - cy >= 0 &&
y + cy <= HEIGHT) {
player.getSlayer().relocate(x - cx, y - cy);
player.getSlayerHitbox().relocate(x - cx + 37, y - cy + 35);
}
}
public class Player {
private int health;
private int damage;
private int stamina;
private Image slayerImage;
private ImageView slayer;
private Rectangle slayerHitbox;
boolean running, goUp, goDown, goRight, goLeft;
public Player () {
health = 5;
damage = 1;
stamina = 5;
slayerImage = new Image("stick mob slayer.png", 100, 100, true, true);
slayer = new ImageView(slayerImage);
slayerHitbox = new Rectangle(10, 50);
}
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getStamina() {
return stamina;
}
public void setStamina(int stamina) {
this.stamina = stamina;
}
public ImageView getSlayer() {
return slayer;
}
public Rectangle getSlayerHitbox() {
slayerHitbox.setFill(Color.TRANSPARENT);
return slayerHitbox;
}
}
public class Enemies {
private int health;
private int speed;
private Image enemyImage;
private ImageView enemy;
private Rectangle enemyHitbox;
Player player = new Player();
public Enemies () {
health = 1;
speed = 1;
enemyImage = new Image("stick enemy.png", 100, 100, true, true);
enemy = new ImageView(enemyImage);
enemyHitbox = new Rectangle(10, 50);
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public ImageView getEnemy () {
return enemy;
}
public Rectangle getEnemyHitbox() {
enemyHitbox.setFill(Color.YELLOW);
return enemyHitbox;
}
}
This is everything I have done so far. I would appreciate any help. If possible I would like to know how to make the enemies appear from random spots of the borders of the screen as well. Thanks in advance.
you should try first something more simple like implementing A* path search algo or some grid with some units on it before trying todo a game and having such questions
I would like to create a chart in JavaFX. I have such a file:
And I don't know how to put "date" for x or y axis. How should I do it.
I have something like this, but I'm not sure if it is properly.
draw.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event) {
newWindow.setTitle("Chart");
//defining the axes
if(choice1.getValue().toString()=="val" && choice2.getValue().toString()=="total"){}
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Number of Month");
//creating the chart
final LineChart<Number,Number> lineChart = new LineChart<Number,Number>(xAxis,yAxis);
lineChart.setTitle("Chart");
//defining a series
XYChart.Series series = new XYChart.Series();
series.setName("My portfolio");
//populating the series with data
for(int i=0; i<d.size(); i++){
series.getData().add(new XYChart.Data(d.get(choice1.getValue().toString()).get(i), d.get(choice2.getValue().toString()).get(i)));
}
Scene scene = new Scene(lineChart,800,600);
lineChart.getData().add(series);
newWindow.setScene(scene);
newWindow.show();
}
});
LineChart linechart = new LineChart(xAxis, yAxis);
ChoiceBox choice1 = new ChoiceBox(FXCollections.observableArrayList(
"id", "date", "total", "val")
);
ChoiceBox choice2 = new ChoiceBox(FXCollections.observableArrayList(
"id", "date", "total", "val")
);
Button draw = new Button("Draw!");
HBox hb = new HBox(30);
hb.getChildren().addAll(choice1, choice2);
I create an example that demo's your chart. Since you attached your data as an image, I had to create fake data. In this example, I created a DataFrame class to hold each line of data. I added this data to a List named fakeData. I then create and name each Series that will be added to the Chart. After that, I filter the fake data by ID. If the filtered ID equals the Series name, I added the data to the Series. This chart shows Date to Total. If you need Date to Val, replace seriesList.get(i).getData().add(new XYChart.Data(dataFrame.getDate(), dataFrame.getTotal())); with seriesList.get(i).getData().add(new XYChart.Data(dataFrame.getDate(), dataFrame.getVal()));.
Main
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;
public class LineChartSample extends Application
{
String alphbets = "abcdefghij";
#Override
public void start(Stage stage)
{
List<DataFrame> fakeData = generateFakeDataFrames();
stage.setTitle("Line Chart Sample");
//defining the axes
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Date");
//creating the chart
final LineChart<String, Number> lineChart = new LineChart(xAxis, yAxis);
lineChart.setTitle("Fake Chart");
//defining a series
List<XYChart.Series<String, Number>> seriesList = new ArrayList();
for (int i = 0; i < alphbets.length(); i++) {
XYChart.Series<String, Number> series = new XYChart.Series();
series.setName(alphbets.charAt(i) + "");
seriesList.add(series);
}
for (int i = 0; i < seriesList.size(); i++) {
char tempChar = alphbets.charAt(i);
//Filter the fake data
List<DataFrame> subList = fakeData.stream().filter((t) -> {
return t.getId() == tempChar;
}).collect(Collectors.toList());
//Add the filtered data to the correct series
for (DataFrame dataFrame : subList) {
System.out.println(seriesList.get(i).getName() + " :" + dataFrame.getId() + " " + dataFrame.getDate() + " " + dataFrame.getTotal());//Check to see if data is correct.
seriesList.get(i).getData().add(new XYChart.Data(dataFrame.getDate(), dataFrame.getTotal()));
}
}
Scene scene = new Scene(lineChart, 800, 600);
lineChart.getData().addAll(seriesList);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args)
{
launch(args);
}
public List<LocalDate> createDates()
{
List<LocalDate> localDates = new ArrayList();
LocalDate localDate = LocalDate.of(1985, Month.FEBRUARY, 4);
for (int i = 0; i <= 4; i++) {
localDates.add(localDate.plusDays(i));
}
return localDates;
}
public List<DataFrame> generateFakeDataFrames()
{
Random random = new Random();
List<DataFrame> dataFrames = new ArrayList();
List<LocalDate> dates = createDates();
for (int i = 0; i < 50; i++) {
double total = (random.nextDouble() * 2 - 1) * 3;
double val = (random.nextDouble() * 2 - 1) * 2000;
dataFrames.add(new DataFrame(alphbets.charAt(i % 10), dates.get(i / 10).toString(), total, val));
}
return dataFrames;
}
}
DataFrame Class
/**
*
* #author blj0011
*/
public class DataFrame
{
private char id;
private String date;
private double total;
private double val;
public DataFrame(char id, String date, double total, double val)
{
this.id = id;
this.date = date;
this.total = total;
this.val = val;
}
public double getVal()
{
return val;
}
public void setVal(double val)
{
this.val = val;
}
public char getId()
{
return id;
}
public void setId(char id)
{
this.id = id;
}
public String getDate()
{
return date;
}
public void setDate(String date)
{
this.date = date;
}
public double getTotal()
{
return total;
}
public void setTotal(double total)
{
this.total = total;
}
#Override
public String toString()
{
return id + ", " + date + ", " + total + ", " + date + ", " + val;
}
}
I have on 3 class , 3 stage and I want to do something like this: that I want to do show stage . One time I show 1st stage for 10 sec, next I show 2nd stage for 10 sec and next I show 3rd stage for 10 sec and next I show 1st .... But very important is this that the 3 stage have to work all time .
In swing I will be use CardLayout but here I don't know how do this.
code for one class:
public class SimpleSlideShowTest extends Application{
class SimpleSlideShow {
StackPane root = new StackPane();
ImageView[] slides;
public SimpleSlideShow() {
this.slides = new ImageView[4];
File file1 = new File("C:/Users/022/workspace22/EkranLCD/res/images/belka.png");
Image image1 = new Image(file1.toURI().toString());
File file = new File("C:/Users/022/workspace22/EkranLCD/res/images/kropka.png");
Image image2 = new Image(file.toURI().toString());
Image image3 = new Image(file1.toURI().toString());
Image image4 = new Image(file1.toURI().toString());
slides[0] = new ImageView(image1);
slides[1] = new ImageView(image2);
slides[2] = new ImageView(image3);
slides[3] = new ImageView(image4);
}
public StackPane getRoot() {
return root;
}
// The method I am running in my class
public void start() {
SequentialTransition slideshow = new SequentialTransition();
for (ImageView slide : slides) {
SequentialTransition sequentialTransition = new SequentialTransition();
FadeTransition fadeIn = getFadeTransition(slide, 0.0, 1.0, 0);
PauseTransition stayOn = new PauseTransition(Duration.millis(2000));
FadeTransition fadeOut = getFadeTransition(slide, 0, 0.0, 2000);
sequentialTransition.getChildren().addAll(fadeIn, stayOn, fadeOut);
slide.setOpacity(0);
this.root.getChildren().add(slide);
slideshow.getChildren().add(sequentialTransition);
}
slideshow.play();
}
// the method in the Transition helper class:
public FadeTransition getFadeTransition(ImageView imageView, double fromValue, double toValue, int durationInMilliseconds) {
FadeTransition ft = new FadeTransition(Duration.millis(durationInMilliseconds), imageView);
ft.setFromValue(fromValue);
ft.setToValue(toValue);
return ft;
}
}
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
SimpleSlideShow simpleSlideShow = new SimpleSlideShow();
Text msg = new Text("java2s.com d sad adas dsa sad dsa dsa dsa dsa sdasa dsa dsa");
msg.setFont(Font.font ("Verdana", 40));
msg.setY(Config.ySize-(Config.ySize/6));
Pane root1 = new Pane(msg);
root1.setLayoutX(Config.xSize/2);
root1.setLayoutY(Config.ySize-(Config.ySize/5));
root1.setPrefSize(Config.xSize/2,400);
Main2.start(msg);
simpleSlideShow.getRoot().getChildren().add(root1);
Scene scene = new Scene(simpleSlideShow.getRoot());
primaryStage.setScene(scene);
primaryStage.show();
simpleSlideShow.start();
}
}
My second class which I want to add
public class TestURLImage4 extends Application {
public static ArrayList<BusStop2> list = new ArrayList<>();
public static ArrayList<PositionTilesAndURLPaths> positionTilesAndURLPathsList = new ArrayList<>();
public static HashMap<String, Image> imgCache = new HashMap<>();
public static double lat;
public static double lon;
public static double deltaY;
public static double deltaX;
public static double positionX;
public static double positionY;
public static int[] imageCount = getCountImage();
public static int [] countImage = countImage();
public static int []x = new int [countImage[0]];
public static int []y = new int [countImage[1]];
private File file = new File("C:/Users/ElteGps 022/workspace22/EkranLCD/res/images/kropka.png");
private Image bus = new Image(file.toURI().toString());
public TestURLImage4() {
}
TestURLImage4(double lat, double lon){
int [] tiles= getTileNumber(lat, lon, Config.mapZoom);
deltaX = tile2lon(tiles[0] + 1 , Config.mapZoom) - tile2lon(tiles[0], Config.mapZoom);
deltaY = tile2lat(tiles[1], Config.mapZoom) - tile2lat(tiles[1] + 1 , Config.mapZoom);
positionX = (lon - tile2lon(tiles[0], Config.mapZoom)) * Config.imgSize/deltaX;
positionY = (tile2lat(tiles[1], Config.mapZoom) - lat) * Config.imgSize/deltaY;
getTiles(lat,lon);
getImgPositionAndURLsPath(list);
}
/**
* Method use to get count of image what we need
* #return
*/
private static int[] getCountImage(){
int xImageCount = (int) Math.ceil(Config.xSize/256);
int yImageCount = (int) Math.ceil(Config.ySize/256);
return new int[] {xImageCount, yImageCount};
}
/**
* Method use to get count of tiles
* #return
*/
public static int[] countImage(){
int xImageCount = imageCount[0];
int yImageCount = imageCount[1];
if(xImageCount-1 %2 != 0){
xImageCount = xImageCount + 2;
}
if(yImageCount-1 %2 != 0){
yImageCount = yImageCount + 2;
}
return new int[] {xImageCount, yImageCount};
}
/**
* Method use to get tiles
* #param lat
* #param lon
* #return
*/
private static ArrayList<BusStop2> getTiles(double lat, double lon ){
int [] numberTile = getTileNumber(lat, lon, Config.mapZoom);
int a1 = 1;
int a2 = 1;
int a3 = 1;
int a4 = 1;
x[0] = numberTile[0];
y[0] = numberTile[1];
for (int i = 1; i<x.length; i++){
if(i%2==0){
x[i] = numberTile[0]+(a1);
a1++;
}
else{
x[i] = numberTile[0]-(a2);
a2++;
}
}
for (int i = 1; i<y.length; i++){
if(i%2==0){
y[i] = numberTile[1]+(a3);
a3++;
}
else{
y[i] = numberTile[1]-(a4);
a4++;
}
}
for(int i = 0 ; i<x.length ; i++){
for (int j = 0 ;j<y.length ; j++ ){
list.add(new BusStop2(x[i], y[j], x[0] - x[i], y[0]-y[j]));
}
}
return list;
}
/**
*
* #param list
* #return
*/
private static ArrayList<PositionTilesAndURLPaths> getImgPositionAndURLsPath(ArrayList<BusStop2> list){
for(BusStop2 bus : list){
positionTilesAndURLPathsList.add(new PositionTilesAndURLPaths(256*bus.getX(), 256*bus.getY(),
Config.mapPath + "/" + bus.getA() + "/" + bus.getB() + ".png"));
}
return positionTilesAndURLPathsList;
}
public static int [] getTileNumber(final double lat, final double lon, final int zoom) {
int xtile = (int)Math.floor( (lon + 180) / 360 * (1<<zoom) ) ;
int ytile = (int)Math.floor( (1 - Math.log(Math.tan(Math.toRadians(lat)) + 1 / Math.cos(Math.toRadians(lat))) / Math.PI) / 2 * (1<<zoom) ) ;
if (xtile < 0)
xtile=0;
if (xtile >= (1<<zoom))
xtile=((1<<zoom)-1);
if (ytile < 0)
ytile=0;
if (ytile >= (1<<zoom))
ytile=((1<<zoom)-1);
return new int[] {xtile, ytile};
}
static double tile2lon(int x, int z) {
return x / Math.pow(2.0, z) * 360.0 - 180;
}
static double tile2lat(int y, int z) {
double n = Math.PI - (2.0 * Math.PI * y) / Math.pow(2.0, z);
return Math.toDegrees(Math.atan(Math.sinh(n)));
}
#Override
public void start(Stage stage) throws Exception {
Canvas canvas = new Canvas(Config.xSize, Config.ySize);
GraphicsContext gc = canvas.getGraphicsContext2D();
int [] aa =getTileNumber(51.401968,16.205556, 18);
getTiles(51.401968,16.205556);
getImgPositionAndURLsPath(list);
ExecutorService executor = Executors.newFixedThreadPool(10);
ArrayList<UtlToImageConverter> threadList = new ArrayList<>();
for(PositionTilesAndURLPaths url : positionTilesAndURLPathsList){
threadList.add(new UtlToImageConverter(url.getPath()));
}
try {
executor.invokeAll(threadList);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(imgCache.size());
System.out.println( aa[0] + " " + aa[1] );
for(PositionTilesAndURLPaths pos : getImgPositionAndURLsPath(list)){
gc.drawImage(imgCache.get(pos.getPath()),Config.xSize/2-pos.getX()-Config.imgSize/2 ,(Config.ySize/2)- pos.getY()-Config.imgSize/2, Config.imgSize, Config.imgSize);
}
gc.drawImage(bus,Config.xSize/2-Config.imgSize/2-Config.markWidth/2+(int)positionX, Config.ySize/2+(int)positionY-Config.imgSize/2-Config.markHeight/2, Config.markWidth, Config.markHeight);
Pane root = new Pane();
root.getChildren().add(canvas);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args)
{
Application.launch(args);
}
}
This is my class where I implement a simple pics display for my GWT project
public class PhotosSlideShow extends Composite {
private List<Image> photos;
private int curr;
private AbsolutePanel mainPnl;
private SimplePanel centerPnl;
private Image n;
private Image p;
private final int WIDTH = 800;
public PhotosSlideShow(final List<String> result) {
curr = 0;
photos = new ArrayList<Image>();
mainPnl = new AbsolutePanel();
this.initWidget(mainPnl);
this.setStyleName("slideShow");
centerPnl = new SimplePanel();
String path = GWT.getModuleBaseURL() + "imageUpload?src=";
for (String foto : result) {
String url = path.concat(foto);
Image.prefetch(url);
final Image curr = new Image(url);
double ratio = getRatio(curr);
curr.setPixelSize(WIDTH, (int) (ratio * WIDTH));
curr.addMouseOverHandler(new MouseOverHandler() {
#Override
public void onMouseOver(MouseOverEvent event) {
n.setVisible(true);
p.setVisible(true);
}
});
curr.addMouseOutHandler(new MouseOutHandler() {
#Override
public void onMouseOut(MouseOutEvent event) {
n.setVisible(false);
p.setVisible(false);
}
});
photos.add(curr);
}
n = new Image("images/next.png");
n.setPixelSize(40, 50);
n.setVisible(false);
n.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
showNext();
}
});
p = new Image("images/prev.png");
p.setPixelSize(40, 50);
p.setVisible(false);
p.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
showPrev();
}
});
centerPnl.setWidget(photos.get(curr));
mainPnl.add(centerPnl);
mainPnl.add(n);
mainPnl.add(p);
posizionaBottoni();
}
private void showNext() {
if (curr == photos.size() - 1) {
curr = 0;
centerPnl.setWidget(photos.get(curr));
} else {
curr++;
centerPnl.setWidget(photos.get(curr));
}
posizionaBottoni();
}
private void showPrev() {
if (curr == 0) {
curr = photos.size() - 1;
centerPnl.setWidget(photos.get(curr));
} else {
curr--;
centerPnl.setWidget(photos.get(curr));
}
posizionaBottoni();
}
private void posizionaBottoni() {
mainPnl.setWidgetPosition(p, 0,
(int) (photos.get(curr).getHeight() / 2 - p.getHeight() / 2));
mainPnl.setWidgetPosition(n, (int) (WIDTH - n.getWidth()),
(int) (photos.get(curr).getHeight() / 2 - n.getHeight() / 2));
}
private double getRatio(Image i) {
System.out.println("DIMENSIONI ORIGINALI: " + i.getWidth() + " x "
+ i.getHeight());
double res = (double) i.getHeight() / i.getWidth();
System.out.println("RATIO: " + res);
return res;
}
}
Apparently everything works pretty fine, but there is 1 minor problem: When I hover the pointer over the image, the buttons correctly appear, but as I move the mouse on the buttons to click them, they flicker.
Do anyone know what may be the reason for this strange behaviour?
thanks in advance.