KeyListener is unresponsive 1st time used? - java

I looked at these links, none helped me. Im making a game with a JFrame using KeyListener and Runnalbe. I've never had a problem with it in games i have made in the past, but now heres what im talking about:
i start my program and the window comes up, message displays everything looks fine.
no keys work
-i close the window
-The 2nd time its opened everything works fine.
-If i reset the virtual machine and try again, back to square 1.
here is my constructor:
public Game()
{
super("ZMan");
addKeyListener(this);
setSize(800,600);
setVisible(true);
i = createImage(800,600);
b = i.getGraphics();
makeLevel();
souls = new Image[3];
particles = new double[20][3];
pc = 10;
pH = 20;
player = new Image[8];
nme = new Image[8];
showMessage = false;
try
{
bg = ImageIO.read(new File("bg.png"));
abg = ImageIO.read(new File("abg.png"));
bil = ImageIO.read(new File("buildingP.png"));
bilP = ImageIO.read(new File("building.png"));
message = ImageIO.read(new File("./system/messageBG.png"));
souls[2] = ImageIO.read(new File("sR.png"));
souls[1] = ImageIO.read(new File("sG.png"));
souls[0] = ImageIO.read(new File("sB.png"));
rem = souls[0];
//player
player[0] = ImageIO.read(new File("./player/normal.png"));
player[1] = ImageIO.read(new File("./player/pBloop.png"));
player[2] = ImageIO.read(new File("./player/pscorp.png"));
player[3] = ImageIO.read(new File("./player/pSqui.png"));
player[4] = ImageIO.read(new File("./player/pCato.png"));
player[5] = ImageIO.read(new File("./player/pChubs.png"));
player[6] = ImageIO.read(new File("./player/pPluckers.png"));
player[7] = ImageIO.read(new File("./player/pSpooky.png"));
gate = ImageIO.read(new File("./gate.png"));
levelUp = ImageIO.read(new File("./system/levelUp.png"));
xL = ImageIO.read(new File("./player/x.png"));
/*
nme[0] = ImageIO.read(new File("./enemies/bloop.png"));
nme[1] = ImageIO.read(new File("./enemies/bloop.png"));
nme[2] = ImageIO.read(new File("./enemies/scorp.png"));
nme[3] = ImageIO.read(new File("./enemies/squi.png"));
nme[4] = ImageIO.read(new File("./enemies/cato.png"));
*/
nme[0] = Toolkit.getDefaultToolkit().createImage("./enemies/bloob.png");
nme[1] = Toolkit.getDefaultToolkit().createImage("./enemies/bloob.png");
nme[2] = Toolkit.getDefaultToolkit().createImage("./enemies/scorp.png");
nme[3] = Toolkit.getDefaultToolkit().createImage("./enemies/squi.png");
nme[4] = Toolkit.getDefaultToolkit().createImage("./enemies/cato.png");
nme[5] = Toolkit.getDefaultToolkit().createImage("./enemies/chubs.png");
nme[6] = Toolkit.getDefaultToolkit().createImage("./enemies/pluckers.png");
nme[7] = Toolkit.getDefaultToolkit().createImage("./enemies/spooky.png");
}
catch(Exception e){e.printStackTrace();}
powerT = new String[8];
powerT[0] = "You went back to normal";
powerT[1] = "You are now Bloop!";
powerT[2] = "You are now Scorp!";
powerT[3] = "You are now Squi!";
powerT[4] = "You are now Cato!";
powerT[5] = "You are now Chubs!";
powerT[6] = "You are now Pluckers";
powerT[7] = "You are now Spooky";
startAim();
//music = new Music("./system/music/0.wav");
t.start();
}
does nyone know the problem?

"To fire keyboard events, a component must have the keyboard focus."—How to Write a Key Listener. I'm guessing the relevant component has focus the second time. You can try requestFocusInWindow() or, preferably, look at How to Use Key Bindings.
Addendum: There's a key binding example here.

This may sound dumb, but it's more of a sanity check. Check your main method. I'd recommend doing a debug stepthrough, making sure that the first time the window is launched, the constructor to Game is actually called...Nothing about the constructor appears to be bad (to me), which makes me think that the instantiation of the object might be hosed.
If it isn't that, I can't help you; you'll have to wait for someone smarter in the specifics of your problem to answer :)

