JavaFx Stageshow 3 different stage - java

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);
}
}

Related

How to prevent my Mandelbrotset code from getting blurry

I have written the mandelbrotset in java,but if i want to zoom into it it gets blurry after around 14 clicks, no matter the Maxiterration number, if its 100 it gets blurry and if its 100000 it gets blurry after 14 zoom ins.Something i noticed is that after i zoom in twice, all of the next zoom ins are instant in contrast to the first two which usually take a few seconds, this may help finding the solution. The code:
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.math.BigDecimal;
public class test extends JFrame {
static final int WIDTH = 400;
static final int HEIGHT = WIDTH;
Canvas canvas;
BufferedImage fractalImage;
static final int MAX_ITER = 10000;
static final BigDecimal DEFAULT_TOP_LEFT_X = new BigDecimal(-2.0);
static final BigDecimal DEFAULT_TOP_LEFT_Y = new BigDecimal(1.4);
static final double DEFAULT_ZOOM = Math.round((double) (WIDTH/3));
final int numThreads = 10;
double zoomFactor = DEFAULT_ZOOM;
BigDecimal topLeftX = DEFAULT_TOP_LEFT_X;
BigDecimal topLeftY = DEFAULT_TOP_LEFT_Y;
BigDecimal z_r = new BigDecimal(0.0);
BigDecimal z_i = new BigDecimal(0.0);
// -------------------------------------------------------------------
public test() {
setInitialGUIProperties();
addCanvas();
canvas.addKeyStrokeEvents();
updateFractal();
this.setVisible(true);
}
// -------------------------------------------------------------------
public static void main(String[] args) {
new test();
}
// -------------------------------------------------------------------
private void addCanvas() {
canvas = new Canvas();
fractalImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
canvas.setVisible(true);
this.add(canvas, BorderLayout.CENTER);
} // addCanvas
// -------------------------------------------------------------------
private void setInitialGUIProperties() {
this.setTitle("Fractal Explorer");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(WIDTH, HEIGHT);
this.setResizable(false);
this.setLocationRelativeTo(null);
} // setInitialGUIProperties
// -------------------------------------------------------------------
private BigDecimal getXPos(double x) {
return topLeftX.add(new BigDecimal(x/zoomFactor));
} // getXPos
// -------------------------------------------------------------------
private BigDecimal getYPos(double y) {
return topLeftY.subtract(new BigDecimal(y/zoomFactor));
} // getYPos
// -------------------------------------------------------------------
/**
* Aktualisiert das Fraktal, indem die Anzahl der Iterationen für jeden Punkt im Fraktal berechnet wird und die Farbe basierend darauf geändert wird.
**/
public void updateFractal() {
Thread[] threads = new Thread[numThreads];
int rowsPerThread = HEIGHT / numThreads;
// Construct each thread
for (int i=0; i<numThreads; i++) {
threads[i] = new Thread(new FractalThread(i * rowsPerThread, (i+1) * rowsPerThread));
}
// Starte jeden thread
for (int i=0; i<numThreads; i++) {
threads[i].start();
}
// Warten bis alle threads fertig sind
for (int i=0; i<numThreads; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
canvas.repaint();
} // updateFractal
// -------------------------------------------------------------------
//Gibt basierend auf der Iterationsanzahl eine trennungsfarbe zurück eines gegebenen Punktes im Fraktal
private class FractalThread implements Runnable {
int startY;
int endY;
public FractalThread(int startY, int endY) {
this.startY = startY;
this.endY = endY;
}
public void run() {
BigDecimal c_r;
BigDecimal c_i;
for (int x = 0; x < WIDTH; x++ ) {
for (int y = startY; y < endY; y++ ) {
c_r = getXPos(x);
c_i = getYPos(y);
int iterCount = computeIterations(c_r, c_i);
int pixelColor = makeColor(iterCount);
fractalImage.setRGB(x, y, pixelColor);
}
System.out.println(x);
}
} // run
} // FractalThread
private int makeColor( int iterCount ) {
int color = 0b011011100001100101101000;
int mask = 0b000000000000010101110111;
int shiftMag = iterCount / 13;
if (iterCount == MAX_ITER)
return Color.BLACK.getRGB();
return color | (mask << shiftMag);
} // makeColor
// -------------------------------------------------------------------
private int computeIterations(BigDecimal c_r, BigDecimal c_i) {
BigDecimal z_r = new BigDecimal(0.0);
BigDecimal z_i = new BigDecimal(0.0);
BigDecimal z_r_tmp = z_r;
BigDecimal dummy2 = new BigDecimal(2.0);
int iterCount = 0;
while ( z_r.doubleValue()*z_r.doubleValue() + z_i.doubleValue()*z_i.doubleValue() <= 4.0 ) {
z_r_tmp = z_r;
z_r = z_r.multiply(z_r).subtract(z_i.multiply(z_r)).add(c_r);
z_i = z_i.multiply(dummy2).multiply(z_i).multiply(z_r_tmp).add(c_i);
if (iterCount >= MAX_ITER) return MAX_ITER;
iterCount++;
}
return iterCount;
} // computeIterations
// -------------------------------------------------------------------
private void moveUp() {
double curHeight = HEIGHT / zoomFactor;
topLeftY = topLeftY.add(new BigDecimal(curHeight / 6));
updateFractal();
} // moveUp
// -------------------------------------------------------------------
private void moveDown() {
double curHeight = HEIGHT / zoomFactor;
topLeftY = topLeftY.subtract(new BigDecimal(curHeight / 6));
updateFractal();
} // moveDown
// -------------------------------------------------------------------
private void moveLeft() {
double curWidth = WIDTH / zoomFactor;
topLeftX = topLeftX.subtract(new BigDecimal(curWidth / 6));
updateFractal();
} // moveLeft
// -------------------------------------------------------------------
private void moveRight() {
double curWidth = WIDTH / zoomFactor;
topLeftX = topLeftX.add(new BigDecimal(curWidth / 6));;
updateFractal();
} // moveRight
// -------------------------------------------------------------------
private void adjustZoom( double newX, double newY, double newZoomFactor ) {
topLeftX = topLeftX.add(new BigDecimal(newX/zoomFactor));
topLeftY = topLeftY.subtract(new BigDecimal(newX/zoomFactor));
zoomFactor = newZoomFactor;
topLeftX = topLeftX.subtract(new BigDecimal(( WIDTH/2) / zoomFactor));
topLeftY = topLeftY.add(new BigDecimal( (HEIGHT/2) / zoomFactor));
updateFractal();
} // adjustZoom
// -------------------------------------------------------------------
private class Canvas extends JPanel implements MouseListener {
public Canvas() {
addMouseListener(this);
}
#Override public Dimension getPreferredSize() {
return new Dimension(WIDTH, HEIGHT);
} // getPreferredSize
#Override public void paintComponent(Graphics drawingObj) {
drawingObj.drawImage( fractalImage, 0, 0, null );
} // paintComponent
#Override public void mousePressed(MouseEvent mouse) {
double x = (double) mouse.getX();
double y = (double) mouse.getY();
switch( mouse.getButton() ) {
//Links
case MouseEvent.BUTTON1:
adjustZoom( x, y, zoomFactor*10 );
break;
// Rechts
case MouseEvent.BUTTON3:
adjustZoom( x, y, zoomFactor/2 );
break;
}
} // mousePressed
public void addKeyStrokeEvents() {
KeyStroke wKey = KeyStroke.getKeyStroke(KeyEvent.VK_W, 0 );
KeyStroke aKey = KeyStroke.getKeyStroke(KeyEvent.VK_A, 0 );
KeyStroke sKey = KeyStroke.getKeyStroke(KeyEvent.VK_S, 0 );
KeyStroke dKey = KeyStroke.getKeyStroke(KeyEvent.VK_D, 0 );
Action wPressed = new AbstractAction() {
#Override public void actionPerformed(ActionEvent e) {
moveUp();
}
};
Action aPressed = new AbstractAction() {
#Override public void actionPerformed(ActionEvent e) {
moveLeft();
}
};
Action sPressed = new AbstractAction() {
#Override public void actionPerformed(ActionEvent e) {
moveDown();
}
};
Action dPressed = new AbstractAction() {
#Override public void actionPerformed(ActionEvent e) {
moveRight();
}
};
this.getInputMap().put( wKey, "w_key" );
this.getInputMap().put( aKey, "a_key" );
this.getInputMap().put( sKey, "s_key" );
this.getInputMap().put( dKey, "d_key" );
this.getActionMap().put( "w_key", wPressed );
this.getActionMap().put( "a_key", aPressed );
this.getActionMap().put( "s_key", sPressed );
this.getActionMap().put( "d_key", dPressed );
} // addKeyStrokeEvents
#Override public void mouseReleased(MouseEvent mouse){ }
#Override public void mouseClicked(MouseEvent mouse) { }
#Override public void mouseEntered(MouseEvent mouse) { }
#Override public void mouseExited (MouseEvent mouse) { }
} // Canvas
} // FractalExplorer
I updated the code to use BigDecimals, and tried using less heapspace, because i got a few errors because of it, but know the for loop with x which picks a color just stops when the value of x equals 256-258, and if i change the width/height, then the program stops at around half of the width+an eight of the width.
I did more testing, and it stops at computIterations(...);, i don't know why, but i hope this helps. It seems like it doesn't stop but rather slow down after a certain amount of times.
I finnaly solved it. The code:
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.math.BigDecimal;
public class FractalExplorer2 extends JFrame {
static final int WIDTH = 400;
static final int HEIGHT = WIDTH;
Canvas canvas;
BufferedImage fractalImage;
static final int MAX_ITER = 1000;
static final BigDecimal DEFAULT_TOP_LEFT_X = new BigDecimal(-2.0);
static final BigDecimal DEFAULT_TOP_LEFT_Y = new BigDecimal(1.4);
static final double DEFAULT_ZOOM = Math.round((double) (WIDTH/3));
static final int SCALE = 20;
static final int ROUND = BigDecimal.ROUND_CEILING;
final int numThreads = 10;
double zoomFactor = DEFAULT_ZOOM;
BigDecimal topLeftX = DEFAULT_TOP_LEFT_X;
BigDecimal topLeftY = DEFAULT_TOP_LEFT_Y;
// -------------------------------------------------------------------
public FractalExplorer2() {
long a = System.nanoTime();
setup();
addCanvas();
canvas.addKeyStrokeEvents();
updateFractal();
this.setVisible(true);
long b = System.nanoTime();
System.out.println((b-a));
}
// -------------------------------------------------------------------
public static void main(String[] args) {
new FractalExplorer2();
}
// -------------------------------------------------------------------
private void addCanvas() {
canvas = new Canvas();
fractalImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
canvas.setVisible(true);
this.add(canvas, BorderLayout.CENTER);
} // addCanvas
// -------------------------------------------------------------------
private void setup() {
this.setTitle("Fractal Explorer");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(WIDTH, HEIGHT);
this.setResizable(false);
this.setLocationRelativeTo(null);
} // setInitialGUIProperties
// -------------------------------------------------------------------
private BigDecimal getXPos(double x) {
return topLeftX.add(new BigDecimal(x/zoomFactor));
} // getXPos
// -------------------------------------------------------------------
private BigDecimal getYPos(double y) {
return topLeftY.subtract(new BigDecimal(y/zoomFactor));
} // getYPos
// -------------------------------------------------------------------
/**
* Aktualisiert das Fraktal, indem die Anzahl der Iterationen für jeden Punkt im Fraktal berechnet wird und die Farbe basierend darauf geändert wird.
**/
public void updateFractal() {
Thread[] threads = new Thread[numThreads];
int rowsPerThread = HEIGHT / numThreads;
// Construct each thread
for (int i=0; i<numThreads; i++) {
threads[i] = new Thread(new FractalThread(i * rowsPerThread, (i+1) * rowsPerThread));
}
// Starte jeden thread
for (int i=0; i<numThreads; i++) {
threads[i].start();
}
// Warten bis alle threads fertig sind
for (int i=0; i<numThreads; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
canvas.repaint();
} // updateFractal
// -------------------------------------------------------------------
//Gibt basierend auf der Iterationsanzahl eine trennungsfarbe zurück eines gegebenen Punktes im Fraktal
private class FractalThread implements Runnable {
int startY;
int endY;
public FractalThread(int startY, int endY) {
this.startY = startY;
this.endY = endY;
}
public void run() {
BigDecimal c_r;
BigDecimal c_i;
for (int x = 0; x < WIDTH; x++ ) {
for (int y = startY; y < endY; y++ ) {
c_r = getXPos(x);
c_i = getYPos(y);
int iterCount = computeIterations(c_r, c_i);
int pixelColor = makeColor(iterCount);
fractalImage.setRGB(x, y, pixelColor);
}
}
} // run
} // FractalThread
private int makeColor( int iterCount ) {
int color = 0b011011100001100101101000;
int mask = 0b000000000000010101110111;
int shiftMag = iterCount / 13;
if (iterCount == MAX_ITER)
return Color.BLACK.getRGB();
return color | (mask << shiftMag);
} // makeColor
// -------------------------------------------------------------------
private int computeIterations(BigDecimal c_r, BigDecimal c_i) {
BigDecimal z_r = new BigDecimal(0.0).setScale(SCALE,ROUND);
BigDecimal z_i = new BigDecimal(0.0).setScale(SCALE,ROUND);
BigDecimal z_r_tmp;
BigDecimal dummy2 = new BigDecimal(2.0).setScale(SCALE,ROUND);
BigDecimal dummy4 = new BigDecimal(4.0).setScale(SCALE,ROUND);
int iterCount = 0;
while (z_r.multiply(z_r).add((z_i.multiply(z_i))).compareTo(dummy4) != 1) {
z_r_tmp = z_r.setScale(SCALE,ROUND);
z_r = z_r.multiply(z_r).subtract(z_i.multiply(z_i)).add(c_r).setScale(SCALE,ROUND);
z_i = dummy2.multiply(z_i).multiply(z_r_tmp).add(c_i).setScale(SCALE,ROUND);
if (iterCount >= MAX_ITER) return MAX_ITER;
iterCount++;
}
return iterCount;
} // computeIterations
// -------------------------------------------------------------------
private void moveUp() {
double curHeight = HEIGHT / zoomFactor;
topLeftY = topLeftY.add(new BigDecimal(curHeight / 6));
updateFractal();
} // moveUp
// -------------------------------------------------------------------
private void moveDown() {
double curHeight = HEIGHT / zoomFactor;
topLeftY = topLeftY.subtract(new BigDecimal(curHeight / 6));
updateFractal();
} // moveDown
// -------------------------------------------------------------------
private void moveLeft() {
double curWidth = WIDTH / zoomFactor;
topLeftX = topLeftX.subtract(new BigDecimal(curWidth / 6));
updateFractal();
} // moveLeft
// -------------------------------------------------------------------
private void moveRight() {
double curWidth = WIDTH / zoomFactor;
topLeftX = topLeftX.add(new BigDecimal(curWidth / 6));
updateFractal();
} // moveRight
// -------------------------------------------------------------------
private void adjustZoom( double newX, double newY, double newZoomFactor ) {
topLeftX = topLeftX.add(new BigDecimal(newX/zoomFactor)).setScale(SCALE,ROUND);
topLeftY = topLeftY.subtract(new BigDecimal(newY/zoomFactor)).setScale(SCALE,ROUND);
zoomFactor = newZoomFactor;
topLeftX = topLeftX.subtract(new BigDecimal(( WIDTH/2) / zoomFactor)).setScale(SCALE,ROUND);
topLeftY = topLeftY.add(new BigDecimal( (HEIGHT/2) / zoomFactor)).setScale(SCALE,ROUND);
updateFractal();
} // adjustZoom
// -------------------------------------------------------------------
private class Canvas extends JPanel implements MouseListener {
public Canvas() {
addMouseListener(this);
}
#Override public Dimension getPreferredSize() {
return new Dimension(WIDTH, HEIGHT);
} // getPreferredSize
#Override public void paintComponent(Graphics drawingObj) {
drawingObj.drawImage( fractalImage, 0, 0, null );
} // paintComponent
#Override public void mousePressed(MouseEvent mouse) {
double x = (double) mouse.getX();
double y = (double) mouse.getY();
switch( mouse.getButton() ) {
//Links
case MouseEvent.BUTTON1:
adjustZoom( x, y, zoomFactor*5 );
break;
// Rechts
case MouseEvent.BUTTON3:
adjustZoom( x, y, zoomFactor/2 );
break;
}
} // mousePressed
public void addKeyStrokeEvents() {
KeyStroke wKey = KeyStroke.getKeyStroke(KeyEvent.VK_W, 0 );
KeyStroke aKey = KeyStroke.getKeyStroke(KeyEvent.VK_A, 0 );
KeyStroke sKey = KeyStroke.getKeyStroke(KeyEvent.VK_S, 0 );
KeyStroke dKey = KeyStroke.getKeyStroke(KeyEvent.VK_D, 0 );
Action wPressed = new AbstractAction() {
#Override public void actionPerformed(ActionEvent e) {
moveUp();
}
};
Action aPressed = new AbstractAction() {
#Override public void actionPerformed(ActionEvent e) {
moveLeft();
}
};
Action sPressed = new AbstractAction() {
#Override public void actionPerformed(ActionEvent e) {
moveDown();
}
};
Action dPressed = new AbstractAction() {
#Override public void actionPerformed(ActionEvent e) {
moveRight();
}
};
this.getInputMap().put( wKey, "w_key" );
this.getInputMap().put( aKey, "a_key" );
this.getInputMap().put( sKey, "s_key" );
this.getInputMap().put( dKey, "d_key" );
this.getActionMap().put( "w_key", wPressed );
this.getActionMap().put( "a_key", aPressed );
this.getActionMap().put( "s_key", sPressed );
this.getActionMap().put( "d_key", dPressed );
} // addKeyStrokeEvents
#Override public void mouseReleased(MouseEvent mouse){ }
#Override public void mouseClicked(MouseEvent mouse) { }
#Override public void mouseEntered(MouseEvent mouse) { }
#Override public void mouseExited (MouseEvent mouse) { }
} // Canvas
} // FractalExplorer
I just replaced the double variables with BigDecimal and set a Scale, so that the calculation doesn't take too long. I think the code can still be improved, but this is my code right now.

