Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;

public class Main extends JFrame {
    public Main() {
        MyCanvas thingy = new MyCanvas();
        setLayout(new BorderLayout());
        JPanel panel = new JPanel();
        panel.add(thingy);
        JScrollPane scroll = new JScrollPane();
        scroll.setViewportView(panel);
        add(scroll, BorderLayout.CENTER);
        SpinnerNumberModel spmodel = new SpinnerNumberModel(thingy.getThingySize(), 10.0, 2000.0, 10.0);
        spmodel.addChangeListener(e -> thingy.setThingySize((Double) spmodel.getNumber()));
        add(new JSpinner(spmodel), BorderLayout.NORTH);
    }

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

    private void start() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }
}

class MyCanvas extends JPanel {
    double size = 20.0;

    @Override
    public Dimension getPreferredSize() {
        int isize = (int) this.size;
        return new Dimension(isize, isize);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int[] x = { 0, 100, 100, 0, 0, 75, 75, 125, 25, 50 };
        int[] y = { 0, 10, 10, 100, 25, 125, 75, 75, 510, 50 };
        Graphics2D g2d = (Graphics2D) g;
        AffineTransform at0 = g2d.getTransform();
        g2d.scale(size / 100, size / 100);
        g.drawPolyline(x, y, x.length);
        g2d.setTransform(at0);
    }

    public void setThingySize(double size) {
        this.size = size;
        revalidate();
        repaint();
    }

    public double getThingySize() {
        return this.size;
    }
}