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 java.awt.Rectangle;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;

public class Main extends JFrame {
    private JLabel label = new JLabel(new ImageIcon("largeJava2sLogo.gif"));

    public Main() {
        super("JScrollPane Demo");
        JScrollPane scrollPane = new JScrollPane(label);

        JLabel[] corners = new JLabel[4];
        for (int i = 0; i < 4; i++) {
            corners[i] = new JLabel();
            corners[i].setBackground(Color.white);
            corners[i].setOpaque(true);
        }

        JLabel rowheader = new JLabel() {
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                Rectangle rect = g.getClipBounds();
                for (int i = 50 - (rect.y % 50); i < rect.height; i += 50) {
                    g.drawLine(0, rect.y + i, 3, rect.y + i);
                    g.drawString("" + (rect.y + i), 6, rect.y + i + 3);
                }
            }

            public Dimension getPreferredSize() {
                return new Dimension(25, (int) label.getPreferredSize().getHeight());
            }
        };
        rowheader.setBackground(Color.white);
        rowheader.setOpaque(true);

        JLabel columnheader = new JLabel() {

            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                Rectangle r = g.getClipBounds();
                for (int i = 50 - (r.x % 50); i < r.width; i += 50) {
                    g.drawLine(r.x + i, 0, r.x + i, 3);
                    g.drawString("" + (r.x + i), r.x + i - 10, 16);
                }
            }

            public Dimension getPreferredSize() {
                return new Dimension((int) label.getPreferredSize().getWidth(), 25);
            }
        };
        columnheader.setBackground(Color.white);
        columnheader.setOpaque(true);

        scrollPane.setRowHeaderView(rowheader);
        scrollPane.setColumnHeaderView(columnheader);
        scrollPane.setCorner(JScrollPane.LOWER_LEFT_CORNER, corners[0]);
        scrollPane.setCorner(JScrollPane.LOWER_RIGHT_CORNER, corners[1]);
        scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, corners[2]);
        scrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, corners[3]);

        getContentPane().add(scrollPane);
        setSize(400, 300);
        setVisible(true);
    }

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