How to take control over a canvas loaded using a ClassLoader? - java

Say that I use a UrlClassLoader to load an applet from a website and attach it as a component to a frame. How can I gain control over the canvas so that I can draw to it myself? There is not much information about this as far as I can tell. Someone mentioned something about XBOOTING, but I have no idea what that is and I can't find anything about it.

The problem is that 'every applet is different'. That applet for instance, has no Canvas in it, but instead draws directly to the applet surface. As soon as you have an instance of the applet, you might draw directly to that, but it will be overwritten the moment that the user selects a button.
import java.applet.Applet;
import java.awt.*;
import java.net.*;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class GrabThatCanvas {
GrabThatCanvas() {
try {
String string = "http://mainline.brynmawr.edu/Courses/cs110/spring2002/Applets/Smiley/";
URL[] urls = {
new URL(string)
};
URLClassLoader urlcl = new URLClassLoader(urls);
Class<?> clss = urlcl.loadClass("Smiley");
Object o = clss.newInstance();
Applet applet = (Applet)o;
applet.init();
applet.start();
applet.setPreferredSize(new Dimension(200,200));
Canvas canvas = findFirstCanvas(applet);
if (canvas!=null) {
System.out.println("We have the Canvas!");
} else {
System.out.println("No Canvas found!");
}
JOptionPane.showMessageDialog(null, applet);
} catch (Exception e) {
e.printStackTrace();
}
}
/* Very naive implementation that assumes the canvas is added
* directly to the applet. */
public Canvas findFirstCanvas(Container parent) {
Canvas canvas = null;
Component[] components = parent.getComponents();
for (Component c : components) {
System.out.println(c);
if (c instanceof Canvas) {
canvas = (Canvas)c;
break;
}
}
return canvas;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new GrabThatCanvas();
}
});
}
}
Output
java.awt.Button[button0,0,0,0x0,invalid,label=Smile]
java.awt.Button[button1,0,0,0x0,invalid,label=Sad]
No Canvas found!
Of course, you might put the applet in a Swing GUI, account for the weird mix of Swing and AWT, and use the layered pane to draw 'over the top' of the entire applet. But that introduces new problems.

Related

Getting graphics object to draw with buffer strategy

