Displaying images on java Jframe
This code creates JFrame
and displays a file with an outline f
in this frame. He uses JLabel
, as one of the commenters suggests.
public static void display(String f) throws Exception {
JFrame jf = new JFrame();
JLabel jl = new JLabel(new ImageIcon(ImageIO.read(new File(f))));
jf.add(jl);
jf.setBounds(0, 0, 200, 200);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Note that you probably want to handle exceptions better, set the image size (you can query the result ImageIO.read()
for .getWidth()
and .getHeight()
), etc.
Here's a slightly more complex example where an image is resized to fill its border:
public static void display(final String f) throws Exception {
JFrame jf = new JFrame();
JPanel jp = new JPanel() {
private BufferedImage bi = ImageIO.read(new File(f));
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.setRenderingHints(rh);
int w = getWidth();
int h = getHeight();
g.drawImage(bi, 0, 0, w, h, null);
}
};
jf.add(jp);
jf.setBounds(0, 0, 400, 200);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Note: after reading the links in the comments, I must recommend MadProgrammer's comprehensive posts on this topic. The only merit of this answer is its short length, but if you want to significantly improve scaling , aspect ratio scaling , or other detailed images, follow these links.
source to share