Can't create animation in libgdx - animation

I'm trying to create animation but keep getting errors
package com.leopikinc.bobdestroyer;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
public class MainMenu implements Screen{
Texture background_main;
TextureRegion[] background_textures;
Animation background_animation;
SpriteBatch batch;
TextureRegion current_frame;
float stateTime;
BobDestroyer game;
public MainMenu(BobDestroyer game){
this.game = game;
}
#Override
public void show() {
background_main = new Texture(Gdx.files.internal("main_menu_screen/Background.png"));
//TextureRegion[][] temp = new TextureRegion.split(background_main, 128, 72);
//background_textures = new TextureRegion[3];
for(int i = 0; i<3; i++){
background_textures[i] = new TextureRegion(background_main,0, 0+72*i, 128, 72+72*i);
}
background_animation = new Animation(0.2f,background_textures);
}
#Override
public void render(float delta) {
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
stateTime += Gdx.graphics.getDeltaTime();
current_frame = background_animation.getKeyFrame(stateTime, true);
batch.begin();
batch.draw(current_frame, 0, 0);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
this is my code and then i try to launch it i get
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.leopikinc.bobdestroyer.MainMenu.show(MainMenu.java:31)
at com.badlogic.gdx.Game.setScreen(Game.java:61)
at com.leopikinc.bobdestroyer.BobDestroyer.create(BobDestroyer.java:11)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:143)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
How to fix this? And also when i use TextureRegion[][] temp = new TextureRegion.split(background_main, 128, 72);Eclipse says
TextureRegion.split cannot be resolved to a type

TextureRegion.split cannot be resolved to a type
You are getting an error because you are using keyword new
Do something like this and your error will be fixed
TextureRegion[][] tmp = TextureRegion.split(background_main, background_main.getWidth()/TOTAL_COLS, background_main.getHeight()/TOTAL_ROWS);
Your second error is because you have commented the line where you are initializing your array, you need to uncomment this
//background_textures = new TextureRegion[3];

Related

JavaFX resets my colors when adding buttons

I am using JavaFx to create a front-end to the cli application called spicetify. I am not using an fxml file for the layout instead I am using different classes for layout purposes.
One such class is the Sidebar class. In it I define how the sidebar should look and then create an object of it on the window/page that I need. Whenever I add buttons to the sidebar The colors of the window where the Sidebar object is created go blank/white.
I am unable to find anything by googling and hope that the information provided is enough.
Screenshot of the window without buttons
Screenshot of the window with buttons
Project Structure
Sidebar class:
package spicetify;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
public class Sidebar {
BaseWindow baseWindow = new BaseWindow();
private String[] buttonIconLocation = {
"file:src/main/resources/spicetify/images/buttons/home.png",
"file:src/main/resources/spicetify/images/buttons/theme.png",
"file:src/main/resources/spicetify/images/buttons/extension.png",
"file:src/main/resources/spicetify/images/buttons/edit.png",
};
private ImageView[] buttonIcon = new ImageView[4];
private VBox sidebar;
private Button[] buttons = new Button[4];
public Sidebar(int height, int width, String html, Parent root){
this.sidebar = new VBox();
this.sidebar.setPrefHeight(height);
this.sidebar.setPrefWidth(width);
this.sidebar.setStyle("-fx-background-color: " + html);
for (int i = 0; i < buttonIcon.length; i++){
buttonIcon[i] = new ImageView(buttonIconLocation[i]);
baseWindow.transform(buttonIcon[i], 50, 50, true);
}
for (int i = 0; i < buttons.length; i++){
buttons[i] = new Button("", buttonIcon[i]);
sidebar.getChildren().add(buttons[i]);
buttons[i].setTranslateX(20);
buttons[i].setTranslateY(i * 100);
buttons[i].setStyle("-fx-background-color: " + html);
}
}
public String[] getButtonIconLocation() {
return buttonIconLocation;
}
public void setButtonIconLocation(String[] buttonIconLocation) {
this.buttonIconLocation = buttonIconLocation;
}
public ImageView[] getButtonIcon() {
return buttonIcon;
}
public void setButtonIcon(ImageView[] buttonIcon) {
this.buttonIcon = buttonIcon;
}
public VBox getSidebar() {
return sidebar;
}
public void setSidebar(VBox sidebar) {
this.sidebar = sidebar;
}
}
BaseWindow class:
package spicetify;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
public class BaseWindow{
private Parent root;
private Scene scene;
private Stage stage;
private String title;
private int width;
private int height;
private int minWidth;
private int minHeight;
private String htmlColor;
public int getMinWidth() {
return minWidth;
}
public void setMinWidth(int minWidth) {
this.minWidth = minWidth;
}
public int getMinHeight() {
return minHeight;
}
public void setMinHeight(int minHeight) {
this.minHeight = minHeight;
}
public String getHtmlColor() {
return htmlColor;
}
public void setHtmlColor(String htmlColor) {
this.htmlColor = htmlColor;
}
public Parent getRoot() {
return root;
}
public void setRoot(Parent root) {
this.root = root;
}
public Scene getScene() {
return scene;
}
public void setScene(Scene scene) {
this.scene = scene;
}
public Stage getStage() {
return stage;
}
public void setStage(Stage stage) {
this.stage = stage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public void transform(ImageView view, int width, int height, boolean preserveRatio){
view.setFitWidth(width);
view.setFitHeight(height);
view.setPreserveRatio(preserveRatio);
}
public void start(Stage stage){
stage.setScene(scene);
stage.setTitle(title);
stage.show();
}
}
HomeWindow class:
package spicetify;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class HomeWindow extends BaseWindow {
private ImageView logoView;
private ImageView preview;
private Parent root;
private Scene scene;
BaseWindow baseWindow = new BaseWindow();
Sidebar sidebar = new Sidebar(baseWindow.getHeight(), 100, "#282828", root);
public HomeWindow(int width, int height, String html){
this.logoView = new ImageView(new Image("file:src/main/resources/spicetify/images/essentials/logo.png"));
this.preview = new ImageView(new Image("file:src/main/resources/spicetify/images/essentials/Preview.png"));
this.root = new BorderPane();
baseWindow.setWidth(width);
baseWindow.setMinWidth(width);
baseWindow.setHeight(height);
baseWindow.setMinHeight(height);
baseWindow.setHtmlColor(html);
}
public void start(Stage stage){
((BorderPane) root).setLeft(sidebar.getSidebar());
baseWindow.transform(logoView, 600, 700, true);
((BorderPane) root).setCenter(logoView);
baseWindow.setStage(stage);
baseWindow.setTitle("Spicetify");
baseWindow.setRoot(root);
baseWindow.setScene(new Scene(baseWindow.getRoot(), baseWindow.getWidth(), baseWindow.getHeight(), Color.web(baseWindow.getHtmlColor())));
baseWindow.getStage().setScene(baseWindow.getScene());
baseWindow.getStage().setMinWidth(baseWindow.getMinWidth());
baseWindow.getStage().setMinHeight(baseWindow.getMinHeight());
baseWindow.getStage().setTitle(baseWindow.getTitle());
baseWindow.getStage().show();
}
}
Default Modena CSS has a gray background in panes.
When controls are loaded CSS will be applied to the entire scene, as controls use CSS.
Without any controls, CSS (for performance in straight rendering of graphics primitives) will only be applied to the scene if you specifically apply it.
For more information, and steps you can take to remove the default color from pane backgrounds, see the related question:
JavaFX 8 tooltip removes transparency of stage

How to send dispatchTouchEvent() from service to any Underlay Activity

WHAT I WANT TO DO?
- Basically i want to do the human touch pragmatically at specific time at specific X,Y Coordinates
- Run a service which will receive the X,Y coordinates via some interface (TCP/UDP)
- fire dispatchTouchEvent() using those coordinates and get the results as actual human finger click gives
- I mean focussed activity might be anything either it is Android Home Screen OR Any opened activity OR Anything
- The moment service invokes the dispatchTouchEvent(), It should perform the click.
- For example if opened App is calculator and X,Y coordinates of dispatchTouchEvent() points to numeric 5, It should press the 5 key
WHAT I HAVE DONE TILL NOW?
- I have started a service which receives X,Y coordinates
- On some trigger, it invokes the dispatchTouchEvent(), but it does not work. It does not click anything on the screen.
- It capture every touch event made by human finger.
WHATS THE ISSUE?
- How to issue dispatchTouchEvent() to any underlay activity
SAMPLE CODE:
i am attaching the sample code here. I have just made it simple for test purpose.
First we need to click anywhere in the screen. Its X,Y coordinates will be saved and after some time dispatchTouchEvent() will be invoked
using same coordinates.
MainActivity.java
package com.test.overlay;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Intent intent = new Intent(this, Overlay.class);
Intent intent = new Intent(this, PlayerServiceTest.class);
startService(intent);
finish();
}
}
Overlay.java
package com.test.overlay;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;
#SuppressWarnings("deprecation")
public class Overlay extends Service
{
HUDView mView;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_LONG).show();
mView = new HUDView(this);
/*
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
//WindowManager.LayoutParams.FLAG_LOCAL_FOCUS_MODE | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
//WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
*/
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
/*
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
0,
//WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT);
*/
params.gravity = Gravity.RIGHT | Gravity.TOP;
params.setTitle("Load Average");
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(mView, params);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getBaseContext(),"onDestroy", Toast.LENGTH_LONG).show();
if(mView != null)
{
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(mView);
mView = null;
}
}
}
class HUDView extends ViewGroup
{
private Paint mLoadPaint;
public HUDView(Context context)
{
super(context);
Toast.makeText(getContext(),"HUDView", Toast.LENGTH_LONG).show();
mLoadPaint = new Paint();
mLoadPaint.setAntiAlias(true);
//mLoadPaint.setTextSize(10);
mLoadPaint.setTextSize(25);
//mLoadPaint.setTypeface(Typeface.SANS_SERIF);
mLoadPaint.setTypeface(Typeface.DEFAULT_BOLD);
mLoadPaint.setARGB(255, 25, 200, 50);
}
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawText("THIS IS TEST", 15, 115, mLoadPaint);
}
#Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4)
{
System.out.println("onLayout called ...");
//handleAutoTouches();
}
//===============================================================================
#SuppressLint("NewApi")
public void TestThread()
{
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute()
{
//System.out.println("post0...");
}
#Override
protected Void doInBackground(Void... arg0)
{
//System.out.println("Time started-1");
try
{
//if(flag != 0)
Thread.sleep(7*1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
Toast.makeText(getContext(), "pressed", Toast.LENGTH_SHORT).show();
//System.out.println("handleAutoTouches called-2");
handleAutoTouches();
}
};
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
else
task.execute((Void[])null);
}
//=======================================================================================
public void handleAutoTouches()
{
long downTime = SystemClock.uptimeMillis();
//long eventTime = SystemClock.uptimeMillis() + 100;
long eventTime = SystemClock.uptimeMillis()+700;
//float x = 71.0f;
//float y = 138.0f;
//float x = 120.0f;
//float y = 170.0f;
//Set Manual x/y co-rdinates here
float x = xCor;
float y = yCor;
boolean val;
// List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
int metaState = 0;
final MotionEvent motionEvent = MotionEvent.obtain(
downTime,
eventTime,
//MotionEvent.ACTION_UP,
MotionEvent.ACTION_DOWN,
x,
y,
metaState
);
System.out.println("CLICKED DOWN...");
val = super.dispatchTouchEvent(motionEvent);
System.out.println("Status:"+val);
final MotionEvent motionEvent1 = MotionEvent.obtain(
downTime,
eventTime,
//MotionEvent.ACTION_UP,
MotionEvent.ACTION_UP,
x,
y,
metaState
);
System.out.println("CLICKED UP...");
val = super.dispatchTouchEvent(motionEvent1);
System.out.println("Status:"+val);
//-------------------------------------------------------
flag=0;
}
int flag=0;
float xCor=0;
float yCor=0;
#Override
public boolean onTouchEvent(MotionEvent event)
{
//System.out.println("flag:"+flag);
if(flag == 0) //When manual touch was done
{
//Set flag to avoid the looping
flag=1;
//Get the manual touch co-ordinates for Auto Touch next time
xCor=event.getRawX();
yCor=event.getRawY();
TestThread();
}
System.out.println("onTouchEvent,"+"X:"+event.getRawX()+", Y:"+event.getRawY());
return true;
//return false;
}
/*
#Override
public boolean onInterceptTouchEvent(MotionEvent event)
{
System.out.println("intercepted...");
System.out.println("onTouchEvent,"+"X:"+event.getRawX()+", Y:"+event.getRawY());
if(flag == 0) //When manual touch was done
{
//Set flag to avoid the looping
flag=1;
//Get the manual touch co-ordinates for Auto Touch next time
xCor=event.getRawX();
yCor=event.getRawY();
TestThread();
}
onTouchEvent(event);
return false;
}*/
}
Please point me to the right direction.

