Java ImageIcon.GetImage hanging - java

I am having trouble with ImageIcon().GetImage()
The strange thing is, is that it sometimes works and shows me the window with the maps on it, and other times it doesn't. It also works on other computers flawlessly but not on mine!
I have tried everything, reinstalling Java, reinstalling IntelliJ, also disabling my firewall, but to no avail. I have also written a similar program in C# which works perfectly, which leads me to believe it isn't a permissions error. I have also tested it on a basic Windows XP system with an on board graphics card which also works perfectly.
Here is my code:
public class main {
public static void main(String[] args) {
System.out.println("Running main..");
try
{
URL url = new URL("http://maps.googleapis.com/maps/api/staticmap?center=-33.80382155278416,18.567184266922002&zoom=17&size=1024x1024&maptype=hybrid&sensor=false&format=png&key=AIzaSyCVnp9iTXRSS3ZE5FjzF7uNZavazWhLko4");
Image img=new ImageIcon(url).getImage();
System.out.println("INFO :"+img);
new ImageFrame(img);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static class ImageFrame extends JFrame{
public ImageFrame(Image img){
setPreferredSize(new Dimension(540, 480));
setaImg(img);
ImagePanel somePanel = new ImagePanel(540, 480);
add(somePanel);
setVisible(true);
}
private Image aImg;
public Image getaImg() {
return aImg;
}
public void setaImg(Image aImg) {
this.aImg = aImg;
}
public class ImagePanel extends JPanel{
public ImagePanel(int width, int height){
setPreferredSize(new Dimension(width, height));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(getaImg(), 0, 0, null); // see javadoc for more info on the parameters
}
}
}
}
I have ran it through the step through debugger and it stops at this line:
Image img=new ImageIcon(url).getImage();
But with no error, it just hangs forever.
I am totally confused as to why it isn't working on my system, and only my system. Any help would be GREATLY appreciated.

Works fine for me
Google's not blocking you are they? From memory you have something like 10,000 queries a day or something.
Try downloading the URL manually using the InputStream (URL.openStream()) and see if you're getting some kind of response other than an image binary.
UPDATED
After investigation, found to be a problem with Java 7 and IPv6 as documented here Downloading files using Java randomly freezes

Always start and update the GUI on the EDT. See Concurrency in Swing for more details.
g.drawImage(getaImg(), 0, 0, null); // see javadoc for more info on the parameters
That comment is very good advice, since a 4 char edit should fix the problem.
g.drawImage(getaImg(), 0, 0, this); // Observer is good for asynchronous image load

Related

Different rendering in the simulation or using saveFrame() using Processing in Intellij

After many years with Processing IDE, I missed Intellij IDEA too much so I went back for it but Processing stays on :wink:
However, the shapes drawn are way less sharp than in the real PDE, for example, a simple circle is rendered differently using both time the latest version of Processing available 4.1.2, Java 17, the same PC and the same monitor :
In PDE :
public void setup() {
size(500, 500);
}
public void draw() {
background(40);
noStroke();
fill(255);
circle(width/2, height/2, 400);
saveFrame("./PDE.png");
noLoop();
}
and the result is :
With Intellij however :
import processing.core.PApplet;
public class Main extends PApplet {
public void settings() {
size(500, 500);
}
public void draw() {
background(40);
noStroke();
fill(255);
circle(width/2, height/2, 400);
saveFrame("Intellij IDEA.png");
noLoop();
}
public static void main(String... args) {
Main pt = new Main();
PApplet.runSketch(new String[]{"testRendering"}, pt);
}
}
the saveFrame() is exactly the same as with Processing IDE but the real view in the sketch is :
I guess that it is a problem of renderer but I can't change it using fullScreen(P2D) for example because it throws errors.
The only solution I found were using Maven but I am not so I'd rather find a solution for my problem.
This problem arises because the window is being scaled (according to windows scaling settings) but its content is not rendered in a higher resolution (hence the "jaggies").
It's a problem only with the default (Java AWT) renderer. To fix it:
Call System.setProperty("sun.java2d.uiScale", "1") before PApplet.runSketch() -- this will prevent the window from being scaled.
An alternative solution is to use the JavaFX renderer (size(500, 500, FX2D)), which seems to behave correctly (the content renders at a higher resolution).
If however high DPI scaling is not desired with the FX2D renderer, you can call System.setProperty("prism.allowhidpi", "false")to disable it.

How do I run a JApplet from itself?

Basically I need to do this for school, Ive been through all kinds of posts about this and everyone just says "why'd you wanna do that?" and don't answer. So a lot of people need help on this and your answer could get a lot of likes someday
So here's my class - what couple lines of code do i need to add to main to make this JApplet pop up and draw the bricks into a JApplet window?
public class Wall extends JApplet {
ArrayList<Brick> bricks = new ArrayList<Brick>();
Color[] colors = {Color.decode("#1abc9c"), Color.decode("#f1c40f"), Color.decode("#d35400"), Color.decode("#e74c3c"), Color.decode("#2ecc71"), Color.decode("#3498db"), Color.decode("#9b59b6"), Color.decode("#34495e")};
ArrayList<Integer> usedInts = new ArrayList<Integer>();
public void makeBricks(){
int xPos = 20;
int yPos = 50;
int height = 50;
int width = 60;
for(int i=0; i<8;i++){
Brick b = new Brick();
b.setxPosition(xPos);
xPos =+60;
b.setyPosition(yPos);
if (xPos == 200){
yPos+=50;
}
b.setColor(randomColor());
b.setHeight(height);
b.setWidth(width);
bricks.add(b);
}
}
public Color randomColor(){
Random r = new Random(System.currentTimeMillis());
boolean allAssigned = false;
while(!allAssigned){
int newInt = r.nextInt(8);
if(!usedInts.contains(newInt)){
usedInts.add(newInt);
return colors[newInt];
}
if(usedInts.size()>7){
usedInts.clear();
}
}
return Color.BLACK;
}
public void draw(Graphics g) {
for(Brick b: bricks){
b.draw(g);
}
}
#Override
public void paint(Graphics g){
draw(g);
}
public static void main(String[] args) {
//these lines do not work
Wall wall = new Wall();
wall.makeBricks();
wall.draw();
}
}
JApplet's don't have a window of their own, they are embedded within a web page by a browser. It's possible to use the applet viewer to display them, but you'd need to do that from the command line
Start by creating a custom class the extends from something like JPanel, override it's paintComponent and perform you custom painting there. See Performing Custom Painting for more details.
In your main method, create a new JFrame and add your "game panel" to it...
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new GamePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
If you MUST have a applet, you can now add the "game panel" to it as well
See How to Make Frames (Main Windows) and Using Top-Level Containers for more details
As mentioned by others, applets don't normally have a standalone window. On the other hand, there are at least 3 ways in which an applet can be included in a free floating window:
Run the applet in applet viewer1.1. This should be seriously considered, since the applet viewer is designed to display applets. Better still, it will recreate most of the environment of an applet in a web page, including creating an applet context (from which to get the document or code base, or applet parameters) and a security sand-box.
If you mean 'free floating for the end user'. Launch the applet free floating using Java Web Start. JWS uses the applet viewer (again) to show the applet.
A hybrid application/applet1.2. This is more like you described, an applet with a main(String[]) that creates a wrapper frame for the applet and calls the init() method etc. This is handy for testing simpler (no parameters etc.) applets where the security sand-box just gets in the way.
I also had a site where I provided Appleteer, similar to applet viewer except it would launch multiple applets in a single HTML document, whereas the applet viewer would split them into separate free floating windows (and other slight differences - Appleteer had no security sandbox..). Unfortunately my free hosting for the sites stopped running the web hosting side of the business!
This answer to How to call a paint method inside Applet extended class?
Update 1 has an example of launching an applet in the applet viewer.
Update 2 has an example of creating a hybrid application/applet.

Processing: Sketch gets stuck when using Capture class

I'm using Processing 2.0.3 on Windows 8. I tried to use the following code but I've no idea why my sketch couldn't run when I'm using the processing.video.* library:
import processing.video.*;
Capture cam;
void setup() {
size(200, 200);
cam = new Capture(this);
cam.start();
}
void draw() {
if (cam.available()) {
// Reads the new frame
cam.read();
}
image(cam, 0, 0);
}
I notice that the sketch will get stuck and will not open the sketch applet window at all if I call anything related to the Capture class. Calling println(Capture.list()); for example will cause the sketch to stuck at where ever that line was called.
What do I have to do to resolve this problem?

Java - getImage and drawImage do not work for local files

I am working by way through a tutorial: http://www.kilobolt.com/day-4-enter-the-robot.html
and have been having a problem getting a simple image to display in the applet. I am using IntelliJ 13 Community Edition. The main for loading the images is here:
It does the image setup in the init method:
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
}
// Image Setups
character = getImage(base, "data/character.png").toString());
}
where character is a sprite I obtained from the tutorial website. I saved it in a folder called data. The file structure can be seen here:
When I run this I just see a black background and character.png is not displayed. However if I change the getImage line to:
character = getImage(base, new URL("http://www.kilobolt.com/uploads/1/2/5/7/12571940/character.png").toString());
and point at the URL directly it works. I suspect this must be a path issue but I have not been able to get it working.
I am working on the same program and had the same problem. When run, the document base is actually in KiloboltGame/bin so you need to add your data/character.png here.

