Image Location? - image

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.

Related

Issues running/debugging mapbox android code examples

I am trying to get started with mapbox android and can't get any of the example projects to work.
My problem is with the imports
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import com.mapbox.mapboxandroiddemo.R;
I get I "cannot resolve symbol annotation", "cannot resolve symbol v7" and "cannot resolve symbol mapboxandroiddemo".
I feel like this is some android problem that I am just not understanding correctly so if anyone has some insight that would be amazing. I have tried taking out some code and using the recommended bug fixes but all that has done is break my project.
Here is the entire MainActivity.java file
package com.example.mapboxtut;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatActivity;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.FeatureCollection;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxandroiddemo.R;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import com.mapbox.mapboxsdk.utils.BitmapUtils;
import static com.mapbox.mapboxsdk.style.expressions.Expression.get;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textField;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textOffset;
/**
* Use the {#link MapView#addOnStyleImageMissingListener(MapView.OnStyleImageMissingListener)}
* to handle the situation where a SymbolLayer tries using a missing image as an icon. If an icon-image
* cannot be found in a map style, a custom image can be provided to the map via
* the listener.
*/
public class MissingIconActivity extends AppCompatActivity {
private static final String ICON_SOURCE_ID = "ICON_SOURCE_ID";
private static final String ICON_LAYER_ID = "ICON_LAYER_ID";
private static final String PROFILE_NAME = "PROFILE_NAME";
private static final String CARLOS = "Carlos";
private static final String ANTONY = "Antony";
private static final String MARIA = "Maria";
private static final String LUCIANA = "Luciana";
private MapView mapView;
private MapboxMap mapboxMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Mapbox access token is configured here. This needs to be called either in your application
// object or in the same activity which contains the mapview.
Mapbox.getInstance(this, getString(R.string.access_token));
// This contains the MapView in XML and needs to be called after the access token is configured.
setContentView(R.layout.activity_styles_missing_icon);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
// Add Features which represent the location of each profile photo SymbolLayer icon
Feature carlosFeature = Feature.fromGeometry(Point.fromLngLat(-7.9760742,
41.2778064));
carlosFeature.addStringProperty(PROFILE_NAME, CARLOS);
Feature antonyFeature = Feature.fromGeometry(Point.fromLngLat(-8.0639648,
37.5445773));
antonyFeature.addStringProperty(PROFILE_NAME, ANTONY);
Feature mariaFeature = Feature.fromGeometry(Point.fromLngLat(-9.1845703,
38.9764924));
mariaFeature.addStringProperty(PROFILE_NAME, MARIA);
Feature lucianaFeature = Feature.fromGeometry(Point.fromLngLat(-7.5146484,
40.2459915));
lucianaFeature.addStringProperty(PROFILE_NAME, LUCIANA);
// Use a URL to build and add a Style object to the map. Then add a source to the Style.
mapboxMap.setStyle(
new Style.Builder().fromUrl(Style.LIGHT)
.withSource(new GeoJsonSource(ICON_SOURCE_ID,
FeatureCollection.fromFeatures(new Feature[] {
carlosFeature,
antonyFeature,
mariaFeature,
lucianaFeature}))),
new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
MissingIconActivity.this.mapboxMap = mapboxMap;
// Add a SymbolLayer to the style. iconImage is set to a value that will
// be used later in the addOnStyleImageMissingListener below
style.addLayer(new SymbolLayer(ICON_LAYER_ID, ICON_SOURCE_ID).withProperties(
iconImage(get(PROFILE_NAME)),
iconIgnorePlacement(true),
iconAllowOverlap(true),
textField(get(PROFILE_NAME)),
textIgnorePlacement(true),
textAllowOverlap(true),
textOffset(new Float[] {0f, 2f})
));
}
});
}
});
// Use the listener to match the id with the appropriate person. The correct profile photo is
// given to the map during "runtime".
mapView.addOnStyleImageMissingListener(new MapView.OnStyleImageMissingListener() {
#Override
public void onStyleImageMissing(#NonNull String id) {
switch (id) {
case CARLOS:
addImage(id, R.drawable.carlos);
break;
case ANTONY:
addImage(id, R.drawable.antony);
break;
case MARIA:
addImage(id, R.drawable.maria);
break;
case LUCIANA:
addImage(id, R.drawable.luciana);
break;
default:
addImage(id, R.drawable.carlos);
break;
}
}
});
}
private void addImage(String id, int drawableImage) {
Style style = mapboxMap.getStyle();
if (style != null) {
style.addImageAsync(id, BitmapUtils.getBitmapFromDrawable(
getResources().getDrawable(drawableImage)));
}
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}

How to separate a JavaFX Appliciation