Image Location?

I am having trouble simply importing an image using this code. Where should the Image be stored? I thought it had to be in a folder within the source folder and in this case called ImageIcon but I am not sure... thanks to anybody who helps!
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class Surface extends JPanel {
private Image mshi;
public Surface() {
loadImage();
setSurfaceSize();
}
private void loadImage() {
mshi = new ImageIcon("mushrooms.jpg").getImage();
}
private void setSurfaceSize() {
Dimension d = new Dimension();
d.width = mshi.getWidth(null);
d.height = mshi.getHeight(null);
setPreferredSize(d);
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(mshi, 1, 1, null);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
public class DisplayImage extends JFrame {
public DisplayImage() {
initUI();
}
private void initUI() {
setTitle("Mushrooms");
add(new Surface());
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
DisplayImage ex = new DisplayImage();
ex.setVisible(true);
}
});
}
}
Do you try to put the image in the same directory as your class file Surface ?
Ok, sorry i had not seen the class DisplayImage.
The best way i think to do it, create a separate class file for Surface.
Write in Surface class file, a constructor with parameter. The parameter will be the image path. It will be simple for you to change the image if you want after.
Something like this :
public class Surface extends JPanel {
private Image mshi;
public Surface(String imagePath) {
mshi = new ImageIcon(imagePath).getImage();
setSurfaceSize();
}
private void setSurfaceSize() {
Dimension d = new Dimension();
d.width = mshi.getWidth(null);
d.height = mshi.getHeight(null);
setPreferredSize(d);
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(mshi, 1, 1, null);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
You don't need to write the method loadImage(), it will be probably used in your class because it is private and it just do one simple thing.
Concerning the structure of your project directory make something like this
Project directory\src
Project directory\src\Surface.class
Project directory\src\DisplayImage.class
Project directory\images
Project directory\images\mushrooms.jpg
Ps : Sorry for my english, it still under construction.

Libgdx V1.3.1 Splash Screen Tween Error: Exception in thread "LWJGL Application" java.lang.RuntimeException: No TweenAccessor was found for the target

I am having a difficult time implementing the Universal Tween Engine in my android, desktop, and html libgdx projects (Note that this is a problem with libgdx version 1.3.1 that uses gradle).
I have followed the instructions on the github wiki by using the fileTree method shown in the link below.
https://github.com/libgdx/libgdx/wiki/Universal-Tween-Engine
I managed to set the build path of the CORE and ANDROID projects to include the two tween engine jars. The classes get imported easily but when runnning the DESKTOP project I get the following error:
Exception in thread "LWJGL Application" java.lang.RuntimeException: No TweenAccessor was found for the target
at aurelienribon.tweenengine.Tween.build(Tween.java:787)
at aurelienribon.tweenengine.Tween.build(Tween.java:79)
at aurelienribon.tweenengine.BaseTween.start(BaseTween.java:85)
at aurelienribon.tweenengine.TweenManager.add(TweenManager.java:61)
at aurelienribon.tweenengine.BaseTween.start(BaseTween.java:98)
at com.infinitybit.killtheclouds.Screens.Splash.show(Splash.java:58)
at com.badlogic.gdx.Game.setScreen(Game.java:61)
at com.infinitybit.killtheclouds.KillTheClouds.create(KillTheClouds.java:14)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:136)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
Here is my code
Splash.java
package com.infinitybit.killtheclouds.Screens;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenManager;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.infinitybit.killtheclouds.KillTheClouds;
import com.infinitybit.killtheclouds.TweenStuff.SplashAccessor;
public class Splash implements Screen {
public static int SCREEN_WIDTH = Gdx.graphics.getWidth();
public static int SCREEN_HEIGHT = Gdx.graphics.getHeight();
private KillTheClouds game;
private SpriteBatch splashpaper;
private Sprite splashimage;
private TweenManager tweenManager;
public Splash(KillTheClouds game) {
this.game = game;
}
#Override
public void show() {
// TweenSTUFF
tweenManager = new TweenManager();
Tween.registerAccessor(Sprite.class, new SplashAccessor());
splashpaper = new SpriteBatch();
Texture splashTexture = new Texture("images/splash/logo.png");
splashimage = new Sprite(splashTexture);
// image size
splashimage.setSize(SCREEN_WIDTH / 1.5f, SCREEN_HEIGHT / 2);
// center image
splashimage.setPosition(SCREEN_WIDTH / 2 - splashimage.getWidth() / 2,
SCREEN_HEIGHT / 2 - splashimage.getHeight() / 2);
Tween.set(splashTexture, SplashAccessor.ALPHA).target(0)
.start(tweenManager);
Tween.to(splashTexture, SplashAccessor.ALPHA, 3).target(1)
.start(tweenManager);
Tween.to(splashTexture, SplashAccessor.ALPHA, 2).target(0).delay(2)
.start(tweenManager);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// update tween
tweenManager.update(delta);
splashpaper.begin();
splashimage.draw(splashpaper);
splashpaper.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}
SplashAccessor.java
package com.infinitybit.killtheclouds.TweenStuff;
import aurelienribon.tweenengine.TweenAccessor;
import com.badlogic.gdx.graphics.g2d.Sprite;
public class SplashAccessor implements TweenAccessor<Sprite> {
public static final int ALPHA = 0;
#Override
public int getValues(Sprite target, int tweenType, float[] returnValues) {
switch (tweenType) {
case ALPHA:
returnValues[0] = target.getColor().a;
return 1;
default:
assert false;
return -1;
}
}
#Override
public void setValues(Sprite target, int tweenType, float[] newValues) {
float defRed = target.getColor().r;
float defGreen = target.getColor().g;
float defBlue = target.getColor().b;
switch(tweenType){
case ALPHA:
target.setColor(defRed, defGreen, defBlue, newValues[0]);
break;
default:
assert false;
}
}
}
Your splashTexture isn't the type of Sprite it is Texture!!!
That is your problem.
Create splashSprite from splashTexture, and call this:
Tween.to(splashSprite, SplashAccessor.ALPHA, 3).target(1)
.start(tweenManager);
Hope it helps!

JavaFX : Canvas to Image in non GUI Thread

I have to visualize lot of data (real-time) and I am using JavaFX 2.2. So I have decided to "pre-visualize" data before they are inserted into GUI thread.
In my opinion the fastest way to do it (with antialliasing etc.) is let some NON GUI thread to generate image/bitmap and then put in GUI thread (so the UI is still responsive for user).
But I can't find way how to conver Canvas to Image and then use:
Image imageToDraw = convert_tmpCanvasToImage(tmpCanvas);
Platform.runLater(new Runnable() {
#Override
public void run() {
canvas.getGraphicsContext2D().drawImage(imageToDraw, data.offsetX, data.offsetY);
}
});
Thx for some usable answers. :-)
btw: I have made test app to show my problem.
package canvasandthreads02;
import java.util.Random;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class CanvasAndThreads02 extends Application {
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Paint");
final AnchorPane root = new AnchorPane();
final Canvas canvas = new Canvas(900, 800);
canvas.setLayoutX(50);
canvas.setLayoutY(50);
root.getChildren().add(canvas);
root.getChildren().add(btn);
Scene scene = new Scene(root, 900, 800);
primaryStage.setTitle("Painting in JavaFX");
primaryStage.setScene(scene);
primaryStage.show();
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Start painting");
/**
* Start Thread where some data will be visualized
*/
new Thread(new PainterThread(canvas, new DataToPaint())).start();
}
});
}
private class PainterThread implements Runnable{
private final DataToPaint data;
private final Canvas canvas;
public PainterThread(Canvas canvas, DataToPaint data){
this.canvas = canvas;
this.data = data;
}
#Override
public void run() {
long currentTimeMillis = System.currentTimeMillis();
Canvas tmpCanvas = new Canvas(data.width, data.height);
GraphicsContext graphicsContext2D = tmpCanvas.getGraphicsContext2D();
graphicsContext2D.setFill(data.color;);
for (int i = 0; i < data.height; i++) {
for (int j = 0; j < data.width; j++) {
graphicsContext2D.fillRect(j, i, 1, 1); //draw 1x1 rectangle
}
}
/**
* And now I need still in this Thread convert tmpCanvas to Image,
* or use some other method to put result to Main GIU Thread using Platform.runLater(...);
*/
final Image imageToDraw = convert_tmpCanvasToImage(tmpCanvas);
System.out.println("Canvas painting: " + (System.currentTimeMillis()-currentTimeMillis));
Platform.runLater(new Runnable() {
#Override
public void run() {
//Start painting\n Canvas painting: 430 \n Time to convert:62
//long currentTimeMillis1 = System.currentTimeMillis();
//Image imageToDraw = tmpCanvas.snapshot(null, null);
//System.out.println("Time to convert:" + (System.currentTimeMillis()-currentTimeMillis1));
canvas.getGraphicsContext2D().drawImage(imageToDraw, data.offsetX, data.offsetY);
}
});
}
}
private class DataToPaint{
double offsetX = 0;
double offsetY = 0;
Color color;
int width = 500;
int height = 250;
public DataToPaint(){
Random rand = new Random();
color = new Color(rand.nextDouble(), rand.nextDouble(), rand.nextDouble(), rand.nextDouble());
offsetX = rand.nextDouble() * 20;
offsetY = rand.nextDouble() * 20;
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
use Canvas' snapshot(...) method to create a WritableImage from the Canvas' content. ^^
Works fine for me.
I know this is a really old question, but just for anyone who cares:
There is now a second version of canvas.snapshot that takes a callback and works asynchronously!
public void snapshot(Callback<SnapshotResult,Void> callback,
SnapshotParameters params,
WritableImage image)

Resources