How do I make the enemies of my game follow my character?

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

How can I center a JavaFX MeshView in a scene dynamically?

I'm writing a javafx image generator for .STL files. I'm using StlMeshImporter to import the STL file. However, when I import files in my javafx scene and try to take a snapshot, I get different result for each file because they are not center in the scene.
I would like to be able to scale it or center it, in the scene dynamically to take a snapshot. Is there a way to get the width and height of the object so I could set a scale factor, and offset automatically?
Here is my class:
public class STLImageGenerator extends Application {
private static final String MESH_FILENAME
= "./9sk02_flex_r02.stl";
private static final int VIEWPORT_SIZE = 800;
private static final double MODEL_SCALE_FACTOR = 3;
private static final double MODEL_X_OFFSET = 0;
private static final double MODEL_Y_OFFSET = 0;
private static final double MODEL_Z_OFFSET =0 ;
// private static final int VIEWPORT_SIZE = 4096;
private static final Color lightColor = Color.rgb(204, 204, 204);
private static final Color jewelColor = Color.rgb(0, 100, 204);
final static int CANVAS_WIDTH = 512;
final static int CANVAS_HEIGHT = 512;
private Group root;
private PointLight pointLight;
Canvas canvas = null;
PerspectiveCamera perspectiveCamera = null;
static MeshView[] loadMeshViews() {
File file = new File(MESH_FILENAME);
StlMeshImporter importer = new StlMeshImporter();
importer.read(file);
Mesh mesh = importer.getImport();
return new MeshView[]{new MeshView(mesh)};
}
private Group buildScene() {
MeshView[] meshViews = loadMeshViews();
System.out.println("MESHVIEWS: " + meshViews.length);
for (int i = 0; i < meshViews.length; i++) {
System.out.println("meshViews[i].getLayoutX():"+meshViews[i].getLayoutX());
meshViews[i].setScaleX(MODEL_SCALE_FACTOR);
meshViews[i].setScaleY(MODEL_SCALE_FACTOR);
meshViews[i].setScaleZ(MODEL_SCALE_FACTOR);
meshViews[i].setTranslateX((VIEWPORT_SIZE / 2) + MODEL_X_OFFSET-MODEL_SCALE_FACTOR);
meshViews[i].setTranslateY((VIEWPORT_SIZE / 2) + MODEL_Y_OFFSET-MODEL_SCALE_FACTOR);
meshViews[i].setTranslateZ((VIEWPORT_SIZE / 2) + MODEL_Z_OFFSET);
PhongMaterial sample = new PhongMaterial(jewelColor);
sample.setSpecularColor(lightColor);
sample.setSpecularPower(16);
meshViews[i].setMaterial(sample);
//meshViews[i].getTransforms().setAll(new Rotate(38, Rotate.Z_AXIS), new Rotate(20, Rotate.X_AXIS));
}
pointLight = new PointLight(lightColor);
pointLight.setTranslateX(VIEWPORT_SIZE * 3 / 4);
pointLight.setTranslateY(VIEWPORT_SIZE / 2);
pointLight.setTranslateZ(VIEWPORT_SIZE / 2);
PointLight pointLight2 = new PointLight(lightColor);
pointLight2.setTranslateX(VIEWPORT_SIZE * 1 / 4);
pointLight2.setTranslateY(VIEWPORT_SIZE * 3 / 4);
pointLight2.setTranslateZ(VIEWPORT_SIZE * 3 / 4);
PointLight pointLight3 = new PointLight(lightColor);
pointLight3.setTranslateX(VIEWPORT_SIZE * 5 / 8);
pointLight3.setTranslateY(VIEWPORT_SIZE / 2);
pointLight3.setTranslateZ(0);
Color ambientColor = Color.rgb(80, 80, 80, 0);
AmbientLight ambient = new AmbientLight(ambientColor);
root = new Group(meshViews);
root.getChildren().add(pointLight);
root.getChildren().add(pointLight2);
root.getChildren().add(pointLight3);
root.getChildren().add(ambient);
//root.setAutoSizeChildren(true);
return root;
}
private PerspectiveCamera addCamera(Scene scene) {
perspectiveCamera = new PerspectiveCamera();
System.out.println("Near Clip: " + perspectiveCamera.getNearClip());
System.out.println("Far Clip: " + perspectiveCamera.getFarClip());
System.out.println("FOV: " + perspectiveCamera.getFieldOfView());
perspectiveCamera.setFieldOfView(5);
scene.setCamera(perspectiveCamera);
return perspectiveCamera;
}
#Override
public void start(Stage primaryStage) {
//canvas = new Canvas(VIEWPORT_SIZE, VIEWPORT_SIZE);
Group group = buildScene();
Scene scene = new Scene(group, VIEWPORT_SIZE, VIEWPORT_SIZE, true, SceneAntialiasing.BALANCED);
scene.setFill(Color.rgb(255, 255, 255));
group.setAutoSizeChildren(true);
addCamera(scene);
//root.getChildren().add(canvas);
primaryStage.setMaxHeight(CANVAS_HEIGHT);
primaryStage.setMaxWidth(CANVAS_WIDTH);
String fname = MESH_FILENAME.substring(0, MESH_FILENAME.length() - 3) + "png";
File file = new File(fname);
primaryStage.setTitle("Jewel Viewer");
primaryStage.setScene(scene);
primaryStage.show();
try {
SnapshotParameters s = new SnapshotParameters();
// s.setCamera(perspectiveCamera);
// s.setViewport(Rectangle2D.EMPTY);
WritableImage wim = new WritableImage(1024, 1024);
scene.snapshot(wim);
// WritableImage writableImage = root.snapshot(new SnapshotParameters(), null);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(wim, null);
ImageIO.write(renderedImage, "png", file);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.setProperty("prism.dirtyopts", "false");
Platform.setImplicitExit(false);
launch(args);
}

Java Swing - Display img in frame

I want to draw images but I want to show it in a frame when all the img will be draw. My current code:
public class TestURLImage3 extends JFrame {
private static ArrayList<BusStop2> list = new ArrayList<>();
private static ArrayList<PositionTilesAndURLPaths> positionTilesAndURLPathsList = new ArrayList<>();
private static ArrayList<Image> imgList = new ArrayList<>();
private static ConcurrentHashMap<String, BufferedImage> imgCache = new ConcurrentHashMap<>();
public static void main(String[] args) {
new TestURLImage3();
}
TestURLImage3(){
setUndecorated(false);
setAlwaysOnTop(true);
setSize(Config.xSize, Config.ySize);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getTiles(51.407,16.198);
getImgPositionAndURLsPath(list);
setVisible(true);
setLayout(null);
}
public void paint ( Graphics g ) {
super.paint(g);
getPaint(g);
}
private static void getPaint(Graphics g){
for(PositionTilesAndURLPaths pos : getImgPositionAndURLsPath(list)){
ImageIcon icon = new ImageIcon(getImgFromPath(pos.getPath()));
Image img = icon.getImage();
g.drawImage(img,Config.xSize/2-pos.getX()-Config.imgSize/2 ,(Config.ySize/2)- pos.getY()-Config.imgSize/2, Config.imgSize, Config.imgSize, null);
}
}
/**
* Method use to get image by geographical coordinates
* #param lat
* #param lon
* #return
*/
// private String getFirstImage(double lat, double lon ){
// return new String(TestURLImage.getImg(lat, lon, Config.mapZoom));
// }
/**
* Method use to get image from path
* #param path
* #return
*/
private static BufferedImage getImgFromPath(String path){
if(imgCache.get(path) != null){
return imgCache.get(path);
}
else{
URL url = null;
BufferedImage image = null;
try {
url = new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
image = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
imgCache.put(path, image);
return image;
}
}
/**
* 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
*/
private static int[] countImage(){
int[] imageCount = getCountImage();
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 = TestURLImage.getMapByGeographicalCoordinates(lat, lon, Config.mapZoom);
int a1 = 1;
int a2 = 1;
int a3 = 1;
int a4 = 1;
int [] countImage = countImage();
int []x = new int [countImage[0]];
int []y = new int [countImage[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;
}
}
I see how one img will be add and another ...
So I do it this :
public class TestURLImage2 {
int result[];
private static ArrayList<BusStop2> list = new ArrayList<>();
private static ArrayList<PositionTilesAndURLPaths> positionTilesAndURLPathsList = new ArrayList<>();
private static ConcurrentHashMap<String, BufferedImage> imgCache = new ConcurrentHashMap<>();
public static void main(String[] args) {
new TestURLImage2();
getTiles(51.407,16.198);
getImgPositionAndURLsPath(list);
}
public TestURLImage2() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
try {
JFrame f = new JFrame();
f.setSize(Config.xSize, Config.ySize);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setAlwaysOnTop(true);
f.setSize(Config.xSize, Config.ySize);
f.setVisible(true);
f.setLayout(null);
getTiles(51.407,16.198);
for(PositionTilesAndURLPaths pos : getImgPositionAndURLsPath(list)){
JLabel label = new JLabel(new ImageIcon(getImgFromPath(pos.getPath())));
label.setBounds(Config.xSize/2-pos.getX()-Config.imgSize/2 ,(Config.ySize/2)- pos.getY()-Config.imgSize/2, Config.imgSize, Config.imgSize);
f.getContentPane().add(label);
}
System.out.println(imgCache.size());
} catch (Exception exp) {
exp.printStackTrace();
}
}
});
}
/**
* Method use to get image from path
* #param path
* #return
*/
private BufferedImage getImgFromPath(String path){
if(imgCache.get(path) != null){
return imgCache.get(path);
}
else{
URL url = null;
BufferedImage image = null;
try {
url = new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
image = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
imgCache.put(path, image);
return image;
}
}
/**
* 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
*/
private static int[] countImage(){
int[] imageCount = getCountImage();
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 = TestURLImage.getMapByGeographicalCoordinates(lat, lon, Config.mapZoom);
int a1 = 1;
int a2 = 1;
int a3 = 1;
int a4 = 1;
int [] countImage = countImage();
int []x = new int [countImage[0]];
int []y = new int [countImage[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){enter code here
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;
}
}
But I have to wait 10 seconds for the screen and it is too long. How could I speed up the process?

JavaFX: scrollview swipe effect

I would like to know, how to make scrollview swipe effect when mouse is dragged up and down. I'm developing JavaFX application which has ListView & I need to scroll the list when user drags the mouse up and down (like iOS contact list).
Also how to add the user's dragging velocity and speed to the scrolling value?
UPDATED : I got some code here but It doesn't work properly...
import java.util.ArrayList;
import java.util.Arrays;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.animation.TimelineBuilder;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.Event;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.FlowPane;
import javafx.util.Duration;
public class Swipe extends ScrollPane {
private static final int INERTIA_DURATION = 2400;
private static final double CLICK_THRESHOLD = 20;
private static final double CLICK_TIME_THRESHOLD = Integer.parseInt(System.getProperty("click", "400"));
private final double width;
private final double height;
private long startDrag;
private long lastDrag;
private long lastDragDelta;
private int startDragX;
private int startDragY;
private int lastDragX;
private int lastDragY;
private int lastDragStepX;
private int lastDragStepY;
private double dragVelocityX;
private double dragVelocityY;
private boolean clickThresholdBroken;
private Timeline inertiaTimeline = null;
private long lastClickTime = -1;
private final boolean isFiredByMe = false;
public Swipe(double width, double height) {
this.width = width;
this.height = height;
init();
}
private void init() {
setPrefSize(width, height);
setPannable(true);
setHbarPolicy(ScrollBarPolicy.NEVER);
setVbarPolicy(ScrollBarPolicy.NEVER);
setEventHandlers();
ContentPane cp = new ContentPane();
setContent(cp);
}
private void setEventHandlers() {
setOnMousePressed((MouseEvent event) -> {
lastDragX = startDragX = (int) event.getX();
lastDragY = startDragY = (int) event.getY();
lastDrag = startDrag = System.currentTimeMillis();
lastDragDelta = 0;
if (inertiaTimeline != null) {
inertiaTimeline.stop();
}
clickThresholdBroken = false;
});
setOnDragDetected((MouseEvent event) -> {
// Delta of this drag vs. last drag location (or start)
lastDragStepX = (int) event.getX() - lastDragX;
lastDragStepY = (int) event.getY() - lastDragY;
// Duration of this drag step.
lastDragDelta = System.currentTimeMillis() - lastDrag;
// Velocity of last drag increment.
dragVelocityX = (double) lastDragStepX / (double) lastDragDelta;
dragVelocityY = (double) lastDragStepY / (double) lastDragDelta;
// Snapshot of this drag event.
lastDragX = (int) event.getX();
lastDragY = (int) event.getY();
lastDrag = System.currentTimeMillis();
// Calculate distance so far -- have we dragged enough to scroll?
final int dragX = (int) event.getX() - startDragX;
final int dragY = (int) event.getY() - startDragY;
double distance = Math.abs(Math.sqrt((dragX * dragX) + (dragY * dragY)));
int scrollDistX = lastDragStepX;
int scrollDistY = lastDragStepY;
if (!clickThresholdBroken && distance > CLICK_THRESHOLD) {
clickThresholdBroken = true;
scrollDistX = dragX;
scrollDistY = dragY;
}
if (clickThresholdBroken) {
Event.fireEvent(event.getTarget(), new ScrollEvent(
ScrollEvent.SCROLL,
scrollDistX, scrollDistY,
scrollDistX, scrollDistY,
event.isShiftDown(), event.isControlDown(), event.isAltDown(), event.isMetaDown(),
true, false,
event.getX(), event.getY(),
event.getSceneX(), event.getSceneY(),
ScrollEvent.HorizontalTextScrollUnits.NONE, 0,
ScrollEvent.VerticalTextScrollUnits.NONE, 0, 0, null));
}
});
setOnMouseReleased((MouseEvent event) -> {
handleRelease(event);
});
setOnMouseClicked((MouseEvent event) -> {
final long time = System.currentTimeMillis();
if (clickThresholdBroken || (lastClickTime != -1 && (time - lastClickTime) < CLICK_TIME_THRESHOLD)) {
event.consume();
}
lastClickTime = time;
});
}
private void handleRelease(final MouseEvent me) {
if (clickThresholdBroken) {
// Calculate last instantaneous velocity. User may have stopped moving
// before they let go of the mouse.
final long time = System.currentTimeMillis() - lastDrag;
dragVelocityX = (double) lastDragStepX / (time + lastDragDelta);
dragVelocityY = (double) lastDragStepY / (time + lastDragDelta);
// determin if click or drag/flick
final int dragX = (int) me.getX() - startDragX;
final int dragY = (int) me.getY() - startDragY;
// calculate complete time from start to end of drag
final long totalTime = System.currentTimeMillis() - startDrag;
// if time is less than 300ms then considered a quick flick and whole time is used
final boolean quick = totalTime < 300;
// calculate velocity
double velocityX = quick ? (double) dragX / (double) totalTime : dragVelocityX; // pixels/ms
double velocityY = quick ? (double) dragY / (double) totalTime : dragVelocityY; // pixels/ms
final int distanceX = (int) (velocityX * INERTIA_DURATION); // distance
final int distanceY = (int) (velocityY * INERTIA_DURATION); // distance
//
DoubleProperty animatePosition = new SimpleDoubleProperty() {
double lastMouseX = me.getX();
double lastMouseY = me.getY();
#Override
protected void invalidated() {
final double mouseX = me.getX() + (distanceX * get());
final double mouseY = me.getY() + (distanceY * get());
final double dragStepX = mouseX - lastMouseX;
final double dragStepY = mouseY - lastMouseY;
if (Math.abs(dragStepX) >= 1.0 || Math.abs(dragStepY) >= 1.0) {
Event.fireEvent(me.getTarget(), new ScrollEvent(
ScrollEvent.SCROLL,
dragStepX, dragStepY,
(distanceX * get()), (distanceY * get()),
me.isShiftDown(), me.isControlDown(), me.isAltDown(), me.isMetaDown(),
true, true,
me.getX(), me.getY(),
me.getSceneX(), me.getSceneY(),
ScrollEvent.HorizontalTextScrollUnits.NONE, 0,
ScrollEvent.VerticalTextScrollUnits.NONE, 0,
0, null));
}
lastMouseX = mouseX;
lastMouseY = mouseY;
}
};
// animate a slow down from current velocity to zero
inertiaTimeline = TimelineBuilder.create()
.keyFrames(
new KeyFrame(Duration.ZERO, new KeyValue(animatePosition, 0)),
new KeyFrame(Duration.millis(INERTIA_DURATION), new KeyValue(animatePosition, 1d, Interpolator.SPLINE(0.0513, 0.1131, 0.1368, 1.0000)))
).build();
inertiaTimeline.play();
}
}
private class ContentPane extends FlowPane {
private ArrayList getList() {
String[] list = {
"Kerrie Batts", "Raina Huffstutler", "Kip Kukowski", "Trish Sullivan", "Kyla Hollingsworth", "Gearldine Leavy", "Major Langdon", "Avery Rusin", "Hedy Messina", "Audry Felps", "Tianna Robbins", "Marian Tranmer", "Lashaunda Bivona", "Leighann Schwab", "Emanuel Volpe", "Neida Geist", "Edda Placencia", "Olevia Hippe", "Fernando Cohen", "Danette Dorsett"};
ArrayList<String> nameList = new ArrayList();
nameList.addAll(Arrays.asList(list));
return nameList;
}
public ContentPane() {
setPrefSize(215, 271);
ArrayList<String> nameList = getList();
Element[] element = new Element[nameList.size()];
for (int i = 0; i < nameList.size(); i++) {
String name = nameList.get(i);
Element el = element[i] = new Element(210, 25, name);
getChildren().add(el);
}
}
}
private class Element extends AnchorPane {
private double width;
private double height;
private String name;
public Element(double width, double height, String name) {
this.width = width;
this.height = height;
this.name = name;
init();
}
private Label createName() {
Label label = new Label(name);
label.setPrefSize(width, height);
label.setAlignment(Pos.CENTER_LEFT);
AnchorPane.setLeftAnchor(label, 5.0);
label.setStyle("-fx-font-family: Calibri; -fx-font-size: 14;");
return label;
}
private void init() {
setPrefSize(width, height);
getChildren().add(createName());
}
public void setPrefSize(double width, double height) {
this.width = width;
this.height = height;
}
public void setName(String name) {
this.name = name;
}
}
}
I figured out myself. There is two classes. 1st one is for calculate the velocity of the movement.
VelocityTracker.java
import javafx.scene.input.MouseEvent;
public final class VelocityTracker {
private static final boolean DEBUG = false;
private static final boolean localLOGV = DEBUG;
private static final int NUM_PAST = 10;
private static final int MAX_AGE_MILLISECONDS = 200;
private static final int POINTER_POOL_CAPACITY = 20;
private static Pointer sRecycledPointerListHead;
private static int sRecycledPointerCount;
private static final class Pointer {
public Pointer next;
public int id;
public float xVelocity;
public float yVelocity;
public final float[] pastX = new float[NUM_PAST];
public final float[] pastY = new float[NUM_PAST];
public final long[] pastTime = new long[NUM_PAST]; // uses Long.MIN_VALUE as a sentinel
}
private Pointer mPointerListHead; // sorted by id in increasing order
private int mLastTouchIndex;
public VelocityTracker() {
clear();
}
public void clear() {
releasePointerList(mPointerListHead);
mPointerListHead = null;
mLastTouchIndex = 0;
}
public void addMovement(MouseEvent ev) {
final int historySize = 0;
final int lastTouchIndex = mLastTouchIndex;
final int nextTouchIndex = (lastTouchIndex + 1) % NUM_PAST;
final int finalTouchIndex = (nextTouchIndex + historySize) % NUM_PAST;
mLastTouchIndex = finalTouchIndex;
if (mPointerListHead == null) {
mPointerListHead = obtainPointer();
}
final float[] pastX = mPointerListHead.pastX;
final float[] pastY = mPointerListHead.pastY;
final long[] pastTime = mPointerListHead.pastTime;
pastX[finalTouchIndex] = (float) ev.getX();
pastY[finalTouchIndex] = (float) ev.getY();
pastTime[finalTouchIndex] = System.currentTimeMillis();
}
public void computeCurrentVelocity(int units) {
computeCurrentVelocity(units, Float.MAX_VALUE);
}
public void computeCurrentVelocity(int units, float maxVelocity) {
final int lastTouchIndex = mLastTouchIndex;
for (Pointer pointer = mPointerListHead; pointer != null; pointer = pointer.next) {
final long[] pastTime = pointer.pastTime;
int oldestTouchIndex = lastTouchIndex;
int numTouches = 1;
final long minTime = pastTime[lastTouchIndex] - MAX_AGE_MILLISECONDS;
while (numTouches < NUM_PAST) {
final int nextOldestTouchIndex = (oldestTouchIndex + NUM_PAST - 1) % NUM_PAST;
final long nextOldestTime = pastTime[nextOldestTouchIndex];
if (nextOldestTime < minTime) { // also handles end of trace sentinel
break;
}
oldestTouchIndex = nextOldestTouchIndex;
numTouches += 1;
}
if (numTouches > 3) {
numTouches -= 1;
}
final float[] pastX = pointer.pastX;
final float[] pastY = pointer.pastY;
final float oldestX = pastX[oldestTouchIndex];
final float oldestY = pastY[oldestTouchIndex];
final long oldestTime = pastTime[oldestTouchIndex];
float accumX = 0;
float accumY = 0;
for (int i = 1; i < numTouches; i++) {
final int touchIndex = (oldestTouchIndex + i) % NUM_PAST;
final int duration = (int) (pastTime[touchIndex] - oldestTime);
if (duration == 0) {
continue;
}
float delta = pastX[touchIndex] - oldestX;
float velocity = (delta / duration) * units; // pixels/frame.
accumX = (accumX == 0) ? velocity : (accumX + velocity) * .5f;
delta = pastY[touchIndex] - oldestY;
velocity = (delta / duration) * units; // pixels/frame.
accumY = (accumY == 0) ? velocity : (accumY + velocity) * .5f;
}
if (accumX < -maxVelocity) {
accumX = -maxVelocity;
} else if (accumX > maxVelocity) {
accumX = maxVelocity;
}
if (accumY < -maxVelocity) {
accumY = -maxVelocity;
} else if (accumY > maxVelocity) {
accumY = maxVelocity;
}
pointer.xVelocity = accumX;
pointer.yVelocity = accumY;
}
}
public float getXVelocity() {
Pointer pointer = getPointer(0);
return pointer != null ? pointer.xVelocity : 0;
}
public float getYVelocity() {
Pointer pointer = getPointer(0);
return pointer != null ? pointer.yVelocity : 0;
}
public float getXVelocity(int id) {
Pointer pointer = getPointer(id);
return pointer != null ? pointer.xVelocity : 0;
}
public float getYVelocity(int id) {
Pointer pointer = getPointer(id);
return pointer != null ? pointer.yVelocity : 0;
}
private Pointer getPointer(int id) {
for (Pointer pointer = mPointerListHead; pointer != null; pointer = pointer.next) {
if (pointer.id == id) {
return pointer;
}
}
return null;
}
private static Pointer obtainPointer() {
if (sRecycledPointerCount != 0) {
Pointer element = sRecycledPointerListHead;
sRecycledPointerCount -= 1;
sRecycledPointerListHead = element.next;
element.next = null;
return element;
}
return new Pointer();
}
private static void releasePointer(Pointer pointer) {
if (sRecycledPointerCount < POINTER_POOL_CAPACITY) {
pointer.next = sRecycledPointerListHead;
sRecycledPointerCount += 1;
sRecycledPointerListHead = pointer;
}
}
private static void releasePointerList(Pointer pointer) {
if (pointer != null) {
int count = sRecycledPointerCount;
if (count >= POINTER_POOL_CAPACITY) {
return;
}
Pointer tail = pointer;
for (;;) {
count += 1;
if (count >= POINTER_POOL_CAPACITY) {
break;
}
Pointer next = tail.next;
if (next == null) {
break;
}
tail = next;
}
tail.next = sRecycledPointerListHead;
sRecycledPointerCount = count;
sRecycledPointerListHead = pointer;
}
}
}
And this is second class
import java.util.concurrent.atomic.AtomicReference;
import javafx.animation.FadeTransition;
import javafx.animation.Interpolator;
import javafx.animation.Timeline;
import javafx.animation.TranslateTransition;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Bounds;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;
public class VerticlePane extends Region {
private ObjectProperty<Node> content;
private final VelocityTracker tracker = new VelocityTracker();
private final Rectangle clipRect = new Rectangle();
private Rectangle scrollNode;
private boolean magnet, autoTranslate = true;
private DoubleProperty targetY = new SimpleDoubleProperty(), controlHeight = new SimpleDoubleProperty(), viewHeight = new SimpleDoubleProperty();
private double startValue, endValue;
private HBox indicator;
private StringProperty indicatorValue = new SimpleStringProperty("Pull Up to Update...");
public VerticlePane() {
setFocusTraversable(false);
setClip(clipRect);
contentProperty().addListener((ObservableValue<? extends Node> observable, Node oldValue, Node newValue) -> {
getChildren().clear();
if (newValue != null) {
getChildren().addAll(newValue, createRectangle());
}
layout();
});
final AtomicReference<MouseEvent> deltaEvent = new AtomicReference<>();
final AtomicReference<TranslateTransition> currentTransition1 = new AtomicReference<>();
final AtomicReference<TranslateTransition> currentTransition2 = new AtomicReference<>();
final AtomicReference<Timeline> timeline = new AtomicReference<>();
setOnMousePressed((me) -> {
tracker.addMovement(me);
deltaEvent.set(me);
startValue = me.getY();
if (currentTransition1.get() != null) {
currentTransition1.get().stop();
}
if (currentTransition2.get() != null) {
currentTransition2.get().stop();
}
if (timeline.get() != null) {
timeline.get().stop();
}
});
setOnMouseDragged((event) -> {
tracker.addMovement(event);
double delta = event.getY() - deltaEvent.get().getY();
targetY.set(content.get().getTranslateY() + delta);
content.get().setTranslateY(targetY.get());
controlHeight.set(content.get().getLayoutBounds().getHeight());
viewHeight.set(getHeight());
double scrollTargetY = targetY.divide(controlHeight.divide(viewHeight.get()).get()).get();
double lastInstanceHeight = controlHeight.subtract(viewHeight.get()).multiply(-1).get();
scrollNode.relocate(1.0, (getHeight() - 5.0));
scrollNode.setArcHeight(5.0);
scrollNode.setArcWidth(5.0);
scrollNode.setHeight(viewHeight.divide(controlHeight.divide(viewHeight.get()).get()).get());
scrollNode.setVisible(true);
scrollNode.setOpacity(0.25);
if (targetY.lessThan(0).and(targetY.greaterThan(lastInstanceHeight)).get()) {
scrollNode.setTranslateY(Math.abs(scrollTargetY));
} else if (targetY.greaterThanOrEqualTo(0).get()) {
scrollNode.setHeight(scrollNode.getHeight() - targetY.get());
}
if (targetY.get() < lastInstanceHeight) {
double scrollNodeHeight = scrollNode.getHeight() - (lastInstanceHeight - targetY.get());
double scrollNodeTranslateY = viewHeight.subtract(viewHeight.divide(controlHeight.divide(viewHeight.get()).get()).get()).add(lastInstanceHeight - targetY.get()).get();
scrollNode.setHeight(scrollNodeHeight);
scrollNode.setTranslateY(scrollNodeTranslateY);
}
deltaEvent.set(event);
});
setOnMouseReleased((me) -> {
FadeTransition ft = new FadeTransition(Duration.millis(300), scrollNode);
ft.setFromValue(0.25);
ft.setToValue(0.00);
tracker.addMovement(me);
tracker.computeCurrentVelocity(500);
endValue = me.getY();
controlHeight.set(content.get().getLayoutBounds().getHeight());
viewHeight.set(getHeight());
float velocityY = tracker.getYVelocity();
targetY.set(scrollNode(velocityY, currentTransition1, content.get()));
TranslateTransition tt = bb(currentTransition2, scrollNode, Math.abs((targetY.divide(controlHeight.divide(viewHeight.get()).get()).get())));
tt.setOnFinished((ae) -> {
ft.play();
});
});
}
public double getStartValue() {
return startValue;
}
public double getEndValue() {
return endValue;
}
public double getControlHeight() {
return controlHeight.get();
}
public double getViewHeight() {
return viewHeight.get();
}
public VerticlePane(double prefWidth, double prefHeight) {
this();
setPrefSize(prefWidth, prefHeight);
}
public VerticlePane(double prefWidth, double prefHeight, boolean magnet) {
this(prefWidth, prefHeight);
setMagnet(magnet);
}
public final void setMagnet(boolean magnet) {
this.magnet = magnet;
}
private TranslateTransition bb(AtomicReference<TranslateTransition> currentTransition, Node node, Double targetY) {
TranslateTransition translate = new TranslateTransition(new Duration(1000), node);
if (node != null) {
translate.setInterpolator(Interpolator.SPLINE(0.0513, 0.1131, 0.1368, 1.0000));
if (targetY != null) {
translate.setFromY(node.getTranslateY());
translate.setToY(targetY);
}
translate.play();
currentTransition.set(translate);
}
return translate;
}
private Double scrollNode(float velocityY, AtomicReference<TranslateTransition> currentTransition, Node node) {
final Bounds b = node.getLayoutBounds();
Double backBouncingY = null;
Double targetY = null;
if (node != null) {
TranslateTransition translate = new TranslateTransition(new Duration(1000), node);
translate.setInterpolator(Interpolator.SPLINE(0.0513, 0.1131, 0.1368, 1.0000));
if (Math.abs(velocityY) < 10) {
velocityY = 0;
}
targetY = node.getTranslateY();
double controlHeight = b.getHeight() - indicator.heightProperty().add(10).get();
double viewHeight = getHeight();
if (controlHeight < viewHeight && targetY < controlHeight) {
targetY = 0.0;
} else if (targetY > 0) {
targetY = 0.0;
} else if ((targetY < (controlHeight - viewHeight) * -1)) {
targetY = (controlHeight - viewHeight) * -1;
} else {
targetY += velocityY;
if (controlHeight < viewHeight && targetY < controlHeight) {
targetY = -25.0;
backBouncingY = 0.0;
} else if (targetY > 0) {
targetY = 25.0;
backBouncingY = 0.0;
} else if (targetY < (controlHeight - viewHeight) * -1) {
targetY = (controlHeight - viewHeight) * -1 - 25;
backBouncingY = (controlHeight - viewHeight) * -1;
}
}
//Magnet
if (magnet) {
double dragRegion = (viewHeight / 2) * -1;
double instances = controlHeight / viewHeight;
double lastInstance = ((controlHeight - viewHeight) * -1);
double newInstanceValue = dragRegion;
if (targetY > dragRegion) {
targetY = 0.0;
}
if (instances > 1) {
for (int i = 1; i < instances - 1; i++) {
double instanceValue = (viewHeight * i) * -1;
if (targetY < newInstanceValue && targetY > instanceValue || targetY < instanceValue && targetY > (instanceValue + dragRegion)) {
targetY = instanceValue;
}
newInstanceValue += (viewHeight * -1);
}
}
if (targetY < (lastInstance - dragRegion) && targetY > lastInstance) {
targetY = lastInstance;
}
}
//
if (targetY != null) {
translate.setFromY(node.getTranslateY());
translate.setToY(targetY);
}
if (backBouncingY != null) {
final Double fbackFlingY = backBouncingY;
translate.setOnFinished((ae) -> {
currentTransition.set(null);
TranslateTransition translate1 = new TranslateTransition(new Duration(300), node);
if (fbackFlingY != null) {
translate1.setFromY(node.getTranslateY());
translate1.setToY(fbackFlingY);
}
translate1.play();
currentTransition.set(translate1);
});
} else {
translate.setOnFinished((ae) -> {
currentTransition.set(null);
});
}
translate.play();
currentTransition.set(translate);
}
return targetY;
}
private Rectangle createRectangle() {
if (scrollNode == null) {
scrollNode = new Rectangle(4.0, 4.0, Color.BLACK);
}
scrollNode.setVisible(false);
return scrollNode;
}
public ObjectProperty<Node> contentProperty() {
if (content == null) {
content = new SimpleObjectProperty<>(this, "content");
}
return content;
}
public final void setContent(Node value) {
contentProperty().set(
new VBox(10) {
{
getChildren().addAll(value, indicator());
}
}
);
contentProperty().get().layoutBoundsProperty().addListener((ObservableValue<? extends Bounds> obs, Bounds ov, Bounds nv) -> {
Double containerHeight = nv.getHeight();
Double flingHeight = prefHeightProperty().get();
if (autoTranslate) {
if (flingHeight <= containerHeight) {
contentProperty().get().setTranslateY((containerHeight - flingHeight - 34) * -1);
}
}
});
}
private HBox indicator() {
return indicator = new HBox(10) {
{
setVisible(false);
setAlignment(Pos.CENTER);
getChildren().addAll(
new ImageView(new Image(getClass().getResourceAsStream("Indicator.gif"))),
new Label() {
{
textProperty().bind(indicatorValue);
setStyle("-fx-font-family: Roboto; -fx-font-size: 14px;");
}
}
);
}
};
}
public void setAutoTranslate(Boolean autoTranslate) {
this.autoTranslate = autoTranslate;
}
public void setTranslateZero() {
this.contentProperty().get().setTranslateY(0);
}
public HBox getIndicator() {
return indicator;
}
public void showIndicator() {
indicator.setVisible(true);
}
public void hideIndicator() {
indicator.setVisible(false);
}
public void setIndicatorValue(String value) {
indicatorValue.setValue(value);
}
public final Node getContent() {
return content == null ? null : content.get();
}
#Override
protected void layoutChildren() {
super.layoutChildren();
clipRect.setWidth(getWidth());
clipRect.setHeight(getHeight());
}
}
Scroll Bar disabled why?
It should not extend:
public class VerticlePane extends Control

Categories

Resources