Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class Main {
    private static final String[] LABEL_STRINGS = { "A", "B", "C", "D", "E", "F", "G" };
    static int HEIGHT = 400;
    static int WIDTH = 600;
    static int LBL_WIDTH = 60;
    static int LBL_HEIGHT = 40;
    JPanel mainPanel = new JPanel();

    public Main() {
        mainPanel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        mainPanel.setLayout(null);

        MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
        for (int i = 0; i < LABEL_STRINGS.length; i++) {
            JLabel label = new JLabel(LABEL_STRINGS[i], SwingConstants.CENTER);
            label.setSize(new Dimension(LBL_WIDTH, LBL_HEIGHT));
            label.setOpaque(true);
            Random random = new Random();
            label.setLocation(random.nextInt(WIDTH - LBL_WIDTH), random.nextInt(HEIGHT - LBL_HEIGHT));
            label.setBackground(
                    new Color(150 + random.nextInt(105), 150 + random.nextInt(105), 150 + random.nextInt(105)));
            label.addMouseListener(myMouseAdapter);
            label.addMouseMotionListener(myMouseAdapter);

            mainPanel.add(label);
        }
    }

    public JComponent getMainPanel() {
        return mainPanel;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new Main().getMainPanel());
        frame.pack();
        frame.setVisible(true);
    }
}

class MyMouseAdapter extends MouseAdapter {
    private Point initLabelLocation = null;
    private Point initMouseLocationOnScreen = null;

    @Override
    public void mousePressed(MouseEvent e) {
        JLabel label = (JLabel) e.getSource();
        initLabelLocation = label.getLocation();
        initMouseLocationOnScreen = e.getLocationOnScreen();
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        initLabelLocation = null;
        initMouseLocationOnScreen = null;
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        if (initLabelLocation == null || initMouseLocationOnScreen == null) {
            return;
        }
        JLabel label = (JLabel) e.getSource();
        Point mouseLocation = e.getLocationOnScreen();
        int deltaX = mouseLocation.x - initMouseLocationOnScreen.x;
        int deltaY = mouseLocation.y - initMouseLocationOnScreen.y;
        int labelX = initLabelLocation.x + deltaX;
        int labelY = initLabelLocation.y + deltaY;
        label.setLocation(labelX, labelY);
    }
}