Java Hello World App Does Nothing on Launch When Image Displayed - java

I've got a small "hello world" app I've created, using JFrame/JPanel, and it works flawlessly inside my IDE (Netbeans). I tested it with just drawing a string to the screen using Graphics.drawString(), and it worked perfectly both in the browser, and in the built .Jar file.
I decided to add in an image just to test it out (I'm new to Java), and the App continued to function inside the IDE, but the built .Jar file doesn't launch anything, or give an error or anything.
Here are the 2 class files:
Boxy_Main.java:
package boxy;
import javax.swing.JFrame;
import java.awt.*;
public class Boxy_Main extends JFrame {
public static Boxy_Main main;
public Boxy_Main() {
add(new Board());
setTitle("Boxy");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(467, 700);
setLocationRelativeTo(null);
setVisible(true);
setResizable(true);
}
public static void main(String[] args) {
main = new Boxy_Main();
}
}
Board.java:
package boxy;
import javax.swing.JPanel;
import java.awt.*;
import javax.swing.*;
public class Board extends JPanel {
public Graphics2D g2d;
public Graphics g;
public Image hello_image;
public Board() {
this.set_properties();
}
public void set_properties() {
this.hello_image = new ImageIcon(Board.class.getResource("../images/LKRZV.jpg")).getImage();
}
public void paint(Graphics g) {
this.g = g;
this.g2d = (Graphics2D) g;
this.g2d.drawImage(this.hello_image, null, this);
this.g.drawString("hello", 100, 80);
this.g.drawString("world", 100, 94);
}
}
If I comment out
this.hello_image = new ImageIcon(Board.class.getResource("../images/LKRZV.jpg")).getImage();
and
this.g2d.drawImage(this.hello_image, null, this);
it continues to work perfectly.
I've tried to figure this out myself, I can't find anything via google or stack overflow. It is a difficult search phrase to craft.
Anyone have any ideas why this would run in NetBeans, but not as a standalone .Jar?

Your issue is in this line
this.hello_image = new ImageIcon(Board.class.getResource("../images/LKRZV.jpg")).getImage();
The "../images.LKRZV.jpg" path is correct when you're running in NetBeans, but it isn't correct when you run your JAR. Make sure you provide a provide a path that is correct relative to your jar file's location. If you change that path to the absolute path of your image, your program should work correctly. It would probably be better to pack the image in with the jar.

Related

Graphics 2D not drawing images in Java

I'm following a Java course, and the current idea is to draw an image using Java Graphics2D. I'm following the steps one by one, but it seems not to be drawing anything. The panel is shown within the frame and everything is correct, but the image is not drawn. I'm using Java 15 and the course is Java 13.
JPanel class code:
public class MyPanel extends JPanel implements ActionListener {
Image ball;
int x = 0;
int y = 0;
MyPanel(){
this.setPreferredSize(new Dimension(PANEL_WIDTH,PANEL_HEIGHT));
this.setBackground(Color.BLACK);
ball = new ImageIcon("ball.png").getImage();
}
public void paint(Graphics g){
Graphics2D G2D = (Graphics2D) g;
G2D.drawImage(ball,x,y,null);}
JFrame class code:
public class MyFrame extends JFrame{
MyPanel panel;
MyFrame(){
panel = new MyPanel();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(panel);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
Main class code:
new MyFrame();
I picked out most of the relevant code.
First, I recommend reading through Performing Custom Painting and Painting in AWT and Swing to get a better idea of how painting in Swing should work.
I then suggest reading through Reading/Loading an Image
The "problem" with ImageIcon is that
It doesn't report any errors if the load fails
It loads the image in a second thread, which means you don't know (easily) when it's available
ImageIO on the hand will throw an error if the image can't be loaded, which is much easier to diagnose, and will only return AFTER the image is fully loaded and available.
One concept which can be hard to grasp when your starting is the concept of "embedded" resources. Java allows you to package "resources" along with your code. These resources live within the context of your programs class path and make it MUCH easier to load when compared to having to deal with external files.
Have a look Packaging and accessing run-time resources in a runnable Jar for some basics.
Depending on the IDE you're using, it's usually pretty easy to "copy" these resources into your project/src and allow the IDE to package itself.
The problem with a question like this is it's very, very hard for anyone to truely diagnose, as there are so many reasons why the image might not have loaded and the solution is usual one of trial and error.
Me, I'd start by just drawing some lines/rectangles and make sure that paint is been called. I'd then look at things like the image's size, to make sure it's not something like 0x0.
Runnable example
This is a simple runnable example based on comments I made above. I'm using NetBeans and the image was stored in the "Source Package" (so, along with the other source code) under the /images package
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage beachBall;
public TestPane() {
try {
beachBall = ImageIO.read(getClass().getResource("/images/BeachBall.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (beachBall == null) {
return;
}
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - beachBall.getWidth()) / 2;
int y = (getHeight() - beachBall.getHeight()) / 2;
g2d.drawImage(beachBall, x, y, this);
g2d.dispose();
}
}
}
It really looks like your image is not loaded.
As #MadProgrammer just told, new ImageIcon("ball.png") does not raise any error, and getImage() will always return something (not null), even if the file is not properly loaded.
To make sure your image is available, you can try ball.getWidth(null), and
if it returns -1, then something went wrong.
You can check the root path used by the JVM ("execution" location) with System.getProperty("user.dir"), the image file has to be exactly in this folder.
I tried your code with java 1.8 and it works well.

Images in Java coming up NPE

I was trying out putting images in java. My end goal is to make a image I can control with arrow keys, but I can't seem to put an image in. I imported the image, and I have the name correct. I keep getting a null pointer exception.
code:
import java.awt.*;
import javax.swing.*;
public class Test extends JPanel {
public static ImageIcon image;
public void paintComponent(Graphics g) {
super.paintComponent(g);
image = new ImageIcon(getClass().getResource("rocketJava.jpg"));
image.paintIcon(this,g, 20, 20);
}
public static void main(String[] args) {
JFrame f= new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Test s = new Test();
f.add(s);
f.setSize(600,600);
f.setVisible(true);
}
}
The problem was just that I needed to move the picture file to the bin folder.

Error: class X is public, should be declared in file named X

I am searching for a Java compiler that I can use online that includes a graphic output and can support swing, I'm new to this however and I am unsure of what the problem is, I've searched up a simple draw circle program, and I use it to test whether the compiler has a graphic output and supports swing or not, currently, I've stumbled across a website that seems to support graphic outputs but I get an error saying that the class is public and should be in a file, any help or suggestions for compilers?
The website is https://www.codechef.com/ide# Any downloaded compilers are too complex for a beginner like me to navigate around :/
My code is below:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class DrawCircle extends Frame //this is the place of error
{
Shape circle=new Ellipse2D.Float(100.0f,100.0f,100.0f,100.0f);
public void paint(Graphics g)
{
Graphics2D ga=(Graphics2D)g;
ga.draw(circle);
ga.setPaint(Color.blue);
ga.fill(circle);
}
public static void main(String args[])
{
Frame frame=new DrawCircle();
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
frame.setSize(300, 250);
frame.setVisible(true);
}
}

My Window is Forced to Maximized on Java Applet/JFrame

I've tried running both an Applet and a JFrame following certain YouTube tutorials, but when they run on my computer, they ignore the size I specify for the window, and forcibly open maximized and will simply not resize.
Here's a simple example Applet I ran:
package pong;
import java.applet.Applet;
import java.awt.*;
public class Pong extends Applet{
final int WIDTH = 700, HEIGHT = 500;
public void init() {
this.resize(WIDTH, HEIGHT);
}
public void paint(Graphics g) {
}
public void update(Graphics g) {
}
}
I cannot resize the window/panel. I don't know if this is an issue with my computer Yoga 2 Pro.
Any help is greatly appreciated.
EDIT: I think perhaps I wasn't clear enough. I am simply not managing to correctly view ANY JPanel or Applet. They display on my Yoga 2 Pro as maximized, and with their content being strange as well. In this example I'm simply trying to get a 700x500 window, but Java ignores this fact on my computer.
Thanks

Making a Java panel fullscreen

How would you make a JComponent (panel, frame, window, etc.) fullscreen, so that it also overlaps everything on the screen including the windows start bar?
I don't want to change the resolution or anything with the graphics device like bitdepth etc, I just want to overlap everything else.
Check out this tutorial describing Java's Full-Screen mode API.
Example code (taken from the tutorial). Note that the code operates on a Window so you would need to embed your JPanel with a Window (e.g. JFrame) in order to do this.
GraphicsDevice myDevice;
Window myWindow;
try {
myDevice.setFullScreenWindow(myWindow);
...
} finally {
myDevice.setFullScreenWindow(null);
}
You can try some of the codes in this page, allowing a container to fill the screen (so it is not a solution for an individual component, but for a set of components within a container like a JFrame)
public class MainWindow extends JFrame
{
public MainWindow()
{
super("Fullscreen");
getContentPane().setPreferredSize( Toolkit.getDefaultToolkit().getScreenSize());
pack();
setResizable(false);
show();
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
Point p = new Point(0, 0);
SwingUtilities.convertPointToScreen(p, getContentPane());
Point l = getLocation();
l.x -= p.x;
l.y -= p.y;
setLocation(l);
}
});
}
...
}
You need to use the following API: http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html
Going full screen isn't as simple as making a large panel, you need to look into the underlying OS graphics. But your JPanel code should translate just fine.
I needed to search a lot, to do the same. Here is completely a working version of it by steps, so that i can find it later also, and use it.
Step 1: create a file called fullscreen.java
Step 2: copy this code and paste it as it is:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class fullscreen extends Window
{
private Button button;
public fullscreen()
{
super(new Frame());
button = new Button("Close");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
setLayout(new FlowLayout());
add(button);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0,0,screenSize.width, screenSize.height);
}
public static void main(String[] args)
{
// This will take over your whole screen tested and works in my:
// Fedora 12/13/14
// CentOS 5.0
// if this works for you, in other platforms, please leave a comments which OS it worked.
// happy coding!
new fullscreen().setVisible(true);
}
}
Step 3: compile the code and run
Done.
If I were you I would try to make Java not draw the border of the Jframe, then make it take all the screen.
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import javax.swing.JFrame;
public class FenNoBorder extends JFrame {
public FenNoBorder () {
setUndecorated(true);
setVisible(true);
GraphicsEnvironment graphicsEnvironment=GraphicsEnvironment.getLocalGraphicsEnvironment();
Rectangle maximumWindowBounds=graphicsEnvironment.getMaximumWindowBounds();
setBounds(maximumWindowBounds);
}
}

Categories

Resources