I've made a JFrame with a canvas on it and I want to draw on that canvas. At a later date the canvas will be updating many times a second so I am using a buffer strategy for this. Here is the code:
package mainPackage;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class TickPainter {
//just some presets for a window.
public static JFrame makeWindow(String title, int width, int height) {
JFrame mainWindow = new JFrame();
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setSize(width, height);
mainWindow.setVisible(true);
mainWindow.setLocationRelativeTo(null);
mainWindow.setTitle(title);
return mainWindow;
}
public static void main(String[] args) {
JFrame mainWindow = makeWindow("Practice", 800, 600);
Canvas mainCanvas = new Canvas();
mainWindow.add(mainCanvas);
mainCanvas.setSize(mainWindow.getWidth(), mainWindow.getHeight());
mainCanvas.setBackground(Color.white);
mainCanvas.createBufferStrategy(3);
BufferStrategy bufferStrat = mainCanvas.getBufferStrategy();
Graphics g = bufferStrat.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(250, 250, 250, 250);
g.dispose();
bufferStrat.show();
}
}
The program does not draw the black rectangle as intended, I feel like I've missed something really obvious here and I just can't see it. At the moment the program just makes a blank white canvas. I feel like part of the issue is that the buffer is just passing the frame with the rectangle faster than I can see, but there is no frame to load after that so I don't know why it's doing this.
A BufferStrategy has a number of initial requirements which must be meet before it can be rendered to. Also, because of the nature of how it works, you might need to repeat a paint phases a number of times before it's actually accepted by the hardware layer.
I recommend going through the JavaDocs and tutorial, they provide invaluable examples into how you're suppose to use a BufferStrategy
The following example uses a Canvas as the base component and sets up a rendering loop within a custom Thread. It's very basic, but shows the basic concepts you'd need to implement...
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JFrame;
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() {
TestCanvas canvas = new TestCanvas();
JFrame frame = new JFrame();
frame.add(canvas);
frame.setTitle("Test");
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas.start();
}
});
}
public class TestCanvas extends Canvas {
private Thread thread;
private AtomicBoolean keepRendering = new AtomicBoolean(true);
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void stop() {
if (thread != null) {
keepRendering.set(false);
try {
thread.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
public void start() {
if (thread != null) {
stop();
}
keepRendering.set(true);
thread = new Thread(new Runnable() {
#Override
public void run() {
createBufferStrategy(3);
do {
BufferStrategy bs = getBufferStrategy();
while (bs == null) {
System.out.println("get buffer");
bs = getBufferStrategy();
}
do {
// The following loop ensures that the contents of the drawing buffer
// are consistent in case the underlying surface was recreated
do {
// Get a new graphics context every time through the loop
// to make sure the strategy is validated
System.out.println("draw");
Graphics graphics = bs.getDrawGraphics();
// Render to graphics
// ...
graphics.setColor(Color.RED);
graphics.fillRect(0, 0, 100, 100);
// Dispose the graphics
graphics.dispose();
// Repeat the rendering if the drawing buffer contents
// were restored
} while (bs.contentsRestored());
System.out.println("show");
// Display the buffer
bs.show();
// Repeat the rendering if the drawing buffer was lost
} while (bs.contentsLost());
System.out.println("done");
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
} while (keepRendering.get());
}
});
thread.start();
}
}
}
Remember, the point of BufferStrategy is to give you full control over the painting process, so it works outside the normal painting process generally implemented by AWT and Swing
"At a later date the canvas will be updating many times a second so I am using a buffer strategy for this" - Before going down the "direct to hardware" solution, I'd consider using a Swing Timer and the normal painting process to see how well it works

drawImage in Java applet

I can't display image in my applet. Using drawImage() in paint() method. The (Graphics2D) cast is part of a tutorial program. Image supposed to change every few seconds and correspond to title and the http link. Everything works but my images. I tried Oracle's tutorials and looked through other questions on stackoverflow. Tried passing different arguments to drawImage() method. Also I think I may have some unnecessary 'import's.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.net.URL;
// image libraries
import java.awt.Image.*;
import java.io.*;
import java.awt.image.*; // for buffered image
import javax.imageio.*; // read buffered image
import java.awt.image.BufferedImage.*;
public class Ch_19_Ex_01 extends JApplet implements Runnable, ActionListener {
String[] pageTitle = new String[5];
String[] imageString = new String[5];
URL[] pageLink = new URL[5];
BufferedImage[] images = new BufferedImage[5];
Color butterscotch = new Color(255, 204, 158);
int current = 0;
Thread runner;
public void init() {
pageTitle = new String[] {
"Horoscope for cancer",
"Brainy Quotes",
"NJ Daily Lottery",
"Daily Jokes",
"West Milford weather",
};
imageString = new String[] {
"0.jpg",
"1.png",
"2.png",
"3.jpg",
"4.gif",
};
pageLink[0] = getURL("http://my.horoscope.com/astrology/free-daily-horoscope-taurus.html");
pageLink[1] = getURL("http://www.brainyquote.com/quotes/keywords/daily_life.html");
pageLink[2] = getURL("http://www.state.nj.us/lottery/home.shtml");
pageLink[3] = getURL("http://www.jokes.com/");
pageLink[4] = getURL("http://www.weather.com/weather/today/90005");
for (int i = 0; i < 5; i++) {
try {
URL url = new URL(getCodeBase(), imageString[i]);
images[i] = ImageIO.read(url);
} catch (IOException e) {
// dont know
}
}
Button goButton = new Button("Go");
goButton.addActionListener(this);
FlowLayout flow = new FlowLayout();
setLayout(flow);
add(goButton);
Button stopButton = new Button("Stop");
add(stopButton);
}
URL getURL(String urlText) {
URL pageURL = null;
try {
pageURL = new URL(getDocumentBase(), urlText);
} catch (MalformedURLException m) {
System.out.println("Error>>>>");
}
return pageURL;
}
public void paint(Graphics screen) {
Graphics2D screen2D = (Graphics2D) screen;
screen2D.setColor(butterscotch);
screen2D.fillRect(0, 0, getSize().width, getSize().height);
screen2D.setColor(Color.black);
screen2D.drawString(pageTitle[current], 5, 60);
screen2D.drawString("" + pageLink[current], 5, 80);
screen2D.drawImage(images[current], 0, 0, 100, 200, this);
}
public void start() {
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}
public void run () {
Thread thisThread = Thread.currentThread();
while(runner == thisThread) {
current ++;
if (current > 4) {
current = 0;
}
repaint();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Error>>>>>>>>>>>");
}
}
}
public void stop() {
if (runner != null) {
runner = null;
}
}
public void actionPerformed(ActionEvent event) {
if (runner != null) {
runner = null;
}
AppletContext browser = getAppletContext();
if (pageLink[current] != null) {
browser.showDocument(pageLink[current]);
}
}
}
From what I can tell, your paint code should work fine
The problem is, most likely, in the fact that the images are not loading, but since you've chosen to ignore any errors that are raised by this process, you won't have any idea why...
So, instead of // dont know, use e.printStackTrace() when loading your images
for (int i = 0; i < 5; i++) {
try {
URL url = new URL(getCodeBase(), imageString[i]);
images[i] = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
}
This will at least provide you with some more clues as to the problems you are facing.
You should also avoid using AWT (Button) components on Swing (JAppelt) containers. They tend not to play nice well together.
Having said all that, I would encourage you not to use JAppelt as a learning tool. Applets come with a swag of their own issues which are difficult to diagnose at the best of times, more so when you're trying to learn Java and the Swing API. The Swing API is complex enough with adding unnecessary challenges.
You should also avoid extending from top level containers (in this case, you have no choice), but you should also avoid painting directly to top level containers. Apart from the complexities of the paint process, they are not double buffered, which introduces flickering when the UI is updated.
Instead, start with something like a JPanel and override it's paintComponent method. JComponents are double buffered by default, so they won't flicker when they are repainted. You must also call super.paintXxx. As I said, the paint process is a complex process, each paintXxx method is a link in the chain, if you break the chain, you should be prepared for some strange and unexpected behaviour down the track.
Once you have your component setup, you are free to choose how to deploy it, by adding it to something like a JFrame or JApplet, making your component more flexible and reusable.
Take a look at Performing Custom Painting for more details
The next question that comes to mind is why? Why do any custom painting at all, when JLabels will not only do the job, but would probably do it better.
Take a look at Creating an GUI with Swing for more details...

Paint over applet loaded with classloader

I was wondering what would be the best/easiest way to render my own graphics over an applet that has been loaded with:
public class Game {
public static Applet applet = null;
public static URLClassLoader classLoader = null;
public static void load() {
try {
classLoader = new URLClassLoader(new URL[]{Jar.getJar().toURL()});
applet = (Applet) classLoader.loadClass("com.funkypool.client.PoolApplet").newInstance();
applet.setSize(new Dimension(800, 600));
applet.setBackground(Color.BLACK);
applet.setStub(new Stub());
applet.init();
applet.start();
JFrame loader = new JFrame("Loader");
loader.setPreferredSize(applet.getSize());
loader.add(applet);
loader.pack();
loader.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I would like it to render over the applet, but the applet still maintain all of its original functionality, I believe i would need to use reflection possibly? I was thinking about looking at the way Powerbot.org renders over the runescape client, as the client still maintains all its functionality etc.
If you have any questions or need to see more code, just ask.
Assuming this draws something (my applet-fu is rusty), then you can draw on top of it by placing it in a JFrame and subclassing the JFrames' void paint(Graphics g) so that it paints whatever it wants to, and then paints something else.
A modified JFrame that does this could be the following (warning: untested code):
public static class OverlayJFrame extends JFrame {
private JPanel overlay;
public OverlayJFrame(String title) { super(title); }
public void setOverlay(JPanel overlay) { this.overlay = overlay; }
public void paint(Graphics g) { super.paint(g); overlay.setSize(getSize()); overlay.paint(g)); }
}

How to get the x and y of a program window in Java?

Is there a way for me to get the X and Y values of a window in java? I read that I'll have to use runtime, since java can't mess directly, however I am not so sure of how to do this. Can anyone point me some links/tips on how to get this?
To get the x and y position of "any other unrelated application" you're going to have to query the OS and that means likely using either JNI, JNA or some other scripting utility such as AutoIt (if Windows). I recommend either JNA or the scripting utility since both are much easier to use than JNI (in my limited experience), but to use them you'll need to download some code and integrate it with your Java application.
EDIT 1
I'm no JNA expert, but I do fiddle around with it some, and this is what I got to get the window coordinates for some named window:
import java.util.Arrays;
import com.sun.jna.*;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.win32.*;
public class GetWindowRect {
public interface User32 extends StdCallLibrary {
User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class,
W32APIOptions.DEFAULT_OPTIONS);
HWND FindWindow(String lpClassName, String lpWindowName);
int GetWindowRect(HWND handle, int[] rect);
}
public static int[] getRect(String windowName) throws WindowNotFoundException,
GetWindowRectException {
HWND hwnd = User32.INSTANCE.FindWindow(null, windowName);
if (hwnd == null) {
throw new WindowNotFoundException("", windowName);
}
int[] rect = {0, 0, 0, 0};
int result = User32.INSTANCE.GetWindowRect(hwnd, rect);
if (result == 0) {
throw new GetWindowRectException(windowName);
}
return rect;
}
#SuppressWarnings("serial")
public static class WindowNotFoundException extends Exception {
public WindowNotFoundException(String className, String windowName) {
super(String.format("Window null for className: %s; windowName: %s",
className, windowName));
}
}
#SuppressWarnings("serial")
public static class GetWindowRectException extends Exception {
public GetWindowRectException(String windowName) {
super("Window Rect not found for " + windowName);
}
}
public static void main(String[] args) {
String windowName = "Document - WordPad";
int[] rect;
try {
rect = GetWindowRect.getRect(windowName);
System.out.printf("The corner locations for the window \"%s\" are %s",
windowName, Arrays.toString(rect));
} catch (GetWindowRect.WindowNotFoundException e) {
e.printStackTrace();
} catch (GetWindowRect.GetWindowRectException e) {
e.printStackTrace();
}
}
}
Of course for this to work, the JNA libraries would need to be downloaded and placed on the Java classpath or in your IDE's build path.
This is easy to do with the help of the end user. Just get them to click on a point in a screen shot.
E.G.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
/** Getting a point of interest on the screen.
Requires the MotivatedEndUser API - sold separately. */
class GetScreenPoint {
public static void main(String[] args) throws Exception {
Robot robot = new Robot();
final Dimension screenSize = Toolkit.getDefaultToolkit().
getScreenSize();
final BufferedImage screen = robot.createScreenCapture(
new Rectangle(screenSize));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JLabel screenLabel = new JLabel(new ImageIcon(screen));
JScrollPane screenScroll = new JScrollPane(screenLabel);
screenScroll.setPreferredSize(new Dimension(
(int)(screenSize.getWidth()/2),
(int)(screenSize.getHeight()/2)));
final Point pointOfInterest = new Point();
JPanel panel = new JPanel(new BorderLayout());
panel.add(screenScroll, BorderLayout.CENTER);
final JLabel pointLabel = new JLabel(
"Click on any point in the screen shot!");
panel.add(pointLabel, BorderLayout.SOUTH);
screenLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
pointOfInterest.setLocation(me.getPoint());
pointLabel.setText(
"Point: " +
pointOfInterest.getX() +
"x" +
pointOfInterest.getY());
}
});
JOptionPane.showMessageDialog(null, panel);
System.out.println("Point of interest: " + pointOfInterest);
}
});
}
}
Typical output
Point of interest: java.awt.Point[x=342,y=43]
Press any key to continue . . .
A little late to the party here but will add this to potentially save others a little time. If you are using a more recent version of JNA then WindowUtils.getAllWindows() will make this much easier to accomplish.
I am using the most recent stable versions as of this post from the following maven locations:
JNA Platform - net.java.dev.jna:jna-platform:5.2.0
JNA Core - net.java.dev.jna:jna:5.2.0
Java 8 Lambda (Edit: rect is a placeholder and will need to be final or effectively final to work in a lambda)
//Find IntelliJ IDEA Window
//import java.awt.Rectangle;
final Rectangle rect = new Rectangle(0, 0, 0, 0); //needs to be final or effectively final for lambda
WindowUtils.getAllWindows(true).forEach(desktopWindow -> {
if (desktopWindow.getTitle().contains("IDEA")) {
rect.setRect(desktopWindow.getLocAndSize());
}
});
Other Java
//Find IntelliJ IDEA Window
Rectangle rect = null;
for (DesktopWindow desktopWindow : WindowUtils.getAllWindows(true)) {
if (desktopWindow.getTitle().contains("IDEA")) {
rect = desktopWindow.getLocAndSize();
}
}
Then within a JPanel you can draw a captured image to fit (Will stretch image if different aspect ratios).
//import java.awt.Robot;
g2d.drawImage(new Robot().createScreenCapture(rect), 0, 0, getWidth(), getHeight(), this);

