ImageIcon in JLabel not working - java

I've been struggling with this problem for weeks to no avail. Other Java forums have not been able to help me with this so I'm hoping I can find someone here with new eyes. I have a JFrame in which, among other things, I am trying to insert an image. I have put together an SSCCE that reproduces the problem.
public class ImageTest {
public static void main(String[] args) {
SplashScreen.ShowWindow();
}
}
public class SplashScreen {
private JFrame frmKcbsEventsSearch;
public SplashScreen() {
initialize();
}
public static void ShowWindow() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SplashScreen window = new SplashScreen();
window.frmKcbsEventsSearch.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void initialize() {
frmKcbsEventsSearch=new JFrame();
frmKcbsEventsSearch.getContentPane().setBounds(new Rectangle(200, 200, 520, 450));
frmKcbsEventsSearch.getContentPane().setFont(new Font("Times New Roman", Font.PLAIN, 16));
frmKcbsEventsSearch.setTitle("KCBS Events Search");
frmKcbsEventsSearch.setBounds(200,200,520,450);
frmKcbsEventsSearch.getContentPane().setLayout(new FlowLayout());
frmKcbsEventsSearch.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JLabel logo;
java.net.URL logoURL=getClass().getResource("KCBSLogo.jpg");
if (logoURL!=null) {
try {
logo = new JLabel();
logo.setIcon(new ImageIcon(logoURL));
}
catch (Exception e) {
logo = new JLabel("KCBS Logo");
}
}
else {
logo = new JLabel("KCBS Logo missing");
}
logo.setHorizontalAlignment(SwingConstants.CENTER);
logo.setVerticalAlignment(SwingConstants.CENTER);
frmKcbsEventsSearch.getContentPane().add(logo);
}
}
It has been mentioned elsewhere that the layout is important to make this work. I've not had much luck getting layout managers to do what I want but in this case I just want to get the image displayed. Once I have that I'll work through getting it formatted the way I want.

This code works perfectly fine!
I changed the KCBSLogo.jpg to a source that I had named tile.png.
When I ran it displayed perfectly.
Make sure the KCBSLogo.jpg is in your SRC folder in the project.
http://i.stack.imgur.com/sYfYF.png
As you can see the tile image was shown.

Related

Using jWindow as splash screen which shows good but image doesn't paint ... just blank jWindow opened...any thoughts?

jWindow opened for 2 seconds but image doesn't paint... any thoughts?
image file is in the same folder as class file...
public class CreateSplashScreen extends JWindow {
JWindow jw = new JWindow();
Image scImage = Toolkit.getDefaultToolkit().getImage("testImage.png");
ImageIcon imageIcon = new ImageIcon(scImage);
public CreateSplashScreen() {
try {
jw.setSize(700, 500);
jw.setLocationRelativeTo(null);
jw.setVisible(true);
} catch (Exception e) {
}
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(scImage, 0, 0, jw);
}
public void CloseSplashScreen() {
jw.setVisible(false);
}
public static void main(String[] args) {
CreateSplashScreen sp = new CreateSplashScreen();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(CreateSplashScreen.class.getName()).log(Level.SEVERE, null, ex);
}
sp.CloseSplashScreen();
}
}
jWindow opened for 2 seconds but image doesn't paint... any thoughts?
image file is in the same folder as class file...
Why are you creating an internal JWindow when your class CreateSplashScreen already extends JWindow?
There is no need of it. You are messing with your program.
How?
You are actually viewing the inner JWindow by jw.setVisible(true); but you are painting the image in the CreateSplashScreen's `JWindow.
Try this code :
public class CreateSplashScreen extends JWindow
{
ImageIcon i = new ImageIcon(getClass().getResource("/createsplashscreen/testImage.png"));
public CreateSplashScreen() {
setSize(700, 500);
setLocationRelativeTo(null);
setVisible(true);
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(i.getImage(), 0, 0, null);
}
public void CloseSplashScreen() {
setVisible(false);
}
public static void main(String[] args) {
CreateSplashScreen sp = new CreateSplashScreen();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
}
sp.CloseSplashScreen();
}
}
Note: I do not know about your method to fetch image resource from the source folder.
Edit: Assuming that the name of the package containing your class CreateSplashScreen is createsplashscreen, make sure that the image testImage.png is present in the createsplashscreen package of your project.
#Peter
For error code, I deleted one line that I added in mamifest.mf file and build a program...
This time, didn't give me an error, weird...
I was following error code when I got it and it led me to something like "CLASSPATH" section of application generated code... sorry I can't remember exactly
Really appreciate Peter for your help.
Wish you luck...

