Pages

Draw square in JFrame

Source code below will show you, how to draw a square in a JFrame. For your information, square has 4 equal side. It mean it has 4 side with same length.

************************************************************************
COMPLETE SOURCE CODE FOR : DrawSquareInJFrame.java
************************************************************************


import javax.swing.JFrame;

import java.awt.Graphics;
import java.awt.Color;

public class DrawSquareInJFrame extends JFrame
{
public DrawSquareInJFrame()
{
//Set JFrame title
super("Draw A Square In JFrame");

//Set default close operation for JFrame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
setSize(400,400);

//Make JFrame visible
setVisible(true);
}

public void paint(Graphics g)
{
super.paint(g);

//draw square outline
g.drawRect(50,50,100,100);

//set color to RED
//So after this, if you draw anything, all of it's result will be RED
g.setColor(Color.RED);

//fill square with RED
g.fillRect(50,50,100,100);
}

public static void main(String[]args)
{
DrawSquareInJFrame dlijf=new DrawSquareInJFrame();
}
}


************************************************************************
JUST COMPILE AND EXECUTE IT
************************************************************************
Related Posts Plugin for WordPress, Blogger...