`Graphics.drawImage()` won't draw - java

Very simply, I could not draw this image.
public class RenderMap extends JPanel {
static BufferedImage brick;
static BufferedImage groundb;
public static void main(String[] args) {
JFrame window = new JFrame("Super Mario");
RenderMap content = new RenderMap();
window.setContentPane(content);
window.setBackground(Color.WHITE);
window.setSize(1200, 800);
window.setLocation(100,0);
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setResizable(false);
window.setVisible(true);
try {
brick = ImageIO.read(new File("SuperMario/brick.png"));
} catch (IOException e) {
}
try {
URL url = new URL("SuperMario/brick.png");
brick = ImageIO.read(url);
} catch (IOException e) {
}
try {
groundb = ImageIO.read(new File("SuperMario/ground.png"));
} catch (IOException e) {
}
try {
URL url = new URL("SuperMario/ground.png");
groundb = ImageIO.read(url);
} catch (IOException e) {
}
}
public Ground ground;
public RenderMap() {}
public void paintComponent(Graphics g) {
if(ground == null) {
ground = new Ground();
}
ground.draw(g);
}
public class Ground implements ImageObserver {
Ground(){}
void draw(Graphics g) {
g.drawImage(groundb, 0, 0, 1200, 800, this);
g.fillOval( 8, 8, 16, 16);
}
#Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
// TODO Auto-generated method stub
return false;
}
}
}
This draws the oval, but not the image. I tried changing to another image(that is functioning in another program) and it still won't work, so I know it's not the image's problem.

As suspected, the images are not being loaded properly.
java.net.MalformedURLException: no protocol: SuperMario/brick.png
at java.net.URL.<init>(URL.java:586)
at java.net.URL.<init>(URL.java:483)
at java.net.URL.<init>(URL.java:432)
at RenderMap.main(RenderMap.java:40)
java.net.MalformedURLException: no protocol: SuperMario/ground.png
at java.net.URL.<init>(URL.java:586)
at java.net.URL.<init>(URL.java:483)
at java.net.URL.<init>(URL.java:432)
at RenderMap.main(RenderMap.java:51)
It's failing at the load-by-URL function calls because you passed in an invalid URL. Correct URL format should be like how you access them from a web browser, like: http://someplace.com/SuperMarioFolder/brick.png
To load the images, choose only one way to read them. Either by:
URL - Remove the File blocks and make the file accessible via full URL.
try {
URL url = new URL("http://www.proper-url.com/SuperMario/ground.png");
groundb = ImageIO.read(url);
} catch (IOException e) { }
File - Remove the URL blocks. This will only allow the program to access local files.
try {
groundb = ImageIO.read(new File("SuperMario/ground.png"));
} catch (IOException e) {
}
For your project's purpose, I believe option#2 would suffice.
Moving forward, you may want to use an IDE's debugging feature to go through code execution step-by-step. If you're not using one, you may want to IntelliJ and Eclipse.

Related

Image is not showing when Java program is running

