Setting frame size to the size of an image
Hello,
I'm trying to add an image to a JPanel, and I want the frame size to be the exact same as the image size but I don't know which functions to use. Here's the code I'm using. Any ideas how to do this?
Code:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
MyFrame frame = new MyFrame();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
}
});
}
}
class MyFrame extends JFrame
{
private JPanel imagePanel;
BufferedImage image;
Dimension dim;
public MyFrame()
{
setTitle("Lab 7 tester");
try{
image = ImageIO.read(new File("simple.png"));
} catch (Exception e){
e.printStackTrace();
}
dim = new Dimension();
dim.height = image.getHeight();
dim.width = image.getWidth();
imagePanel = new JPanel(){
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(image, 0, 0, null);
}
};
imagePanel.setPreferredSize(dim);
add(imagePanel);
}
}
Thanks.