Reputation: 8851
Hey, so I'm working on a program and for debugging purposes, I'm trying to get the program to take a screenshot of a part of the display. I want to have the display updated, but I can't seem to get it to work. I'm sure it's a simple issue, but my experience with Java Applets is very small.
Here's the part that I'm having issues with:
...
Thread.sleep(5000);
try {gb = new GameBoard(frame.getBounds());}
catch(Exception e){System.out.println("Error.");} // Make "gameboard" Object
while (true)
{
Thread.sleep(1000);
gb.grabImage(); // use java.awt.Robot's createScreenCapture()
ImageIcon icon = new ImageIcon(gb.image()); // wrap the image
JLabel label = new JLabel(icon, JLabel.CENTER);
frame.getContentPane().add(label,BorderLayout.EAST); //display the image (works)
//JOptionPane.showMessageDialog(null, label, "icon", -1);
label.repaint(); //update the display??
frame.repaint();
frame.getContentPane().repaint();
}
As I said, the image appears, and will create new ones if I change the Applet size, but I need a constantly changing image.
Thanks in advance!
Upvotes: 2
Views: 7109
Reputation: 54516
You are creating and adding a new JLabel
each time through the loop. Because you are changing the structure of the component tree you'll need to call revalidate
on the frame's content pane.
A better solution would be to just change the image on a single JLabel. Create one label, add it, then in your loop use JLabel.setIcon
and repaint
.
Upvotes: 5
Reputation: 210765
From what I remember, repaint()
in Java should really have been called invalidate()
-- it doesn't actually repaint the window; it only invalidates it so it can be repainted by the OS at the next opportunity. I didn't look carefully at your code, but I think this might be the issue. I'm not sure how to force a redraw, but an idea would be to return from the function, then have a timer interrupt you and paint it then -- that way, the OS will have a chance to paint the window.
Upvotes: 0
Reputation: 205875
As @RD notes, createScreenCapture()
will throw a SecurityException
if the applet is not signed. Sleeping on the event dispatch thread may be blocking updates. This example captures a screen image as the mouse is dragged; its BufferedImage
"remembers" the last image captured.
Upvotes: 2