I want to seperate a JavaFX project to model, view and controller.
I use netbeans when creating a JavaFX application.
But I want the code seperate, an own GUI, own logic and a Main class just to start the application (I want 3 seperate classes).
But I am not able to solve this problem.
The automatic created code looks like this:
package at.wueschn.www;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
If you are using NetBeans, first choose File -> New Project. Then JavaFX -> JavaFX FXML Application
Note: This is a basic MVC setup. You could do all of this using pure code. James_D could probably help you with more advanced MCV ideas.
Note: If you are going to take this simple approach, I suggest you download SceneBuilder to help you with the view.
Tutorial
Here is a "Java-only" (i.e. no FXML) example of MVC. Note that there are many different variants of MVC, which is a very loosely-defined pattern. This is a kind of "classical" variant: the model has no knowledge of the view(s) or controller(s) (which is the common theme to all MVC-type designs), the controller has a reference to the model and invokes methods on it, implementing some simple logic, and the view has a reference to both the model and controller; observing the model and updating the view components when the data changes, and invoking methods on the controller in response to user input. Other variants of this pattern (MVVM, MVP, etc) typically vary in the relationship between the view and the controller.
This simple application implements a very basic calculator, which simply knows how to add two single-digit integers.
The model:
import javafx.beans.binding.NumberBinding;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
public class Model {
private boolean firstNumberEntered ;
private final IntegerProperty firstNumber = new SimpleIntegerProperty();
private final IntegerProperty secondNumber = new SimpleIntegerProperty();
private final NumberBinding sum = firstNumber.add(secondNumber);
public Model() {
firstNumber.addListener((obs, oldValue, newValue) -> firstNumberEntered = true );
}
public IntegerProperty firstNumberProperty() {
return firstNumber ;
}
public int getFirstNumber() {
return firstNumberProperty().get();
}
public void setFirstNumber(int number) {
firstNumberProperty().set(number);
}
public IntegerProperty secondNumberProperty() {
return secondNumber ;
}
public int getSecondNumber() {
return secondNumberProperty().get();
}
public void setSecondNumber(int number) {
secondNumberProperty().set(number);
}
public NumberBinding sumBinding() {
return sum ;
}
public int getSum() {
return sum.intValue();
}
public boolean isFirstNumberEntered() {
return firstNumberEntered ;
}
public void reset() {
setFirstNumber(0);
setSecondNumber(0);
firstNumberEntered = false ;
}
}
The controller:
public class Controller {
private final Model model ;
public Controller(Model model) {
this.model = model ;
}
public void enterFirstNumber(int number) {
model.setFirstNumber(number);
}
public void enterSecondNumber(int number) {
model.setSecondNumber(number);
}
public void clear() {
model.reset();
}
public void enterNumber(int number) {
if (model.isFirstNumberEntered()) {
enterSecondNumber(number) ;
} else {
enterFirstNumber(number);
}
}
}
The view:
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.RowConstraints;
public class View {
private final BorderPane root ;
private final Controller controller ;
public View(Model model, Controller controller) {
this.controller = controller ;
root = new BorderPane();
GridPane buttons = new GridPane();
configureButtons(buttons);
createAndAddButtons(controller, buttons);
Label resultLabel = new Label();
configureDisplay(model, resultLabel);
root.setTop(resultLabel);
root.setCenter(buttons);
root.setStyle("-fx-font-size: 36pt;");
}
private void configureDisplay(Model model, Label resultLabel) {
BorderPane.setAlignment(resultLabel, Pos.CENTER_RIGHT);
BorderPane.setMargin(resultLabel, new Insets(5));
resultLabel.textProperty().bind(Bindings.createStringBinding(
() -> String.format("%d + %d = %d", model.getFirstNumber(), model.getSecondNumber(), model.getSum()),
model.firstNumberProperty(), model.secondNumberProperty(), model.sumBinding()));
}
private void createAndAddButtons(Controller controller, GridPane buttons) {
for (int i = 1 ; i <= 9 ; i++) {
int row = (9 - i) / 3 ;
int column = (i -1) % 3 ;
buttons.add(createNumberButton(i), column, row);
}
buttons.add(createNumberButton(0), 0, 3);
Button clearButton = createButton("C");
clearButton.setOnAction(e -> controller.clear());
buttons.add(clearButton, 1, 3, 2, 1);
}
private void configureButtons(GridPane buttons) {
for (int row = 0 ; row < 4 ; row++) {
RowConstraints rc = new RowConstraints();
rc.setFillHeight(true);
rc.setPercentHeight(100.0 / 4);
buttons.getRowConstraints().add(rc);
}
for (int column = 0 ; column < 3 ; column++) {
ColumnConstraints cc = new ColumnConstraints();
cc.setFillWidth(true);
cc.setPercentWidth(100.0 / 3);
buttons.getColumnConstraints().add(cc);
}
buttons.setVgap(5);
buttons.setHgap(5);
buttons.setPadding(new Insets(5));
}
public Parent getRoot() {
return root ;
}
private Button createNumberButton(int number) {
Button button = createButton(Integer.toString(number));
button.setOnAction(e -> controller.enterNumber(number));
return button ;
}
private Button createButton(String text) {
Button button = new Button(text);
button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
return button ;
}
}
and finally the "main" class which creates each piece and displays the view in a window:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class TrivialCalcaulatorApp extends Application {
#Override
public void start(Stage primaryStage) {
Model model = new Model();
Controller controller = new Controller(model);
View view = new View(model, controller);
Scene scene = new Scene(view.getRoot());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

JFrame won't load the images I want it to

Please be patient with me.. I'm very new to Java.
I have two separate JFrames and the first loads the background I want but when I dispose the first JFrame and load the second one it loads with the background from the first.
j1.java
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
public class j1 extends JFrame implements KeyListener {
public bg1 img;
public bg2 img2;
public j1() {
lvl1();
}
private JFrame lvl1() {
this.img=new bg1();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
setTitle("lvl1");
setResizable(false);
setSize(600, 600);
setMinimumSize(new Dimension(600, 600));
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().add(img);
pack();
setVisible(true);
return(this);
}
private JFrame lvl2() {
this.img2=new bg2();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
setTitle("lvl2");
setResizable(false);
setSize(600, 600);
setMinimumSize(new Dimension(600, 600));
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().add(img2);
pack();
setVisible(true);
return(this);
}
public void keyPressed(KeyEvent e) { }
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()== KeyEvent.VK_RIGHT) {
lvl1().dispose();
lvl2();
}
}
public void keyTyped(KeyEvent e) { }
public static void main(String[] args) {
new j1();
}
}
bg1.java
import java.awt.Graphics;
import javax.swing.JComponent;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
public class bg1 extends JComponent {
public BufferedImage person;
public BufferedImage background;
public bg1() {
loadImages2();
}
public void loadImages2() {
try {
String personn = "Images/person.gif";
person = ImageIO.read(new File(personn));
String backgroundd = "Images/background2.jpg";
background = ImageIO.read(new File(backgroundd));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, this);
g.drawImage(person, 100, 100, this);
}
public static void main(String[] args) {
new bg1();
}
}
bg2.java is very similar to bg1.java but it has different names for the images and voids.
So you kind of have a series of problems.
First, this is one of the dangers of re-using a frame this way, basically, you never actually remove bg1 from the frame, you just keep adding new instances of the bg2. This means that bg1 is still visible and valid on the frame...
Second, you're calling lvl1() AGAIN before you call lvl2, which is making a new instance of bg1 and adding that to the window and then disposing of it (which does NOT dispose of the components) and then you add a new instance of lvl2 to the frame and the whole thing is just one big mess.
Instead, you should simply be using a CardLayout which will allow you to switch between the individual views more elegantly. See How to Use CardLayout for moer details.
You should also have a look at How to Use Key Bindings instead of using KeyListener
As general rule of thumb, you should avoid overriding JFrame, this has a nasty habit of just confusing the whole thing. Simple create a new instance of a JFrame when you need it and add you components directly to it. Before anyone takes that the wrong way, you'll also want to have a look at The Use of Multiple JFrames, Good/Bad Practice?

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!

