I'm trying to get some images to scale for a chess program I'm writing. I tried writing up a small program just to get a feel for scaling images and I ran into a problem with the image displaying. Basically the image will only display properly if that ImageIcon (icon) is there and it is above pawn in the code. If it doesn't exist, it is below pawn in the code, or the image sources are different pawn displays as a black square. If I don't try and scale pawn then the whole thing works just fine regardless of whether icon is there or not. This whole thing just really perplexes me because the only association pawn and icon have is that they share a source image. Can anyone shed some light on this?
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class resizeImg extends JFrame{
public void generateGui(){
JPanel mainPanel=new JPanel();
getContentPane().add(mainPanel);
JPanel main=new JPanel();
main.setBorder(BorderFactory.createLineBorder(new Color(0,0,0)));
main.setSize(400,400);
mainPanel.add(main);
mainPanel.setLayout(null);
ImageIcon icon=new ImageIcon(Toolkit.getDefaultToolkit().getImage("resources/pawn.jpg"));
//if you remove the above ImageIcon the image just displays as a black square
Image pawn=scale(Toolkit.getDefaultToolkit().getImage("resources/pawn.jpg"));
JLabel pawnContainer=new JLabel(new ImageIcon(pawn));
main.add(pawnContainer);
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public BufferedImage scale(Image i){
BufferedImage resized=new BufferedImage(50,50,BufferedImage.TYPE_INT_RGB);
Graphics2D g=resized.createGraphics();
g.drawImage(i,0,0,50,50,null);
g.dispose();
return resized;
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
resizeImg imgObject=new resizeImg();
imgObject.generateGui();
imgObject.setVisible(true);
}
});
}
}