How do I remove the 'Applet Started' message in the status bar of Firefox/Chrome on Ubuntu?

This is for a kiosk application where this message is not desired. It's odd because Mac doesn't display this message in either browser -- seems to only happen on Ubuntu.
Using this example applet on Ubuntu 10, Firefox 12, I was able to reproduce the message "Applet initialized," illustrated below. It doesn't appear to be from an overridden init(), and the super implementation is empty; I presume it's a feature of either the plug-in or the browser itself. Oddly, the message actually moves from one lower corner of the browser window to the other, as the mouse cursor approaches it.
For embedded use, consider starting the applet (or hybrid application) via java-web-start as shown in the example.
Addendum: Andrew's example produces the message "Applet started."
Seems like futzing to me, but if by 'status bar' you mean the little bar at the bottom of older browsers, try using Applet.showStatus("") at the end of init() or start().
Edit: Using the following command produces the expected result in appletviwer.
$ appletviewer NoMessageApplet.java
Code:
// intended only to show attributes - view in browser
// <applet code='NoMessageApplet' width=400 height=400></applet>
import java.awt.BorderLayout;
import javax.swing.*;
public class NoMessageApplet extends JApplet {
String noMessage = " Nobody Here But Us Chickens..";
JTextArea output;
#Override
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
initGui();
}
});
} catch(Exception e) {
e.printStackTrace();
}
}
public void initGui() {
JPanel gui = new JPanel(new BorderLayout(5,5));
output = new JTextArea(5,20);
gui.add(new JScrollPane(output));
setContentPane(gui);
setMessage("initGui()" + noMessage);
}
#Override
public void start() {
setMessage("start()" + noMessage);
}
/** Both sets the message as the 'status' message &
appends it to the output control */
public void setMessage(final String message) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
output.append(message + "\n");
}
});
showStatus(message);
}
}
This is not a direct answer to your question but definitely a possible solution to your problem (Was a comment. Added as an answer as suggested by #Andrew Thompson):
If it is a kiosk application then why is there a status bar at all?
If you have control over the system where the application is used from (or where the browser is installed), you can either deactivate the status bar in the browser or make the browser to be displayed always in full screen mode.
Most kiosk applications operate this way.
FF13 fixed it (so does the most recent version of Chrome). Both now currently do not enable status bar's by default (they did when I made this initial post). Not quite an answer, but an answer that worked for me.

Categories

Resources