How do you take in key inputs without a text field in Java

I want to know how to be able to change a JLabel in java Swing to the button I press but I don't know what I'm missing something. Please help.
What it should end up looking like is on the top of the screen it will show the key being pressed and will update the JLabel as you press it. Don't worry about the Imports, I have them all in the actual code. Thanks :)
public class RandomFrame extends JFrame{
Dimension Size = new Dimension(800,800);
ListenForKeys LFK = new ListenForKeys();
JLabel JInput = new JLabel("");
JPanel P1 = new JPanel();
public static void main(String[] args) {
new RandomFrame();
}
public RandomFrame() {
super("RandomFrame");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(Size);
P1.add(JInput);
this.add(P1);
this.setVisible(true);
}
private class ListenForKeys implements KeyListener {
#Override
public void keyPressed(KeyEvent e) {
String Key = String.valueOf(e.getKeyChar());
JInput.setText(Key);
}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyTyped(KeyEvent e) {}
}
}
Austin pointed out that LFK wasn't attached to anything and sure enough, I added it to the JFrame using the line this.addKeyListener(LFK) and sure enough it worked. Thank you :)

Worldwind SurfaceImage Deep/Batch Picking

I'm using WorldWind and trying to "pick" multiple surface images in the same layer and not understanding why it isn't working.
I was under the impression that calling this:
this.getWwd().getSceneController().setDeepPickEnabled(true);
Would enable me to pick multiple renderables in the same layer. This seems to work for all other cases other than SurfaceImage. I also noticed if I force the loaded SurfaceImage into different layers it works as expected.
This is the code I'm using to test this out:
public class SurfaceImageViewer extends ApplicationTemplate
{
public static class AppFrame extends ApplicationTemplate.AppFrame
{
private JFileChooser fileChooser = new JFileChooser();
private JSlider opacitySlider;
private SurfaceImageLayer layer;
private JLabel statusLabel = new JLabel("status: ready");
public AppFrame()
{
super(true, true, false);
this.getWwd().getSceneController().setDeepPickEnabled(true);
try
{
this.layer = new SurfaceImageLayer();
this.layer.setOpacity(1);
this.layer.setPickEnabled(true);
this.layer.setName("Surface Images");
insertBeforeCompass(this.getWwd(), layer);
this.getControlPanel().add(makeControlPanel(), BorderLayout.SOUTH);
}
catch (Exception e)
{
e.printStackTrace();
}
this.getWwd().addSelectListener(new SelectListener() {
#Override
public void selected(SelectEvent event) {
PickedObjectList pol = AppFrame.this.getWwd().getObjectsAtCurrentPosition();
if(event.isLeftClick()){
System.out.println("POL SIZE "+pol.size());
}
}
});
}
Action openElevationsAction = new AbstractAction("Open Elevation File...")
{
public void actionPerformed(ActionEvent e)
{
int status = fileChooser.showOpenDialog(AppFrame.this);
if (status != JFileChooser.APPROVE_OPTION)
return;
final File imageFile = fileChooser.getSelectedFile();
if (imageFile == null)
return;
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
CompoundElevationModel cem
= (CompoundElevationModel) getWwd().getModel().getGlobe().getElevationModel();
LocalElevationModel em = new LocalElevationModel();
em.addElevations(imageFile.getPath());
cem.addElevationModel(em);
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
});
t.setPriority(Thread.MIN_PRIORITY);
t.start();
}
};
Action openImageAction = new AbstractAction("Open Image File...")
{
public void actionPerformed(ActionEvent actionEvent)
{
int status = fileChooser.showOpenDialog(AppFrame.this);
if (status != JFileChooser.APPROVE_OPTION)
return;
final File imageFile = fileChooser.getSelectedFile();
if (imageFile == null)
return;
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
statusLabel.setText("status: Loading image");
// TODO: proper threading
layer.addImage(imageFile.getAbsolutePath());
getWwd().redraw();
statusLabel.setText("status: ready");
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
t.setPriority(Thread.MIN_PRIORITY);
t.start();
}
};
private JPanel makeControlPanel()
{
JPanel controlPanel = new JPanel(new GridLayout(0, 1, 5, 5));
JButton openImageButton = new JButton(openImageAction);
controlPanel.add(openImageButton);
this.opacitySlider = new JSlider();
this.opacitySlider.setMaximum(100);
this.opacitySlider.setValue((int) (layer.getOpacity() * 100));
this.opacitySlider.setEnabled(true);
this.opacitySlider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
int value = opacitySlider.getValue();
layer.setOpacity(value / 100d);
getWwd().redraw();
}
});
JPanel opacityPanel = new JPanel(new BorderLayout(5, 5));
opacityPanel.setBorder(new EmptyBorder(0, 10, 0, 0));
opacityPanel.add(new JLabel("Opacity"), BorderLayout.WEST);
opacityPanel.add(this.opacitySlider, BorderLayout.CENTER);
controlPanel.add(opacityPanel);
JButton openElevationsButton = new JButton(openElevationsAction);
controlPanel.add(openElevationsButton);
controlPanel.add(statusLabel);
controlPanel.setBorder(new EmptyBorder(15, 15, 15, 15));
return controlPanel;
}
}
public static void main(String[] args)
{
ApplicationTemplate.start("World Wind Surface Images", SurfaceImageViewer.AppFrame.class);
}
}
These are 2 geotiffs that are layered on top of each other that I've been using to test this out. I would expect my println on the SelectListener to print out "3" when I single left click on both geotiffs. (I've uploaded the geotiffs into a zip available here)
The area where you will see these is in San Francisco, see screenshot:
Update:
It was discovered that the examples for Batch Picking were oriented around AbstractSurfaceObject instances, which did not apply in this case. For the handling of SurfaceImage instances the property for setAlwaysOnTop should be configured to false which appears to let the selection event process all elements under the cursor.
Reading through the examples for DeepPicking, there are actually 2 things that need to be done.
setDeepPickEnabled(true); //This is done.
Disable Batch picking on the desired elements
https://github.com/nasa/World-Wind-Java/blob/master/WorldWind/src/gov/nasa/worldwindx/examples/DeepPicking.java
In order to enable deep picking, any batch picking for the desired elements must be disabled and the
SceneController's deep picking property must be enabled. See {#link gov.nasa.worldwind.SceneController#setDeepPickEnabled(boolean)
Took me a little while to understand the second one, but it appears to be tied to the AbstractSurfaceObject class.
I am assuming that the things that you're drawing on the layer are a subclass of AbstractSurfaceObject
I believe that in this situation, I would subclass the SurfaceImageLayer, and override the addRenderable methods. I would check the renderable if it was an instance of an AbstractSurfaceObject, and disable batch picking on it before forwarding it to the super class.
This code may not be the best long-term solution, but it may provide quick results to determine if this is the underlying issue.
import gov.nasa.worldwind.layers.SurfaceImageLayer;
import gov.nasa.worldwind.render.AbstractSurfaceObject;
import gov.nasa.worldwind.render.Renderable;
/**
* Very Rough extension of SurfaceImageLayer which disables batch picking on all AbstractSurfaceobjects.
* #author http://stackoverflow.com/users/5407189/jeremiah
* #since Nov 26, 2016
*
*/
public class MySurfaceImageLayer extends SurfaceImageLayer {
#Override
public void addRenderable(Renderable renderable) {
if (renderable instanceof AbstractSurfaceObject) {
((AbstractSurfaceObject)renderable).setEnableBatchPicking(false);
}
super.addRenderable(renderable);
}
#Override
public void addRenderables(Iterable<? extends Renderable> renderables) {
for (Renderable r : renderables) {
addRenderable(r);
}
}
}
IF the thing you want to have picked is the image directly, that appears to not be supported out-of-the-box. You would need to do something to get the SurfaceImage references from the SurfaceImageLayer to be visible to the RenderableLayer on doPick. That may come with a new set of problems to watch out for.
As a side-note, if you're rendering Icons then all you need to do is set the IconRenderer.setAllowBatchPicking(false)
I hope that's at least somewhat helpful.
Best of Luck.

