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.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;

public class Main extends JFrame {
    public Main() {
        JViewport viewport = new MyViewport();
        viewport.setView(new MyPanel());
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setViewport(viewport);
        add(scrollPane);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        new Main();
    }
}

class MyViewport extends JViewport {
    int TILE = 64;

    public MyViewport() {
        setOpaque(false);
        setPreferredSize(new Dimension(6 * TILE, 6 * TILE));
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.blue);
        g.fillRect(TILE, TILE, 3 * TILE, 3 * TILE);
    }
}

class MyPanel extends JPanel {
    int TILE = 64;

    public MyPanel() {
        setOpaque(false);
        setPreferredSize(new Dimension(9 * TILE, 9 * TILE));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.lightGray);
        int w = getWidth() / TILE + 1;
        int h = getHeight() / TILE + 1;
        for (int row = 0; row < h; row++) {
            for (int col = 0; col < w; col++) {
                if ((row + col) % 2 == 0) {
                    g.fillRect(col * TILE, row * TILE, TILE, TILE);
                }
            }
        }
    }
}