Why is paint()/paintComponent() never called?

For the last two days I have tried to understand how Java handles graphics, but have failed miserably at just that. My main problem is understanding exactly how and when paint() (or the newer paintComponent() ) is/should be called.
In the following code I made to see when things are created, the paintComponent() is never called, unless I manually add a call to it myself or calls to JFrame.paintAll()/JFrame.paintComponents().
I renamed the paint() method to paintComponent() in hoping that would fix my problem of it never being called (even at repaint()), but no luck.
package jpanelpaint;
import java.awt.*;
import javax.imageio.*;
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
public class ImageLoadTest extends JComponent {
ArrayList<Image> list;
public ImageLoadTest() {
list = new ArrayList<Image>();
try { //create the images (a deck of 4 cards)
for(String name : createImageFileNames(4)){
System.err.println(name);
list.add(ImageIO.read(new File(name)));
}
} catch (IOException e) { }
}
protected void paintComponent(Graphics g) {
int yOffset=0;
System.err.println("ImageLoadTest.paintComponent()");
for(Image img : list) {
g.drawImage(img, 0, yOffset, null);
yOffset+=20;
}
}
public static void main(String args[]) throws InterruptedException {
JFrame frame = new JFrame("Empty JFrame");
frame.setSize(new Dimension(1000, 500));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Thread.sleep(1000);
frame.setTitle("Loading images");
ImageLoadTest ilt = new ImageLoadTest();
frame.add(ilt);
//update the screen
//DOESN'T WORK. only works if I call frame.paintAll(frame.getGraphics())
ilt.repaint();
frame.repaint();
Thread.sleep(1000);
frame.setTitle("Setting background");
ilt.setBackground(Color.BLACK);
//update the screen - DOESN'T WORK even if I call paintAll ..
ilt.repaint();
frame.repaint();
//have to call one of these to get anything to display
// ilt.paintComponent(frame.getGraphics()); //works
frame.paintComponents(frame.getGraphics()); //works
}
//PRIVATE HELPER FUNCTIONS
private String[] createImageFileNames(int count){
String[] fileNames = new String[count];
for(int i=0; i < count; i++)
fileNames[i] = "Cards" + File.separator + (i+1) + ".bmp";
return fileNames;
}
}
One of the reasons the paintComponent() doesn't get invoked in the original code is because the component has a "zero size" and the RepaintManger is smart enough not to try and paint something with no size.
The reason the reordering of the code works is because when you add the component to the frame and then make the frame visible the layout manager is invoked to layout the component. By default a frame uses a BorderLayout and by default a component is added to the center of the BorderLayout which happens give all the space available to the component so it gets painted.
However, you change the layout manager of the content pane to be a FlowLayout, you would still have a problem because a FlowLayout respects the preferred size of the component which is zero.
So what you really need to do is assign a preferred size to you your component so layout managers can do their job.
One major issue here is you are not updating your swing components on the Event Dispatch Thread (EDT). Try wrapping all the code in your main method in the following:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// swing code here...
}
});
Also: add your ImageLoadTest to the frame before setting the frame visible. This is based on a quick cursory read of the code -- I will read it further and see what else I can find.
EDIT:
Follow my original advice above, and simplify your main method to look like the following and your paintComponent() will be called:
public static void main(String args[]) throws InterruptedException {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Empty JFrame");
frame.setSize(new Dimension(1000, 500));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PaintComponentTest ilt = new PaintComponentTest();
frame.add(ilt);
frame.setVisible(true);
ilt.setBackground(Color.BLACK);
}
});
}
Also I would read up on using timers to perform animation, as well as general Swing event dispatching and how/when to override various paint methods.
http://java.sun.com/products/jfc/tsc/articles/painting/
http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html
http://java.sun.com/docs/books/tutorial/uiswing/concurrency/dispatch.html
To make Tom Hawtin - tackline happy. I rewrote once again
There are several things I changed (check the lines with the //new comment)
Rewrote it completely
Split into a clean new component file (ImageLoadTest.java) and a file to test it (Tester.java)
Improvements on original posters code
call constructor of parent in ImageLoadTest constructor (super())
provided second constructor to set list of images which component should display
IMPORTANT: call to setPreferredSize() of component in constructor. If size isn't set swing of course won't paint your component. preferred size is based on max. width of all images and on sum of all image heights
call to super.paintComponent(g) in overriden paintComponent()
changed paintComponent to automatically base yOffset on height of images being drawn
GUI initialization done on EDT
as original code based on using sleep() to illustrate loading and loading of images could take a long time SwingWorker's are used
worker waits then sets new title and then loads images
on completion the worker in done() finally adds the component to the JFrame and displays it. Added component to content pane of JFrame as described in JFrame api. And as described in javadoc made necessary call to validate() on JFrame after calling add(), as the JFrame is an already visible container whichs children changed.
javdoc citation from validate()
The validate method is used to cause a
container to lay out its subcomponents
again. It should be invoked when this
container's subcomponents are modified
(added to or removed from the
container, or layout-related
information changed) after the
container has been displayed.
second worker just does some more waiting then sets background color to black
used JPanel as baseclass for ImageLoadTest to fix setBackground() which I couldn't get to work with JComponent.
So your main problems where that you didn't set the preferred size of the component and that you did not call validate() on the JFrame after adding something to the already visible container.
This should work
jpanelpaint/ImageLoadTest.java
package jpanelpaint;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
import java.util.List;
public class ImageLoadTest extends JPanel {
private List<Image> list;
public ImageLoadTest() {
super();
}
public ImageLoadTest(List<Image> list) {
this();
this.list = list;
int height = 0;
int width = 0;
for (Image img : list) {
height += img.getHeight(this);
width = img.getWidth(this) > width ? img.getWidth(this) : width;
setPreferredSize(new Dimension(width, height));
}
}
#Override
protected void paintComponent(Graphics g) {
int yOffset=0;
super.paintComponent(g);
System.err.println("ImageLoadTest.paintComponent()");
for(Image img : list) {
g.drawImage(img, 0, yOffset, null);
yOffset+=img.getHeight(this);
}
}
}
Tester.java
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.SwingWorker;
import javax.swing.SwingUtilities;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import jpanelpaint.ImageLoadTest;
public class Tester {
private JFrame frame;
private ImageLoadTest ilt;
private final int NUMBEROFFILES = 4;
private List<Image> list;
//will load the images
SwingWorker worker = new SwingWorker<List<Image>, Void>() {
#Override
public List<Image> doInBackground() throws InterruptedException {
//sleep at start so user is able to see empty jframe
Thread.sleep(1000);
//let Event-Dispatch-Thread (EDT) handle this
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setTitle("Loading images");
}
});
//sleep again so user is able to see loading has started
Thread.sleep(1000);
//loads the images and returns list<image>
return loadImages();
}
#Override
public void done() {
//this is run on the EDT anyway
try {
//get result from doInBackground
list = get();
frame.setTitle("Done loading images");
ilt = new ImageLoadTest(list);
frame.getContentPane().add(ilt);
frame.getContentPane().validate();
//start second worker of background stuff
worker2.execute();
} catch (InterruptedException ignore) {}
catch (ExecutionException e) {
String why = null;
Throwable cause = e.getCause();
if (cause != null) {
why = cause.getMessage();
} else {
why = e.getMessage();
}
System.err.println("Error retrieving file: " + why);
}
}
};
//just delay a little then set background
SwingWorker worker2 = new SwingWorker<Object, Void>() {
#Override
public List<Image> doInBackground() throws InterruptedException {
Thread.sleep(1000);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setTitle("Setting background");
}
});
Thread.sleep(1000);
return null;
}
#Override
public void done() {
ilt.setBackground(Color.BLACK);
frame.setTitle("Done!");
}
};
public static void main(String args[]) {
new Tester();
}
public Tester() {
//setupGUI
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame = new JFrame("Empty JFrame");
frame.setSize(new Dimension(1000, 500));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
//start the swingworker which loads the images
worker.execute();
}
//create image names
private String[] createImageFileNames(int count){
String[] fileNames = new String[count];
for(int i=0; i < count; i++)
fileNames[i] = "Cards" + File.separator + (i+1) + ".bmp";
return fileNames;
}
//load images
private List<Image> loadImages() {
List<Image> tmpA = new ArrayList<Image>();
try {
for(String name : createImageFileNames(NUMBEROFFILES)){
System.err.println(name);
tmpA.add(ImageIO.read(new File(name)));
}
} catch (IOException e) { }
return tmpA;
}
}
These were the main problems with the original code that caused it not to work:
not calling validate() after an add() operation
not setting the preferred size of the component.
not calling super.paintComponent() when overriding it (this made the
setBackground() call not work)
I needed to inherit from JPanel in order for it to get painted. Neither Component nor JComponent was sufficient for the setBackground() call to work, even when fixing point 3.
Having done the above, it really didn't matter if calling the method paintComponent or paint, both seemed to work as long as I remembered to call the super constructor at the start.
This info was assembled from what #jitter, #tackline, and #camickr wrote, so big kudos!
P.S. No idea if answering your own question is considered bad form, but since the information I needed was assembled from several answers, I thought the best way was upmodding the other answers and writing a sum up like this.
I recommend reading the first couple of chapters of "Filthy Rich Clients". I had been using Swing for years, but only after reading this book did I finally fully understand exactly how Java's painting mechanism works.

Categories