JFrame won't load the images I want it to - image

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?

Related

I am trying to learn uses of GUI but vscode and eclipse are both saying "GUI cannot be resolved to a type" after declaring "new GUI()" in main

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUITest {
private JPasswordField passwordBox;
private JButton enterButton = new JButton ("Enter");
private JLabel textBox = new JLabel("Enter Password Here:");;
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
public void GUITest() {
PanelSetup();
FrameSetup();
}
public void PanelSetup(){
panel.setBorder(BorderFactory.createEmptyBorder(150, 150, 250, 250));
panel.setLayout(new GridLayout(0,1));
}
public void FrameSetup(){
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setTitle("GUI TEST");
frame.pack();
frame.setVisible (true);
}
public static void main (String[] args) {
new GUI();
}
}
Unfortunately, the problem is creating the new GUI and I cannot run the code to see if the rest of it works and/or adding more stuff to it. If you can help that would be much appreciated
Change "new GUI();" to "new GUITest();" as you are creating a new instance of the current class.
public static void main (String[] args) {
new GUI();
}
to
public static void main (String[] args) {
new GUITest();
}
Also, remove the void tag from your constructor as it turns it into a method.
public void GUITest() {
PanelSetup();
FrameSetup();
}
to
public GUITest() {
PanelSetup();
FrameSetup();
}
It seems like you're new to java, welcome! I'd take a look at w3schools excellent java docs if you want to get better at syntax. w3schools java

Javafx titledpane animation speed

Is there a way to set the animation speed of a titledpane? I couldn't find anything.
In fact there are two issues.
First:
The animation of the expanding is faster than the expanding of the content itself. You see that the circle is slightly slower than the bar from the second titledpane is moving down.
Second:
How to change the speed of both of them. I need them at the same speed, because it looks weird.
Here is a small example for testing purposes:
package test;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class TestClass extends Application{
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
VBox vb = new VBox();
{
TitledPane tp = new TitledPane();
System.out.println(tp.getContextMenu());
tp.setContent(new Circle(100));
tp.setText("asfadf");
tp.expandedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
System.out.println("expand " + newValue);
}
});
vb.getChildren().add(tp);
}
vb.getChildren().add(new Line(0, 0, 100, 0));
{
TitledPane tp = new TitledPane();
tp.setContent(new Circle(100));
tp.setText("asfadf");
tp.expandedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
System.out.println("expand " + newValue);
}
});
vb.getChildren().add(tp);
}
vb.setStyle("-fx-background-color: gray");
Scene scene = new Scene(vb,500,500);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Short answer: There's no API to change the duration.
However, there are two ways to achieve it anyway:
Alternative #1: Reflection
The duration is defined in the static final field com.sun.javafx.scene.control.TitledPaneSkin.TRANSITION_DURATION. Using reflection, you can change its value but this is really bad. Not only because that's a dirty hack, but also because TitledPaneSkin is Oracle internal API that is subject to change anyway. Also, this does not fix the issue with the different speeds:
private static void setTitledPaneDuration(Duration duration) throws NoSuchFieldException, IllegalAccessException {
Field durationField = TitledPaneSkin.class.getField("TRANSITION_DURATION");
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(durationField, durationField.getModifiers() & ~Modifier.FINAL);
durationField.setAccessible(true);
durationField.set(TitledPaneSkin.class, duration);
}
Alternative #2: Set your own skin
To be on the safe side, you could create and use your own skin (start by copying the existing one) using titledPane.setSkin(). This way you can also fix the different speed, which is basically caused by linear vs. ease interpolation - but that's quite some work.
Just disable the animation with something like:
TitledPane pane = new TitledPane();
pane.animatedProperty().set(false);
and expanding will be as fast as possible.

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.

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

Update UI from an AsyncTaskLoader

