Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.LayoutManager;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
    public static void main(String[] args) throws Exception {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        URL url = new URL("http://www.java2s.com/style/download.png");
        Image image = ImageIO.read(url);

        ImagePanel ip = new ImagePanel(new GridLayout(4, 4, 20, 20));
        ip.setPreferredSize(new Dimension(640, 480));
        f.setContentPane(ip);
        f.pack();
        f.setVisible(true);

        ip.setImage(new ImageIcon(image));
    }
}

class ImagePanel extends JPanel {
    private Image image = null;

    ImagePanel(LayoutManager layout) {
        super(layout);
    }

    public void setImage(ImageIcon icon) {
        image = icon.getImage().getScaledInstance(this.getWidth(), this.getHeight(), Image.SCALE_DEFAULT);
        repaint();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image != null) {
            g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
        }
    }
}