Using this class and this main method, I am trying to make it so that the window that is created when running the main class is the right size to hold all of the icons that are passed into it without having to resize the window, and without hardcoding a value into what I want the window size to be when I initialize it.
Right now when it runs, the window starts extremely tiny, and as I resize it the layout of all of the icons that are painted onto it are messed up.
I know how to determine the proper size it should be, but I am not sure how I I know using the coordinates ArrayList is how I would determine the size, but I am not sure how I would change the size of the window after it has already been initialized.
public class CompositeIcon implements Icon
{
ArrayList<Icon> iList;
static int width;
static int height;
ArrayList<Point> coordinates;
public CompositeIcon()
{
iList = new ArrayList<Icon>();
coordinates = new ArrayList<Point>();
}
public int getIconHeight()
{
return height;
}
public void addIcon(Icon icon, int x, int y)
{
iList.add(icon);
coordinates.add(new Point(x, y));
}
public int getIconWidth()
{
return width;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
int i = 0;
for (Icon s : iList)
{
Point offset = coordinates.get(i++);
s.paintIcon(c, g, x + offset.x, y + offset.y);
}
}
This is the main to test it
public static void main (String args[]) {
JFrame frame = new JFrame();
Container panel = frame.getContentPane();
panel.setLayout(new BorderLayout());
CompositeIcon icon = new CompositeIcon();
try {
icon.addIcon(new ImageIcon(new URL("http://th02.deviantart.net/fs71/150/f/2013/103/2/7/java_dock_icon_by_excurse-d61mi0t.png")), 10, 10);
icon.addIcon(new ImageIcon(new URL("http://www.bravegnu.org/blog/icons/java.png")), 5, 370);
icon.addIcon(new ImageIcon(new URL("http://fc03.deviantart.net/fs20/f/2007/274/9/8/3D_Java_icon_by_BrightKnight.png")), 200, 200);
}
catch (MalformedURLException e) {
System.err.println("Apparently, somebody cannot type a URL");
}
panel.add(new JLabel(icon));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Basically, the width
and height
of the CompositeIcon
should represent the combined width and height's of the icons you add (allowing for the x/y offsets)
Something like...
public void addIcon(Icon icon, int x, int y) {
iList.add(icon);
width = Math.max(width, x + icon.getIconWidth());
height = Math.max(height, y + icon.getIconHeight());
coordinates.add(new Point(x, y));
}
You will need to remove the static
declearations for width
and height
as each instance of CompositeIcon
should have it's own width
and height