Cara Membuat Grafik menggunakan Java

Gambar di atas adalah salah satu gambar primitive dari Graphic2d java,menggunakan Class Shape  ,untuk membuatnya cukup mudah,buat Class baru  java kemudian tulis seperti di bawah ini:

import java.awt.*;
 import java.awt.geom.Ellipse2D;
 import javax.swing.*;

<!--more-->public class tugas1 extends JPanel {

public void segitiga(Graphics g) {
 Graphics2D se3 = (Graphics2D) g;
 int x[] = {50, 150, 250};
 int y[] = {250, 50, 250};
 se3.setColor(Color.green);
 se3.fill(new Polygon(x, y, x.length));
 }

public void kotak(Graphics g) {
 Graphics2D kot = (Graphics2D) g;
 int x = 500, y = 100;
 int p = 100, l = 100;
 kot.setColor(Color.yellow);
 kot.fill(new Rectangle(x, y, p, l));
 }

public void poligon(Graphics g) {
 Graphics2D g2d = (Graphics2D) g;
 Polygon pol;
 int x[] = {375, 400, 450, 475, 450, 400};
 int y[] = {150, 100, 100, 150, 200, 200};
 pol = new Polygon(x, y, x.length);
 g2d.setPaint(Color.red);
 g2d.fill(pol);
 }

public void linkaran(Graphics g) {
 Graphics2D ling = (Graphics2D) g;
 Ellipse2D lingkaran;
 double x = 250, y = 100;
 double diameter = 80;
 lingkaran = new Ellipse2D.Double(x, y, diameter, diameter);
 ling.setColor(Color.blue);
 ling.fill(lingkaran);
 }

public void garis(Graphics g) {
 Graphics2D g2d = (Graphics2D) g;
 g2d.drawLine(50, 50, 100, 50);
 }

public void titik(Graphics g) {
 Graphics2D t2k = (Graphics2D) g;
 t2k.drawLine(30,30,30,30);
 }

public void paintComponent(Graphics g) {
 clear(g);
 segitiga(g);
 kotak(g);
 poligon(g);
 garis(g);
 linkaran(g);
 titik(g);

}

protected void clear(Graphics g) {
 super.paintComponent(g);
 }

public static void main(String[] args) {
 tugas1 panelGambar = new tugas1();
 JFrame fr = new JFrame();
 fr.setSize(650,350);
 fr.getContentPane().add(panelGambar);
 fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 fr.setVisible(true);
 }
 }
Advertisements