Let's Draw in a Window with Java

Learn how to simply draw in a Java window

Let's see how to simply draw in a Java window. First, we start with a JFrame containing a panel. A frame needs a canvas, so I create a program where in the main I initialize the JFrame and in the next class I initialize a JPanel, which by analogy is my canvas. Here is the code:

package disegno; import javax.swing.*; public class Disegno { public static void main(String[] args) { JFrame t= new JFrame("Grafica Iterativa"); t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Tela p = new Tela(); t.add(p); t.setSize(500, 500); t.setVisible(true); }
and here is the second file
package disegno;
import java.awt.*; import javax.swing.*;
public class Tela extends JPanel{
public void paintComponent(Graphics g) { super.paintComponent(g); this.setBackground(Color.WHITE); g.setColor(Color.BLACK); // this following instruction publishes // a rectangle in the position 5,5 top left for (int r=0;r<500;r=r+12) for(int i=0;i<500;i=i+12) { g.fillRect(i,r,10,10); } /*while(i<500) { g.fillRect(i,12,10,10); i=i+12; numeroRettangoli++; if(numeroRettangoli==40) { numeroRettangoli=0; i=0; r=r+12; } }*/ }