Friday, July 22, 2016

Simple program to create JFrame and add a JPanel to it and draw using Graphics class in Java

This program is self explanatory...

I have done this to demonstrate simple way of creating A window(using Java Swing) and display something inside a panel in it.

/* Program to display a rectangle, filled rectangle and a line all with different colors
 * and a text string
 */
import java.awt.Graphics;
import java.awt.Color;
//import java.awt.
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.JFrame;
//import javax.swing.Timer;
public class FirstJavaGraphics extends JPanel
{
   
public static void main(String[] args)
{
    FirstJavaGraphics fjg=new FirstJavaGraphics();
    JFrame window=new JFrame("Hello Java Graphics");
    window.setSize(640, 480);
    window.add(fjg);
    window.setVisible(true);
}
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    setBackground(Color.RED);
    g.drawRect(100, 20, 30, 30);
    g.setColor(Color.GREEN);
    g.fillRect(200, 320, 40, 40);
    g.drawLine(100, 100, 200, 200);
    g.setColor(Color.BLUE);
    g.drawString("Hello WOrld", 100, 250);
}
FirstJavaGraphics()
{
}
}

Snapshot:

The next program will be to animate the scene using a Timer in the swing package.

No comments:

Post a Comment