Image in JFrame doesn't want to display with the call in another class

I work on a Java development software with Swing and I have a problem with my code, I want to display an image with the LoadingFrame class, its main work but when I call the constructor and the start() method in my main class, the frame opens but the image doesn't display (I have no Exception).
Why it doesn't work with my main class?
public class LoadingFrame
{
private JFrame frame;
public LoadingFrame()
{
frame = new JFrame();
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setUndecorated(true);
frame.setContentPane(new Panneau());
}
public void start()
{
frame.setVisible(true);
}
public void stop()
{
frame.setVisible(false);
}
public static void main(String[] args)
{
LoadingFrame l = new LoadingFrame();
l.start();
try
{
Thread.sleep(3000);
}
catch(Exception e)
{
e.printStackTrace();
}
l.stop();
}
}
public class Panneau extends JPanel
{
public void paintComponent(Graphics g)
{
System.out.println("hello");
try
{
Image img = ImageIO.read(new File("Images/loading.png"));
//g.drawImage(img, 0, 0, this);
//Pour une image de fond
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
The App class is my main class :
public class App {
//Attributes used to display the application
private JFrame frame;
//Attribute which display a waiting frame
private static LoadingFrame loadingFrame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
loadingFrame = new LoadingFrame();
loadingFrame.start();
App window = new App();
loadingFrame.stop();
window.frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public App()
{
initialize();
synchronizeScriptReferenceList();
synchronizeTests();
}
[...]
}
I was able to get this to work from App.java. For some reason, using EventQueue isn't cutting it. I tried to use SwingUtilities as well, but that doesn't work either. Finally I tried just get rid of the Thready-stuff in App.main at just straight up running it in the main thread. For some reason, this works when the other approaches do not! Here is my code:
// In the App class:
public static void main(String[] args) {
try {
loadingFrame = new LoadingFrame();
loadingFrame.start();
App window = new App();
loadingFrame.stop();
window.frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
When I used this code, I got it to work! (for some reason unknown to me), And here's a bonus rewrite of the Panneau class:
class Panneau extends JPanel
{
Image img;
public Panneau() {
try
{
img = ImageIO.read(new File("Images/loading.png"));
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
There are two main difference with this class; problems which I addressed. Here they are:
I call super.paintComponent as the very first method in our own paintComponent
I only load the loading image once, in the constructor, and not every single time I want to draw, which moves everything along much smoother. (you don't want the loading screen to be CPU heavy, do you?)
Hopefully, with these improvements, I hope you can make your program work! It worked with me, so I wish the best of luck to you.
P.S. Don't call frame.pack(), that was a mistake on my part. For some reason, I think it doesn't work well with undecorated windows.

BufferedImage in JFrame doesnt Show up

trying to get an image to print into a window. Everything runs without errors, and it also works if I replace the drawImage with another graphics class. However, the window is missing the image, and i'm not sure why. Again, the JFrame stuff and Graphics work fine with drawing other graphics, but only doesn't draw the image here. Thanks.
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.imageio.*;
import javax.imageio.stream.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
public class GraphicsMovement2 extends JApplet{
BufferedImage image = null;
public static void main(String args[]){
BufferedImage image = null;
try {
File file = new File("C:\\Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");
ImageInputStream imgInpt = new FileImageInputStream(file);
image = ImageIO.read(file);
}
catch(FileNotFoundException e) {
System.out.println("x");
}
catch(IOException e) {
System.out.println("y");
}
JApplet example = new GraphicsMovement2();
JFrame frame = new JFrame("Movement");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(example);
frame.setSize(new Dimension(1366,768)); //Sets the dimensions of panel to appear when run
frame.setVisible(true);
}
public void paint (Graphics page){
page.drawImage(image, 100, 100, 100, 100, Color.RED, this);
}
}
You've defined image twice...
BufferedImage image = null;
public static void main(String args[]){
BufferedImage image = null;
This essentially means that by the time you get to the paint method, it is null as you haven't initialized the instance variable.
Another problem you will have is the fact that you are trying to load the image from a static reference but the image isn't declared as static. Better to move this logic into the constructor or instance method.
Don't use JApplet as your container when you're adding to a JFrame, you're better of using something like JPanel. It will help when it comes to adding things to the container.
YOU MUST CALL super.paint(g)...in fact, DON'T override the paint method of top level containers like JFrame or JApplet. Use something like JPanel and override the paintComponent method instead. Top level containers aren't double buffered.
The paint methods does a lot of important work and it's just easier to use JComponent#paintComponent ... but don't forget to call super.paintComponent
UPDATED
You need to define image within the context it is going to be used.
Because you declared the image as an instance field of GraphicsMovement2, you will require an instance of GraphicsMovement2 in order to reference it.
However, in you main method, which is static, you also declared a variable named image.
The paint method of GraphicsMovement2 can't see the variable you declared in main, only the instance field (which is null).
In order to fix the problem, you need to move the loading of the image into the context of a instance of GraphicsMovement2, this can be best achived (in your context), but moving the image loading into the constructor of GraphicsMovement2
public GraphicsMovement2() {
try {
File file = new File("C:\\Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");
ImageInputStream imgInpt = new FileImageInputStream(file);
image = ImageIO.read(file);
}
catch(FileNotFoundException e) {
System.out.println("x");
}
catch(IOException e) {
System.out.println("y");
}
}
The two examples below will produce the same result...
The Easy Way
public class TestPaintImage {
public static void main(String[] args) {
new TestPaintImage();
}
public TestPaintImage() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ImagePane extends JPanel {
public ImagePane() {
setLayout(new BorderLayout());
ImageIcon icon = null;
try {
icon = new ImageIcon(ImageIO.read(new File("/path/to/your/image")));
} catch (Exception e) {
e.printStackTrace();
}
add(new JLabel(icon));
}
}
}
The Hard Way
public class TestPaintImage {
public static void main(String[] args) {
new TestPaintImage();
}
public TestPaintImage() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ImagePane extends JPanel {
private BufferedImage background;
public ImagePane() {
try {
background = ImageIO.read(new File("/path/to/your/image"));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return background == null ? super.getPreferredSize() : new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g.drawImage(background, x, y, this);
}
}
}
}
Take the time to read through the tutorials
Creating a GUI With JFC/Swing
Performing Custom Painting
Your class shouldn't extend JApplet when you're not even using applets -- this makes no sense. Instead
Have your drawing class extend JPanel
Draw in the JPanel's paintComponent method
Add this JPanel to the JFrame's contentPane.
Read the Swing painting tutorials. You can't guess at this stuff and expect it to work, and the tutorials will show you how it's done correctly.
Don't mix file deviders,
File file = new File("C:\\Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");
should be replaced with:
File file = new File("C:/Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");

Categories

Resources