Image won't display in JFrame

I am trying to get an image to display inside my JFrame and having no success. I have followed the Oracle tutorial exactly and I get a NullPointerException:
Exception in thread "main" java.lang.NullPointerException
at net.ultibyte.TheDo.CreateLoginScreen.DisplayImage(CreateLoginScreen.java:35)
at net.ultibyte.TheDo.CreateLoginScreen.main(CreateLoginScreen.java:41)
Below is my code.
public class CreateLoginScreen extends JFrame {
CreateLoginScreen() {
setTitle("TheDo");
setSize(1280, 720);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static Image loadImage() {
Image i = null;
try {
i = ImageIO.read(new File("src/resources/LoginScreen.png"));
} catch (IOException e) {
}
return i;
}
public static void DisplayImage(Image i) {
Graphics g = i.getGraphics();
g.drawImage(i, 0, 0, null);
}
public static void main(String[] args) {
CreateLoginScreen a = new CreateLoginScreen();
DisplayImage(loadImage());
}
}
And the image is named "LoginScreen.png", and is located in a package called "resources" which is in the src folder.
I have no idea what's wrong and would very much appreciate any help :).
Update: Corrected file path, pointed out by peeskillet. This fixed the NullPointerException. Still won't display image though.
"located in a package called "resources" which is in the src folder."
You need to use this file path. "src/resources/LoginScreen.png"
Your IDE will first look in the main project folder. since src is direct child of the project root, you need to add that to the path
EDIT
"The window loads up but no image is displayed. Any idea on this? "
Yes, you need to override a paint method in order to draw the image on to the component. I wouldn't use JFrame though. I would use a JPanel and override the paintComponent method.
Try this out
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
class JPanelTemplate extends JPanel {
private static final int SCREEN_WIDTH = 400;
BufferedImage img;
public JPanelTemplate() {
try {
img = ImageIO.read(new File("src/resources/LoginScreen.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(SCREEN_WIDTH, SCREEN_WIDTH);
}
private static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new JPanelTemplate());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Resources