Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Drawing multiple images on a JPanel

802561Oct 19 2010 — edited Oct 20 2010
Hi,

I'm trying to draw multiple images, and it's doing something weird, such as moving the image too far over, then not showing if the frame is expanded/minimized too much. Here's a SSCCE so you can see for yourself.
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Gui extends JFrame {
	
	public int increase;
	
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			public void run() {
				new Gui().initializeGui();
			}

		});
	}

	public void addComponents(Container pane) {
		JPanel panel = new JPanel() {
			
			protected void paintComponent(Graphics g) {
				int test = "Test".length();
				try {
					for (int i = 0; i < test; i++) {
						ImageIcon icon = new ImageIcon(new URL("http://i51.tinypic.com/122fbwi.png"));
						g.drawImage(icon.getImage(), increase, 0, null);
						increase += 35;
					}
					super.paintComponent(g);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
			}
			
		};
		panel.setOpaque(false);
		
		pane.add(panel);
	}

	public void initializeGui() {
		Gui gui = new Gui();
		gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		gui.addComponents(gui.getContentPane());
		gui.setTitle("Word Generator");
		gui.setSize(new Dimension(450, 150));
		gui.setVisible(true);
	}
	
}
Please note that what I'm using is barely different, and the only difference is that the string will be different lengths based upon a randomly generated word.

Thanks.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 17 2010
Added on Oct 19 2010
3 comments
762 views