I've converted my AsyncTask to an AsyncTaskLoader (mostly to deal with configuration changes). I have a TextView I am using as a progress status and was using onProgressUpdate in the AsyncTask to update it. It doesn't look like AsyncTaskLoader has an equivalent, so during loadInBackground (in the AsyncTaskLoader) I'm using this:
getActivity().runOnUiThread(new Runnable() {
public void run() {
((TextView)getActivity().findViewById(R.id.status)).setText("Updating...");
}
});
I am using this in a Fragment, which is why I'm using getActivity(). This work pretty well, except when a configuration change happens, like changing the screen orientation. My AsyncTaskLoader keeps running (which is why I'm using an AsyncTaskLoader), but the runOnUiThread seems to get skipped.
Not sure why it's being skipped or if this is the best way to update the UI from an AsyncTaskLoader.
UPDATE:
I ended up reverting back to an AsyncTask as it seems better suited for UI updates. Wish they could merge what works with an AsyncTask with an AsyncTaskLoader.
It's actually possible. You essentially need to subclass the AsyncTaskloader and implement a publishMessage() method, which will use a Handler to deliver the progress message to any class that implements the ProgressListener (or whatever you want to call it) interface.
Download this for an example: http://www.2shared.com/file/VW68yhZ1/SampleTaskProgressDialogFragme.html (message me if it goes offline) - this was based of http://habrahabr.ru/post/131560/
Emm... you shouldn't be doing this.
because how an anonymous class access parent class Method or Field is by storing an invisible reference to the parent class.
for example you have a Activity:
public class MyActivity
extends Activity
{
public void someFunction() { /* do some work over here */ }
public void someOtherFunction() {
Runnable r = new Runnable() {
#Override
public void run() {
while (true)
someFunction();
}
};
new Thread(r).start(); // use it, for example here just make a thread to run it.
}
}
the compiler will actually generate something like this:
private static class AnonymousRunnable {
private MyActivity parent;
public AnonymousRunnable(MyActivity parent) {
this.parent = parent;
}
#Override
public void run() {
while (true)
parent.someFunction();
}
}
So, when your parent Activity destroys (due to configuration change, for example), and your anonymous class still exists, the whole activity cannot be gc-ed. (because someone still hold a reference.)
THAT BECOMES A MEMORY LEAK AND MAKE YOUR APP GO LIMBO!!!
If it was me, I would implement the "onProgressUpdate()" for loaders like this:
public class MyLoader extends AsyncTaskLoader<Something> {
private Observable mObservable = new Observable();
synchronized void addObserver(Observer observer) {
mObservable.addObserver(observer);
}
synchronized void deleteObserver(Observer observer) {
mObservable.deleteObserver(observer);
}
#Override
public void loadInBackground(CancellationSignal signal)
{
for (int i = 0;i < 100;++i)
mObservable.notifyObservers(new Integer(i));
}
}
And in your Activity class
public class MyActivity extends Activity {
private Observer mObserver = new Observer() {
#Override
public void update(Observable observable, Object data) {
final Integer progress = (Integer) data;
mTextView.post(new Runnable() {
mTextView.setText(data.toString()); // update your progress....
});
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreated(savedInstanceState);
MyLoader loader = (MyLoader) getLoaderManager().initLoader(0, null, this);
loader.addObserver(mObserver);
}
#Override
public void onDestroy() {
MyLoader loader = (MyLoader) getLoaderManager().getLoader(0);
if (loader != null)
loader.deleteObserver(mObserver);
super.onDestroy();
}
}
remember to deleteObserver() during onDestroy() is important, this way the loader don't hold a reference to your activity forever. (the loader will probably be held alive during your Application lifecycle...)
Answering my own question, but from what I can tell, AsyncTaskLoader isn't the best to use if you need to update the UI.
In the class in which you implement LoaderManager.LoaderCallback (presumably your Activity), there is an onLoadFinished() method which you must override. This is what is returned when the AsyncTaskLoader has finished loading.
The best method is to use LiveData, 100% Working
Step 1: Add lifecycle dependency or use androidx artifacts as yes during project creation
implementation "androidx.lifecycle:lifecycle-livedata:2.1.0"
Step 2: Create the loader class as follow, in loader create in public method to set the livedata that can be observed from activity or fragment. see the setLiveCount method in my loader class.
package com.androidcodeshop.asynctaskloaderdemo;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.MutableLiveData;
import androidx.loader.content.AsyncTaskLoader;
import java.util.ArrayList;
public class ContactLoader extends AsyncTaskLoader<ArrayList<String>> {
private MutableLiveData<Integer> countLive = new MutableLiveData<>();
synchronized public void setLiveCount(MutableLiveData<Integer> observer) {
countLive = (observer);
}
public ContactLoader(#NonNull Context context) {
super(context);
}
#Nullable
#Override
public ArrayList<String> loadInBackground() {
return loadNamesFromDB();
}
private ArrayList<String> loadNamesFromDB() {
ArrayList<String> names = new ArrayList<>();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
names.add("Name" + i);
countLive.postValue(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return names;
}
#Override
protected void onStartLoading() {
super.onStartLoading();
forceLoad(); // forcing the loading operation everytime it starts loading
}
}
Step 3: Set the live data from activity and observe the change as follows
package com.androidcodeshop.asynctaskloaderdemo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<ArrayList> {
private ContactAdapter mAdapter;
private ArrayList<String> mNames;
private MutableLiveData<Integer> countLiveData;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNames = new ArrayList<>();
mAdapter = new ContactAdapter(this, mNames);
RecyclerView mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
countLiveData = new MutableLiveData<>();
countLiveData.observe(this, new androidx.lifecycle.Observer<Integer>() {
#Override
public void onChanged(Integer integer) {
Log.d(TAG, "onChanged: " + integer);
Toast.makeText(MainActivity.this, "" +
integer,Toast.LENGTH_SHORT).show();
}
});
// initialize the loader in onCreate of activity
getSupportLoaderManager().initLoader(0, null, this);
// it's deprecated the best way is to use viewmodel and livedata while loading data
}
#NonNull
#Override
public Loader onCreateLoader(int id, #Nullable Bundle args) {
ContactLoader loader = new ContactLoader(this);
loader.setLiveCount(countLiveData);
return loader;
}
#Override
public void onLoadFinished(#NonNull Loader<ArrayList> load, ArrayList data) {
mNames.clear();
mNames.addAll(data);
mAdapter.notifyDataSetChanged();
}
#Override
public void onLoaderReset(#NonNull Loader loader) {
mNames.clear();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Hope this will help you :) happy coding

Resources