Whenever I run the program, the background image is not visible, it is just a white blank space. I tried following the instructions on this website -> https://www.tutorialspoint.com/how-to-add-background-image-to-jframe-in-java, but is not working. I tried the getImage method and provided the file path towards that image. Can someone please explain what is wrong with my code and how to fix it?
public class MainForm extends JFrame {
Image img = Toolkit.getDefaultToolkit().getImage("C:\\Users\\Jack\\Desktop\\Folder\\Course\\Draft repo");
public MainForm() throws IOException {
this.setContentPane(new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
}
});
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new MainForm();
} catch (IOException ex) {
Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
according to: How do I draw an image to a JPanel or JFrame? ,
instead of using
Image img = Toolkit.getDefaultToolkit().getImage("C:\\Users\\xxxx\\Path\\image.jpg");
try to use:
BufferedImage img = ImageIO.read(new File("C:\\Users\\xxxx\\Path\\image.jpg"));
Do not forget to indicate the correct path to the file and the file itself with the extension.

Needing JAVA help in animation

I'm new in Java (still learning) all the other works have gone well but only this animation gives my headache and the coffee won't even help=(!
I should make an animation of Javaman (10 gif pictures named as T1, T2,...T10) I should use Thread, MediaTracker-class and addImage-method. Then I should specify the speed of the animation by using sleep-method (I used join-method if that's right??).
(MY JAVA CODE GOES LIKE THIS)
import java.applet.Applet;
import java.awt.*;
public class Animaatio extends Applet implements Runnable {
Image[] images = null;
MediaTracker tracker = null;
int current = 0;
Thread animThread;
#Override
public void init() {
// Creating a new media tracker, to track loading images
tracker = new MediaTracker(this);
// Creating an array of ten images
images = new Image[10];
// Downloading the images
for (int i = 0; i < 10; i++) {
// Loading the images
images[i] = getImage(getCodeBase(), (i + 1) + "T.gif");
tracker.addImage(images[i], 0);
}
try {
tracker.waitForAll();
} catch (InterruptedException e) {
}
}
#Override
public void start() {
if (animThread == null) {
animThread = new Thread(this);
animThread.start();
}
try {
animThread.join();
} catch (InterruptedException e) {
}
}
#Override
public void paint(Graphics g) {
g.drawImage(images[current++], 0, 0, this);
}
#Override
public void run() {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
}
}
The problem is that I don't see any animation just an empty applet viewer which just keeps running. Problem might be caused if the images are storaged in the wrong place? If someone could wreally help me, I would be really thankful for my knight=).

Creating new Thread to update JLabel and setIcon() in said separate Thread

Trying to get an image from another application sending an array of bytes through socket, translating it to a BufferedImage and setting a JLabel in the GUI that updates every 3 seconds.
I tried looking it up on forums but questions regarding graphical update are recurrent to me and I never seem to get it right -- there's at least 6 update methods in java for graphical interface and every one I tried won't work.
I know the problem isn't in the connection to the client because I can easily save the image I receive with ImageIO.write() and it updates every 3 seconds to the image I was expecting to receive. I just can't have Java updating the JLabel correctly without having to go to forums and ask people. Such a complex task I guess. Here is the code: http://pastebin.com/95nMGLvZ. I am doing this project in Netbeans so there's a lot of stuff in there that is unnecessary to read as it does not directly relate to the problem.
I think the answer lies in creating a separate thread to update my JLabel from the ever-changing BufferedImage that is received from the ObjectInputStream. Anyone mind giving me a hand at this? What is better for my code? SwingWorker, Threading (wtf is setDaemon(flag)?), Runnable, Timer, invokeLater? Tried all of this. Not correctly apparently.
EDIT1:
Tried your answer immibis:
public void startRunning() {
try {
server = new ServerSocket(666, 10);
connection = server.accept();
networkStatus("Connected to " + connection.getInetAddress().getHostName());
Thread thr = new Thread(new Runnable() {
#Override
public void run() {
try {
input = new ObjectInputStream(connection.getInputStream());
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
}
});
thr.start();
System.out.println(!connection.isInputShutdown());
while (connection.isConnected()) {
try {
byte[] byteImage = (byte[]) input.readObject();
InputStream in = new ByteArrayInputStream(byteImage);
final BufferedImage bi = ImageIO.read(in);
jLabel_screen.setIcon(new ImageIcon(bi));
ImageIO.write(bi, "jpg", new File("C:\\Users\\User\\Desktop\\test.jpg"));
System.out.println("i'm working");
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
} catch (ClassNotFoundException ex) {
Logger.getLogger(SpyxServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
}
It does not work. It says byte[] byteImage = (byte[]) input.readObject(); line has a NullPointerException. The only value that can be null is the return from readObject(), meaning either the input was not initialized correctly or the connection is not synchronized. I hope it's the first option because I wouldn't know how to handle the last.
EDIT2:
Tried your answer blazetopher:
public void startRunning() throws IOException {
server = new ServerSocket(666, 10);
try {
connection = server.accept();
networkStatus("Connected to " + connection.getInetAddress().getHostName());
input = new ObjectInputStream(connection.getInputStream());
while (true) {
try {
byte[] byteImage = (byte[]) input.readObject();
InputStream in = new ByteArrayInputStream(byteImage);
final BufferedImage bi = ImageIO.read(in);
SwingUtilities.invokeLater(new Runnable() {//<-----------
#Override
public void run() {
jLabel_screen.setIcon(new ImageIcon(bi));
}
});
ImageIO.write(bi, "jpg", new File("C:\\Users\\User\\Desktop\\test.jpg"));
System.out.println("i'm working");
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
} catch (ClassNotFoundException ex) {
Logger.getLogger(SpyxServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (EOFException eofException) {
networkStatus("Connection Closed. :(");
} finally {
input.close();
connection.close();
}
}
Using SwingUtilities.invokeLater didn't work either. At least the program runs and can even save the image but still can't update the JLabel. Am I running out of options here?
EDIT3:
Tried Jordan's code:
#Override
public void paint(Graphics g) {
g.drawImage(biGlobal, 0, 0, null);
}
The GUI kind of crashed and was "drawing" the components just when I had my mouse cursor hovering it. When I started the code, it did not crashed (+1) but it did not draw anything, even when I try to hover the cursor into where the BufferedImage should be painted. Maybe I should add revalidate() or repaint after calling the Overwritten paint(getGraphics()) inside the startRunning() method?
EDIT4: the while(true) that the code is actually in may be the problem but when I use a SwingTimer it gets out of sync with the client and crashes after first cycle. Any alternatives to this?
Generally speaking you have a producer/consumer pattern. Something is producing images and something wants to consume images. Normally, the consumer would wait on the producer to tell it something has been produced, but in this case, we can use a observer pattern instead, having the producer notify the consumer that something was been produced (instead of waiting for it)
We need someway for the producer to communicate with the consumer...
public interface PictureConsumer {
public void newPicture(BufferedImage img);
}
You would create an implementation of this in your UI code, this would then set the icon property of the JLabel
Now, we need something to produce the images...
public class PictureProducer extends SwingWorker<Object, BufferedImage> {
private PictureConsumer consumer;
public PictureProducer(PictureConsumer consumer) {
this.consumer = consumer;
}
#Override
protected void process(List<BufferedImage> chunks) {
// Really only interested in the last image
BufferedImage img = chunks.get(chunks.size() - 1);
consumer.newPicture(img);
}
#Override
protected Object doInBackground() throws Exception {
/*
This whole setup worries me. Why is this program acting as the
server? Why aren't we pooling the image producer?
*/
try (ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(666, 10)) {
try (Socket socket = server.accept()) {
try (ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {
// Using `while (true)` is a bad idea, relying on the fact
// that an exception would be thrown when the connection is closed is
// a bad idea.
while (!socket.isClosed()) {
// Generally, I'd discourage using an ObjectInputStream, this
// is just me, but you could just as easily read directly from
// the ByteArrayInputStream...assuming the sender was sending
// the data as a byte stream ;)
byte[] bytes = (byte[]) ois.readObject();
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes)) {
BufferedImage img = ImageIO.read(bis);
publish(img);
}
}
}
}
}
return null;
}
#Override
protected void done() {
try {
get();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Image Producer has failed: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
See Worker Threads and SwingWorker for more details
You can a reverse example of this (where some server is producing images and a client is consuming them) here
To update your label, you want to ensure you're using the EDT thread, so use SwingUtilities.invokeLater from the code where you're receiving the BufferedImage (which would ideally be in a separate "worker" thread:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// Update your label here
}
});
What is it you are attempting to accomplish.there might be a better way all together.
For example replace the JLabel with a JPanel then use that JPanel paint method
#Override
public void paint(Graphics g) {
g.drawImage(Img, xcord, ycord, null);
}
Then make that JPanel implement runnable and do your updates in that run method.
JPanel class
public class GraphicsPanel extends JPanel{
private BufferedImage img;
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D G2D = (Graphics2D) g;
G2D.drawImage(img, 0, 0, null);
}
public void setImg(BufferedImage img) {
this.img = img;
}
}
then make sure this panel is visible from wherever you wish to call its methods.
this will look something like this
GraphicsPanel graphicsPanel = new GraphicsPanel();
boolean running;
BufferedImage srcImage;
public void run(){
while(running){
graphicsPanel.setImg(srcImage);
graphicsPanel.repaint();
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Java Applets and Proxies

Assuming that I use the following code to connect to a SOCKS5 proxy, would connections or packets sent by an applet that I instantiate go through the same proxy?
System.getProperties().setProperty("socksProxySet", "true");
System.getProperties().setProperty("socksProxyHost", "*.*.*.*");
System.getProperties().setProperty("socksProxyPort", "*");
Applet is started using a classloader object from which a newInstance is created.
classLoader = new CustomClassLoader(/* Hashmap of byte arrays */); // Custom classloader that works using byte arrays
Applet applet = (Applet) classLoader.loadClass("class").newInstance();
applet.setStub(stub);
applet.init();
applet.start();
frame.add(applet);
It appears that the answer to this question is yes.
The following code:
public class TestApplet extends Applet {
private String ip;
public void init() {
try {
URL ipCheck = new URL("http://checkip.amazonaws.com");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ipCheck.openStream()));
ip = bufferedReader.readLine();
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stop() {
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.CYAN);
g.drawString("Current IP: " + ip, 10, 20);
}
}
and
public class Boot {
public static void main(String[] args) {
System.getProperties().setProperty("socksProxySet", "true");
System.getProperties().setProperty("socksProxyHost", "71.9.127.141"); //Credits to HideMyAss.com
System.getProperties().setProperty("socksProxyPort", "28045");//Credits to HideMyAss.com
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
TestApplet testApplet = new TestApplet();
testApplet.init();
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jFrame.setSize(500, 500);
jFrame.setContentPane(testApplet);
jFrame.setVisible(true);
}
}).start();
}
}
Outputs:
Tyler, if I understand your question correctly - yes. But this comes with a caveat: the System properties that you set will persist only across the current JVM instantiation.
So, if like your example shows you set the properties and execute the Applet on the same JVM you should be fine.

BufferedImage goes black when used as method parmeter

I've got what seems like a very simple section of code, and I can't work out for the life of me why it's not working.
I have a method that listens for image updates from a camera and when it recieves them it calls another segment of code.
My listener is:
public void imageUpdated(BufferedImage image) {
if (null != video) {
video.setImage(image);
}
File outputfile = new File("savedingui.jpg");
try {
ImageIO.write(image, "jpg", outputfile);
} catch (IOException e) {
e.printStackTrace();
}
Which happily saves the correct image to disc. However when I save the image again from the setImage method (called on line 3 of the listener code)
public void setImage(BufferedImage image) {
File outputfile = new File("savedorig.jpg");
try {
ImageIO.write(image, "jpg", outputfile);
} catch (IOException e) {
e.printStackTrace();
}
It now just saves a jpeg of black. But the right sized square of black.
Any clues as to whats going on?
I can not reproduce your issue with the following source (which is basically copied from your question):
public static void imageUpdated(BufferedImage image) {
setImage(image);
File outputfile = new File("savedingui.jpg");
try {
ImageIO.write(image, "jpg", outputfile);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void setImage(BufferedImage image) {
File outputfile = new File("savedorig.jpg");
try {
ImageIO.write(image, "jpg", outputfile);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
BufferedImage image = ImageIO.read(new File("test.jpg"));
imageUpdated(image);
}
Is the same instance used somewhere else, e.g. camera writing updated data in it?

Categories