Related

How do i put a icon to jLabel

By default it has an image with the path /img/profileicon/29.png
but then from the main I want to change it, but for some reason instead of changing it disappears.
The code:
int iconId = summoner.getProfileIconId();
ImageIcon img = new javax.swing.ImageIcon("/img/profileicon/"+iconId+".png");
profileIconImg.setIcon(img);
Finally I was able to use this code, making use of class.getResource
URL iconUrl = EuwGG.class.getResource("/img/profileicon/"+profileIconId+".png");
Image profileImage = ImageIO.read(iconUrl);
ImageIcon profileIcon = new ImageIcon(profileImage);
Image i = profileIcon.getImage().getScaledInstance(125, 125, Image.SCALE_SMOOTH);
profileIcon = new ImageIcon(i);
profileIconImg.setIcon(profileIcon);

How to display a jpeg2000 image on a Jframe?

I have a jpeg2000 image, img.jp2 on a file, and on a DataInputStream object imgobj in my project, and want to show that image on a JFrame.
The old version jai_imageio-1.1.jar recommended here and the jj2000 library are both included.
I have tried:
j2kImageReader.setInput(new FileImageInputStream(new File(fileName)));
ImageReadParam imageReadParam =
j2kImageReader.getDefaultReadParam();
imageReadParam.setSourceRegion(new Rectangle(0, 0, 300, 300));
IIOImage image = j2kImageReader.readAll(0, imageReadParam);
// This type of images is difficult to handle,
// I just don't know what to do with IIOImage,
// ImageIcon doesn't accept that type in its constructor.
And this:
Image img = ImageIO.read(new File(fileName));
ImageIcon imgIcon = new ImageIcon(img);
JLabel label = new JLabel(imgIcon);
panel1.add(label);
panel1.repaint();
//Error: Can't read input file!. The panel is still empty
The option included in JMRTD is using two decoders, and no one of them accepts .jp2:
NistDecoder dec=new NistDecoder();
WsqDecoder wdec=new WsqDecoder();
//using the last one, I tried: bitmp= wdec.decode(myDataInputStream);
//but with Error, Invalid pointer : 0!.
So the question is: what is the proper use of jj2000 or jai_imageio to read a jpeg2000 image from a file or a DataInputStream, and if it is possible, to show it on a simple panel on a JFrame?
Thank you for help.
EDIT
AS requested in comments, this is what I did:
//1
FaceImageInfo imgfn = fsinf.getFaceImageInfos().get(0);
BufferedImage bf=ImageIO.read(imgfn.getImageInputStream());
ImageIcon iconImg = new ImageIcon();
iconImg= new ImageIcon(bf);// if this fails try write it to a stream and read it back see //2
JLabel(iconImg, JLabel.CENTER);
//2
ByteArrayOutputStream baos=null;
try{
baos=new ByteArrayOutputStream();
ImageIO.write(bf, "jpg", baos);
}
finally{
try{
baos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
try {
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
bf2=ImageIO.read(bais) ;
iconImg= new ImageIcon(bf2);
JLabel(iconImg, JLabel.CENTER);
} catch (Exception e) {
e.printStackTrace();
}
Assuming the code otherwise reads the image like you want it, you can easily get a BufferedImage from the ImageReader like this:
try (ImageInputStream input = ImageIO.createImageInputStream(new File(fileName))) {
j2kImageReader.setInput(input));
// Not sure why/if you want to read only the upper left, but I'll leave it as is
ImageReadParam imageReadParam = j2kImageReader.getDefaultReadParam();
imageReadParam.setSourceRegion(new Rectangle(0, 0, 300, 300));
// Use read instead of readAll
BufferedImage image = j2kImageReader.read(0, imageReadParam);
// You can now create an icon and add to a component
Icon icon = new ImageIcon(image);
JLabel label = new JLabel(icon);
// Etc...
}

set size of image after retrieving from json

I want to set the size of image get through json service. ???
Here is my code
public void getImage(){
try {
URL url = new URL("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=good%20idea%20good%20idea%20water%20jug%20water%20jug%20thirsty%20crow%20thirsty%20crow%20long%20time%20long%20time%20jug%20jug");
URLConnection connection = url.openConnection();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject json = new JSONObject(builder.toString());
String imageUrl = json.getJSONObject("responseData").getJSONArray("results").getJSONObject(0).getString("url");
BufferedImage image = ImageIO.read(new URL(imageUrl));
ImageIcon img = new ImageIcon(image);
JLabel label = new JLabel("", img, JLabel.CENTER);
jPanel1.add( label, BorderLayout.CENTER );
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Failure", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
I am showing the image in a jPanel.I want to set the size of image so it must be smaller than panel size. How could I achieve this ????
If you don't care about the quality of the result, you could use Image#getScaledInstance, but you should have a read of The Perils of Image.getScaledInstance() of first
Image scaled = image.getScaledInstance(jPanel1.getWidth(), jPanel1.getHeight(), Image.SCALE_SMOOTH);
But this won't maintain the aspect ratio of the image, to do that, you'd have to decide which dimension is more important
int width = jPanel1.getWidth();
int height = jPanel1.getHeight();
if (width < height) {
height = -1;
} else {
width = -1;
}
Image scaled = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
Have a look at Java: maintaining aspect ratio of JPanel background image for more details
Now, if you do care about the quality of the resulting image, then you need to use a different scaling approach, you could use something like a divide and conqure approach, as demonstrated in Quality of Image after resize very low -- Java or use a 3rd party library, like ImgSclr
Now, you next problem is, the size of a component is generally calculated based on the needs of it's children. In this case, that means that jPanel1 may want to use the size of the JLabel to determine how large it should be. Equally, the JLabel will use the size of the image to determine how large it should be. Which puts you in a catch 22 problem.
You could use a JScrollPane which will allow the image to occupy a large area then is available or you will need a dynamic panel which can resize the image automatically based on the available space, but you would still need to make a determination of what the "default" or "preferred" size should be
try this:
resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);

Cursor blinking while taking capture screen

I use this code to make 100 screen captures:
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
for(int i = 0; i < 100; i++){
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "jpg", new File("D:/pictures/pic" + i + ".jpg"));
}
Why is the cursor blinking when are taking the captures? Is something wrong in my code?
No, there is nothing wrong with your code. From the Javadocs:
This image does not include the mouse cursor.
So Java hides the cursor momentarily in order to take the screenshot, then it makes it visible again.

Merging BufferedImages leaves black border

For a class project, we were required to take a program that implements the Sobel algorithm and run it across multiple threads as an exercise to become familiar with threading. I have the program running correctly as far as threads go (as far as I can tell), however whenever I implement it using more than 1 thread, I see a black border running down the dividing area where the buffer doesn't seem to be writing to the destination BufferedImage.
Here is some code of the method responsible for threading and writing the file:
public void processImage(int threads)
{
try{
File imgFile = new File(bmpFile);
image = ImageIO.read(imgFile);
w = image.getWidth();
wThr = (image.getWidth()/threads);
h = image.getHeight();
inData = new int[wThr*h];
BufferedImage[] pieces = new BufferedImage[threads];
//instantiate array used for storing pieces of image
for (int i=0; i<threads; i++){
pieces[i] = new BufferedImage(wThr, h, BufferedImage.TYPE_BYTE_GRAY);
}
wThr = pieces[0].getWidth();
h = pieces[0].getHeight();
//instantiate target image
combined = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
//split into threads, each one taking a division of the image and running algorithm
Thread[] threadList = new Thread[threads];
for (int i = 0; i < threadList.length; i++) {
image.getRaster().getPixels((i*wThr), 0, wThr, h, inData);
threadList[i] = new Pr1();
threadList[i].start();
try{
threadList[i].join();
}catch (InterruptedException ie) {}
//Write images to pieces and draw pieces individually onto target image
pieces[i].getRaster().setPixels(0, 0, wThr, h, outData);
Graphics2D g = combined.createGraphics();
g.drawImage(pieces[i], i*(wThr), 0, null);
g.dispose();
}
outFile = new File("1.bmp");
ImageIO.write(combined, "BMP", outFile);
}
catch(IOException e)
{
// Handle the exception here!
}
}
This is the image when processed with 2 threads: http://i.imgur.com/n5gasAW.png?1
Anyone have any insight on how to repair this? I've altered the parameters of the BufferedImages and arrays every way I can think and still no luck.

Categories

Resources