Posted by : Unknown Selasa, 21 November 2017

Silakan bisa buat project baru File -> New Project, pilih kategory Java->Java Application.

Langsung saja tulis CanvasGambar seperti code di bawah dan baca sendiri komentarnya:


package canvasgambar;

import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

/**
*
* @author Nekiikoma
*/
public class CanvasGambar extends Canvas{
private int w;
private int h;

public CanvasGambar(int w, int h){
this.w = w;
this.h = h;
this.setSize(w, h);
}
public void paint(Graphics g){
//cast Graphics ke Graphics2D yg lebih lengkap
Graphics2D g2d = (Graphics2D)g;

//set warna putih
g2d.setColor(Color.white);
//warnai canvas dari titik (0,0) sampai lebar w dan tinggi h
g2d.fillRect(0, 0, w, h);

//set warna hitam
g2d.setColor(Color.black);
g2d.drawString("Belajar menggambar dengan canvas by Nekiikoma", 10, 20);

//set warna biru
g2d.setColor(Color.blue);
g2d.drawLine(10, 25, w-10, 25);

g2d.setColor(Color.green);      //set warna hijau
g2d.fillRect(10, 40, 100, 50);  //kotak penuh pada (10,40) pxl=100x50

g2d.setStroke(new BasicStroke(3));  //ketebalan stroke(garis) diset 3pixel
g2d.setColor(Color.black);
g2d.drawRoundRect(120, 40, 100, 100, 10, 10);   //gambar garis kotak tumpul

g2d.setStroke(new BasicStroke(2));
g2d.setColor(Color.orange);
g2d.fillOval(230, 40, 50, 50);  //lingkaran penuh
g2d.setColor(Color.gray);
g2d.drawOval(230, 40, 50, 50);  //lingkaran garis
}
}

Selanjutnya silakan buat lagi file FormCanvas di package yang sama (package main), lihat contoh kodenya di bawah :


package canvasgambar;

import javax.swing.JFrame;

/**
 *
 * @author Nekiikoma
 */
public class FormCanvas extends JFrame {
    public FormCanvas(){
        //membuat form baru dari konstruktor parent JFrame
        super("Ini Form Canvas Saya");

        //menambahkan CanvasGambar ukuran 500x500 yg tadi dibuat
        this.add(new CanvasGambar(300,200));

        //agar ukuran form menyesuaikan Canvas
        this.pack();

        //agar form muncul di tengah layar
        this.setLocationRelativeTo(null);

        //agar form bisa diclose
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //agar form bisa terlihat
        this.setVisible(true);
    }

    //method main untuk menjalankan form, sintaks sudah bawaan java
    public static void main(String arg[]){
        //agar aman dalam menampilkan form gunakan sintaks ini
        java.awt.EventQueue.invokeLater(new Runnable(){
            public void run(){
                new FormCanvas();
            }
        });

    }
}

Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Software Engineering - Hatsune Miku - Powered by Blogger - Designed by Johanes Djogan -