Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.URL;

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

public class Main {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                try {
                    frame.add(new MyPanel());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                frame.setSize(250, 250);
                frame.setVisible(true);
            }
        });
    }
}

class MyPanel extends JPanel {
    public MyPanel() throws Exception {
        setLayout(new FlowLayout());
        int size = 100;

        URL url = new URL("http://www.java2s.com/style/download.png");
        BufferedImage bi = ImageIO.read(url);

        Image left = createImage(size, Color.YELLOW);

        Image merged = merge(left, bi);

        add(new JLabel(new ImageIcon(merged)));
    }

    public static Image createImage(int size, Color color) {
        BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        g.setColor(color);
        g.fillRect(0, 0, size, size);
        g.dispose();
        return image;
    }

    public static Image merge(Image left, Image right) {
        BufferedImage merged = new BufferedImage(left.getWidth(null) + right.getWidth(null), left.getHeight(null),
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) merged.getGraphics();
        g.drawImage(left, 0, 0, null);
        g.drawImage(right, left.getWidth(null), 0, null);
        return merged;
    }
}