Sunday, December 20, 2020

Tugas 9 PBO-C "Java Exception Handling"

    Pada program Java, jika di tengah-tengah program menemui error atau disebut juga runtime error, maka akan dilemparkan sebagai exception / pengecualian. Exception ini  juga adalah yang merepresentasikan suatu error atau kondisi yang mencegah eksekusi berjalan secara normal. Jika exception tidak ditangani, maka program akan berhenti secara tidak normal. 

    Java menyediakan beberapa fitur untuk exception handling, dimana terdapat secara built-in dalam bentuk keyword try, catch, dan finally. Bahasa pemrograman Java memungkinkan kita untuk membuat exception yang baru dan melemparnya dengan menggunakan keyword throw dan throws.


Berikut adalah beberapa contoh Exception Handling pada bahasa pemrograman Java :

    1. Arithmatic Exception : Muncul ketika ada pembagian suatu bilangan dengan 0

  • Sourcecode:
    public class Contoh1
    {
       public static void main(String args[])
       {
          try{
             int num1=30, num2=0;
             int output=num1/num2;
             System.out.println ("Result: "+output);
          }
          catch(ArithmeticException e){
             System.out.println ("You Shouldn't divide a number by zero");
          }
       }
    }
    

    2. ArrayIndexOutOfBound Exception : Muncul ketika kita mencoba mengakses index array yang tidak ada

  • Sourcecode:
    public class Contoh2
    {
        public static void main(String args[])
       {
          try{
            int a[]=new int[10];
            //Array has only 10 elements
            a[11] = 9;
          }
          catch(ArrayIndexOutOfBoundsException e){
             System.out.println ("ArrayIndexOutOfBounds");
          }
       }
    }
    


    3. NumberFormat Exception : Muncul ketika kita mencoba mengubah string menjadi angka

  • Sourcecode:
    public class Contoh3
    {
        public static void main(String args[])
       {
          try{
         int num=Integer.parseInt ("XYZ") ;
         System.out.println(num);
          }catch(NumberFormatException e){
          System.out.println("Number format exception occurred");
           }
       }
    }
    


    4. StringIndexOutOfBound Exception : Muncul ketika kita mencari index yang tidak ada pada sebuah string

  • Sourcecode:
    public class Contoh4
    {
        public static void main(String args[])
       {
          try{
         String str="beginnersbook";
         System.out.println(str.length());;
         char c = str.charAt(0);
         c = str.charAt(40);
         System.out.println(c);
          }catch(StringIndexOutOfBoundsException e){
          System.out.println("StringIndexOutOfBoundsException!!");
           }
       }
    }
    


    5. NullPointer Exception : Muncul ketika ada suatu objek yang bernilai NULL

  • Sourcecode:
    public class Contoh5
    {
        public static void main(String args[])
       {
        try{
            String str=null;
            System.out.println (str.length());
        }
            catch(NullPointerException e){
            System.out.println("NullPointerException..");
        }
       }
    }

Terima kasih telah berkunjung. Mohon maaf apabila ada kesalahan dalam penulisan. πŸ˜πŸ‘

Sunday, December 13, 2020

Tugas 8 PBO-C "Membuat Game Pong"

    Bermain game adalah suatu hal yang menyenangkan untuk dilakukan bagi sebagian besar orang, apalagi jika mampu membuat sendiri gamenya. Nah, pada kesempatan kali ini saya akan mencoba membuat game sederhana yang bernama game Pong. 

    Game Pong adalah permainan video generasi pertama yang dirilis sebagai permainan arkade yang dioperasikan dengan koin yang dikembangkan oleh Atari Inc. Saya akan membuat game ini dengan mengimplementasikan bahasa pemrograman java dan menggunakan konsep OOP. 

Program ini menggunakan 4 class yaitu :

  1. Class Ball, berfungsi untuk mengatur semua yang berkaitan dengan bola pong nya
  2. Class Paddle, berfungsi untuk mengatur semua yang berkaitan dengan pemukul / alas nya
  3. Class Renderer, berfungsi untuk mengatur grafik dari gamenya
  4. Class Pong, berfungsi untuk meload seluruh class yang ada pada program ini
  • Sourcecode Ball:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.util.Random;
     
    public class Ball
    {
     
        public int x, y, width = 25, height = 25;
     
        public int motionX, motionY;
     
        public Random random;
     
        private Pong pong;
     
        public int amountOfHits;
     
        public Ball(Pong pong)
        {
            this.pong = pong;
     
            this.random = new Random();
     
            spawn();
        }
     
        public void update(Paddle paddle1, Paddle paddle2)
        {
            int speed = 5;
     
            this.x += motionX * speed;
            this.y += motionY * speed;
     
            if (this.y + height - motionY > pong.height || this.y + motionY < 0)
            {
                if (this.motionY < 0)
                {
                    this.y = 0;
                    this.motionY = random.nextInt(4);
     
                    if (motionY == 0)
                    {
                        motionY = 1;
                    }
                }
                else
                {
                    this.motionY = -random.nextInt(4);
                    this.y = pong.height - height;
     
                    if (motionY == 0)
                    {
                        motionY = -1;
                    }
                }
            }
     
            if (checkCollision(paddle1) == 1)
            {
                this.motionX = 1 + (amountOfHits / 5);
                this.motionY = -2 + random.nextInt(4);
     
                if (motionY == 0)
                {
                    motionY = 1;
                }
     
                amountOfHits++;
            }
            else if (checkCollision(paddle2) == 1)
            {
                this.motionX = -1 - (amountOfHits / 5);
                this.motionY = -2 + random.nextInt(4);
     
                if (motionY == 0)
                {
                    motionY = 1;
                }
     
                amountOfHits++;
            }
     
            if (checkCollision(paddle1) == 2)
            {
                paddle2.score++;
                spawn();
            }
            else if (checkCollision(paddle2) == 2)
            {
                paddle1.score++;
                spawn();
            }
        }
     
        public void spawn()
        {
            this.amountOfHits = 0;
            this.x = pong.width / 2 - this.width / 2;
            this.y = pong.height / 2 - this.height / 2;
     
            this.motionY = -2 + random.nextInt(4);
     
            if (motionY == 0)
            {
                motionY = 1;
            }
     
            if (random.nextBoolean())
            {
                motionX = 1;
            }
            else
            {
                motionX = -1;
            }
        }
     
        public int checkCollision(Paddle paddle)
        {
            if (this.x < paddle.x + paddle.width && this.x + width > paddle.x && this.y < paddle.y + paddle.height && this.y + height > paddle.y)
            {
                return 1; //bounce
            }
            else if ((paddle.x > x && paddle.paddleNumber == 1) || (paddle.x < x - width && paddle.paddleNumber == 2))
            {
                return 2; //score
            }
     
            return 0; //nothing
        }
     
        public void render(Graphics g)
        {
            g.setColor(Color.RED);
            g.fillOval(x, y, width, height);
        }
     
    }
    
  • Sourcecode Paddle:
    import java.awt.Color;
    import java.awt.Graphics;
     
    public class Paddle
    {
     
        public int paddleNumber;
     
        public int x, y, width = 50, height = 250;
     
        public int score;
     
        public Paddle(Pong pong, int paddleNumber)
        {
            this.paddleNumber = paddleNumber;
     
            if (paddleNumber == 1)
            {
                this.x = 0;
            }
     
            if (paddleNumber == 2)
            {
                this.x = pong.width - width;
            }
     
            this.y = pong.height / 2 - this.height / 2;
        }
     
        public void render(Graphics g)
        {
            g.setColor(Color.BLACK);
            g.fillRect(x, y, width, height);
        }
     
        public void move(boolean up)
        {
            int speed = 15;
     
            if (up)
            {
                if (y - speed > 0)
                {
                    y -= speed;
                }
                else
                {
                    y = 0;
                }
            }
            else
            {
                if (y + height + speed < Pong.pong.height)
                {
                    y += speed;
                }
                else
                {
                    y = Pong.pong.height - height;
                }
            }
        }
     
    }
    
  • Sourcecode Renderer:
    import java.awt.Graphics;
    import java.awt.Graphics2D;
     
    import javax.swing.JPanel;
     
    public class Renderer extends JPanel
    {
     
        private static final long serialVersionUID = 1L;
     
        @Override
        protected void paintComponent(Graphics g)
        {
            super.paintComponent(g);
     
            Pong.pong.render((Graphics2D) g);
        }
     
    }
    
    
  • Sourcecode Pong:
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.Timer;
     
    public class Pong implements ActionListener, KeyListener
    {
    public static Pong pong;
    public int width = 700, height = 700;
    public Renderer renderer;
    public Paddle player1;
    public Paddle player2;
    public Ball ball;
    public boolean bot = false, selectingDifficulty;
    public boolean w, s, up, down;
    public int gameStatus = 0, scoreLimit = 7, playerWon; //0 = Menu, 1 = Paused, 2 = Playing, 3 = Over
    public int botDifficulty, botMoves, botCooldown = 0;
    public Random random;
    public JFrame jframe;
     
    public Pong()
    {
    Timer timer = new Timer(20, this);
    random = new Random();
    jframe = new JFrame("Pong");
    renderer = new Renderer();
    jframe.setSize(width + 15, height + 35);
    jframe.setVisible(true);
    jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jframe.add(renderer);
    jframe.addKeyListener(this);
    timer.start();
    }
     
    public void start()
    {
    gameStatus = 2;
    player1 = new Paddle(this, 1);
    player2 = new Paddle(this, 2);
    ball = new Ball(this);
    }
     
    public void update()
    {
    if (player1.score >= scoreLimit)
    {
    playerWon = 1;
    gameStatus = 3;
    }
    if (player2.score >= scoreLimit)
    {
    gameStatus = 3;
    playerWon = 2;
    }
    if (w)
    {
    player1.move(true);
    }
    if (s)
    {
    player1.move(false);
    }
    if (!bot)
    {
    if (up)
    {
    player2.move(true);
    }
    if (down)
    {
    player2.move(false);
    }
    }
    else
    {
    if (botCooldown > 0)
    {
    botCooldown--;
    if (botCooldown == 0)
    {
    botMoves = 0;
    }
    }
    if (botMoves < 10)
    {
    if (player2.y + player2.height / 2 < ball.y)
    {
    player2.move(false);
    botMoves++;
    }
    if (player2.y + player2.height / 2 > ball.y)
    {
    player2.move(true);
    botMoves++;
    }
    if (botDifficulty == 0)
    {
    botCooldown = 20;
    }
    if (botDifficulty == 1)
    {
    botCooldown = 15;
    }
    if (botDifficulty == 2)
    {
    botCooldown = 10;
    }
    }
    }
    ball.update(player1, player2);
    }
     
    public void render(Graphics2D g)
    {
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, width, height);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    if (gameStatus == 0)
    {
    g.setColor(Color.BLACK);
    g.setFont(new Font("Arial", 1, 50));
    g.drawString("PONG", width / 2 - 75, 50);
    if (!selectingDifficulty)
    {
    g.setFont(new Font("Arial", 1, 30));
    g.drawString("Press Space to Play", width / 2 - 150, height / 2 - 25);
    g.drawString("Press Shift to Play with Bot", width / 2 - 200, height / 2 + 25);
    g.drawString("<< Score Limit: " + scoreLimit + " >>", width / 2 - 150, height / 2 + 75);
    }
    }
    if (selectingDifficulty)
    {
    String string = botDifficulty == 0 ? "Easy" : (botDifficulty == 1 ? "Medium" : "Hard");
    g.setFont(new Font("Arial", 1, 30));
    g.drawString("<< Bot Difficulty: " + string + " >>", width / 2 - 180, height / 2 - 25);
    g.drawString("Press Space to Play", width / 2 - 150, height / 2 + 25);
    }
    if (gameStatus == 1)
    {
    g.setColor(Color.BLACK);
    g.setFont(new Font("Arial", 1, 50));
    g.drawString("PAUSED", width / 2 - 103, height / 2 - 25);
    }
    if (gameStatus == 1 || gameStatus == 2)
    {
    g.setColor(Color.BLACK);
    g.setStroke(new BasicStroke(5f));
    g.drawLine(width / 2, 0, width / 2, height);
    g.setStroke(new BasicStroke(2f));
    g.drawOval(width / 2 - 150, height / 2 - 150, 300, 300);
    g.setFont(new Font("Arial", 1, 50));
    g.drawString(String.valueOf(player1.score), width / 2 - 90, 50);
    g.drawString(String.valueOf(player2.score), width / 2 + 65, 50);
    player1.render(g);
    player2.render(g);
    ball.render(g);
    }
    if (gameStatus == 3)
    {
    g.setColor(Color.BLACK);
    g.setFont(new Font("Arial", 1, 50));
    g.drawString("PONG", width / 2 - 75, 50);
    if (bot && playerWon == 2)
    {
    g.drawString("The Bot Wins!", width / 2 - 170, 200);
    }
    else
    {
    g.drawString("Player " + playerWon + " Wins!", width / 2 - 165, 200);
    }
    g.setFont(new Font("Arial", 1, 30));
    g.drawString("Press Space to Play Again", width / 2 - 185, height / 2 - 25);
    g.drawString("Press ESC for Menu", width / 2 - 140, height / 2 + 25);
    }
    }
     
    @Override
    public void actionPerformed(ActionEvent e)
    {
    if (gameStatus == 2)
    {
    update();
    }
    renderer.repaint();
    }
     
    public static void main(String[] args)
    {
    pong = new Pong();
    }
     
    @Override
    public void keyPressed(KeyEvent e)
    {
    int id = e.getKeyCode();
    if (id == KeyEvent.VK_W)
    {
    w = true;
    }
    else if (id == KeyEvent.VK_S)
    {
    s = true;
    }
    else if (id == KeyEvent.VK_UP)
    {
    up = true;
    }
    else if (id == KeyEvent.VK_DOWN)
    {
    down = true;
    }
    else if (id == KeyEvent.VK_RIGHT)
    {
    if (selectingDifficulty)
    {
    if (botDifficulty < 2)
    {
    botDifficulty++;
    }
    else
    {
    botDifficulty = 0;
    }
    }
    else if (gameStatus == 0)
    {
    scoreLimit++;
    }
    }
    else if (id == KeyEvent.VK_LEFT)
    {
    if (selectingDifficulty)
    {
    if (botDifficulty > 0)
    {
    botDifficulty--;
    }
    else
    {
    botDifficulty = 2;
    }
    }
    else if (gameStatus == 0 && scoreLimit > 1)
    {
    scoreLimit--;
    }
    }
    else if (id == KeyEvent.VK_ESCAPE && (gameStatus == 2 || gameStatus == 3))
    {
    gameStatus = 0;
    }
    else if (id == KeyEvent.VK_SHIFT && gameStatus == 0)
    {
    bot = true;
    selectingDifficulty = true;
    }
    else if (id == KeyEvent.VK_SPACE)
    {
    if (gameStatus == 0 || gameStatus == 3)
    {
    if (!selectingDifficulty)
    {
    bot = false;
    }
    else
    {
    selectingDifficulty = false;
    }
    start();
    }
    else if (gameStatus == 1)
    {
    gameStatus = 2;
    }
    else if (gameStatus == 2)
    {
    gameStatus = 1;
    }
    }
    }
     
    @Override
    public void keyReleased(KeyEvent e)
    {
    int id = e.getKeyCode();
    if (id == KeyEvent.VK_W)
    {
    w = false;
    }
    else if (id == KeyEvent.VK_S)
    {
    s = false;
    }
    else if (id == KeyEvent.VK_UP)
    {
    up = false;
    }
    else if (id == KeyEvent.VK_DOWN)
    {
    down = false;
    }
    }
     
    @Override
    public void keyTyped(KeyEvent e)
    {
    }
    }
    

Screenshot akhir program ketika dijalankan:


Terima kasih telah berkunjung. Mohon maaf apabila ada kesalahan dalam penulisan. πŸ‘ΎπŸ‘Ύ

Monday, December 7, 2020

Tugas 7 PBO-C "Image Viewer"

    Pada tugas PBO kali ini, saya mencoba membuat sebuah program Image Viewer yang merupakan implementasi GUI dengan komponen AWT dan Swing. Program ini berfungsi untuk menampilkan gambar / foto dan memiliki beberapa filter di dalamnya.

Program ini menggunakan 4 Class yaitu :

  1. Class ImageViewer, merupakan class utama untuk memanggil semua komponen fungsi lain dan tampilan GUI
  2. Class ImagePanel, berisi komponen Swing yang dapat menampilkan OFI Image. Selain itu, class ini juga mengatur tinggi dan lebar panel aplikasi agar menyesuaikan gambar / foto
  3. Class ImageFileManager, berfungsi untuk memuat dan menyimpan gambar / foto
  4. Class OFImage, berfungsi untuk mendefinisikan gambar / foto menjadi OF. Selain itu, terdapat beberapa fungsi untuk edit filter seperti darker, lighter, dan threshold
  • Sourcecode ImageViewer:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import java.io.File;
    public class ImageViewer{
    // static fields:
    private static final String VERSION = "Version 1.0";
    private static JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
    // fields:
    private JFrame frame;
    private ImagePanel imagePanel;
    private JLabel filenameLabel;
    private JLabel statusLabel;
    private OFImage currentImage;
    /**
    * Buat ImageViewer yg ditampilkan pd layar.
    */
    public ImageViewer(){
    currentImage = null;
    makeFrame();
    }
    // ---- implementation of menu functions ----
    // Open function: open a file chooser to select a new image file.
    private void openFile(){
    int returnVal = fileChooser.showOpenDialog(frame);
    if(returnVal != JFileChooser.APPROVE_OPTION){
    return; // Gagal/ batal
    }
    File selectedFile = fileChooser.getSelectedFile();
    currentImage = ImageFileManager.loadImage(selectedFile);
    if(currentImage == null) { // File gambar tdk valid
    JOptionPane.showMessageDialog(frame,
    "File yang dipilih tidak sesuai dengan format yang telah ditentukan.",
    "Image Load Error",
    JOptionPane.ERROR_MESSAGE);
    return;
    }
    imagePanel.setImage(currentImage);
    showFilename(selectedFile.getPath());
    showStatus("File loaded.");
    frame.pack();
    }
    // Close function: close the current image.
    private void close(){
    currentImage = null;
    imagePanel.clearImage();
    showFilename(null);
    }
    // Quit function: keluar dari aplikasi.
    private void quit(){
    System.exit(0);
    }
    //'Darker' function: membuat gambar lebih gelap.
    private void makeDarker(){
    if(currentImage != null){
    currentImage.darker();
    frame.repaint();
    showStatus("Applied: darker");
    }else{
    showStatus("No image loaded.");
    }
    }
    // 'Lighter' function: membuat gambar lebih terang
    private void makeLighter(){
    if(currentImage != null){
    currentImage.lighter();
    frame.repaint();
    showStatus("Applied: lighter");
    }else{
    showStatus("No image loaded.");
    }
    }
    // 'threshold' function: menerapkan threshold filter
    private void threshold(){
    if(currentImage != null){
    currentImage.threshold();
    frame.repaint();
    showStatus("Applied: threshold");
    }else{
    showStatus("No image loaded.");
    }
    }
    // 'Lighter' function: membuat gambar lebih terang
    private void showAbout(){
    JOptionPane.showMessageDialog(frame,
    "ImageViewer\n" + VERSION,
    "About ImageViewer",
    JOptionPane.INFORMATION_MESSAGE);
    }
    // ---- support methods ----
    /**
    * Tampilkan nama file pada label.
    * @param filename Nama file yg akan ditampilkan.
    */
    private void showFilename(String filename){
    if(filename == null){
    filenameLabel.setText("No file displayed.");
    }else{
    filenameLabel.setText("File: " + filename);
    }
    }
    /**
    * Tampilkan status pada frame status bar.
    * @param text Status yang akan ditampilkan.
    */
    private void showStatus(String text){
    statusLabel.setText(text);
    }
    // ---- swing stuff to build the frame and all its components ----
    // Buat Swing frame beserta kontennya.
    private void makeFrame(){
    frame = new JFrame("ImageViewer");
    makeMenuBar(frame);
     
    Container contentPane = frame.getContentPane();
     
    // Specify the layout manager with nice spacing
    contentPane.setLayout(new BorderLayout(6, 6));
     
    filenameLabel = new JLabel();
    contentPane.add(filenameLabel, BorderLayout.NORTH);
     
    imagePanel = new ImagePanel();
    contentPane.add(imagePanel, BorderLayout.CENTER);
     
    statusLabel = new JLabel(VERSION);
    contentPane.add(statusLabel, BorderLayout.SOUTH);
     
    // building is done - arrange the components and show
    showFilename(null);
    frame.pack();
     
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);
    frame.setVisible(true);
    }
    /**
    * Buat main frame's menu bar.
    * @param frame Frame yang akan ditambahkan di menu bar.
    */
    private void makeMenuBar(JFrame frame){
    final int SHORTCUT_MASK =
    Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
     
    JMenuBar menubar = new JMenuBar();
    frame.setJMenuBar(menubar);
     
    JMenu menu;
    JMenuItem item;
     
    // create the File menu
    menu = new JMenu("File");
    menubar.add(menu);
     
    item = new JMenuItem("Open");
    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, SHORTCUT_MASK));
    item.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) { openFile(); }
    });
    menu.add(item);
     
    item = new JMenuItem("Close");
    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, SHORTCUT_MASK));
    item.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) { close(); }
    });
    menu.add(item);
    menu.addSeparator();
     
    item = new JMenuItem("Quit");
    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
    item.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) { quit(); }
    });
    menu.add(item);
     
    // create the Filter menu
    menu = new JMenu("Filter");
    menubar.add(menu);
     
    item = new JMenuItem("Darker");
    item.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) { makeDarker(); }
    });
    menu.add(item);
     
    item = new JMenuItem("Lighter");
    item.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) { makeLighter(); }
    });
    menu.add(item);
     
    item = new JMenuItem("Threshold");
    item.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) { threshold(); }
    });
    menu.add(item);
     
    // create the Help menu
    menu = new JMenu("Help");
    menubar.add(menu);
     
    item = new JMenuItem("About ImageViewer...");
    item.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) { showAbout(); }
    });
    menu.add(item);
     
    }
    }
    
  • Sourcecode OFImage:
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class OFImage extends BufferedImage{
    /**
    * Buat OFImage yg merupakan salinan BufferedImage.
    * @param image Gambar yg akan disalin.
    */
    public OFImage(BufferedImage image){
    super(image.getColorModel(), image.copyData(null),
    image.isAlphaPremultiplied(), null);
    }
    /**
    * Create an OFImage with specified size and unspecified content.
    * @param width The width of the image.
    * @param height The height of the image.
    */
    public OFImage(int width, int height){
    super(width, height, TYPE_INT_RGB);
    }
    /**
    * Atur pixel gambar dg warna yg spesifik (r,g,b).
    * @param x Posisi x dlm pixel.
    * @param y Posisi y dlm pixel.
    * @param col Warna pixel.
    */
    public void setPixel(int x, int y, Color col){
    int pixel = col.getRGB();
    setRGB(x, y, pixel);
    }
    /**
    * Dapatkan value dari warna pada posisi pixel.
    * @param x Posisi x dlm pixel.
    * @param y Posisi y dlm pixel.
    * @return Warna pixel pada posisi yg sudah ditentukan.
    */
    public Color getPixel(int x, int y){
    int pixel = getRGB(x, y);
    return new Color(pixel);
    }
    // Buat gambar lebih gelap.
    public void darker(){
    int height = getHeight();
    int width = getWidth();
    for(int y = 0; y < height; y++) {
    for(int x = 0; x < width; x++) {
    setPixel(x, y, getPixel(x, y).darker());
    }
    }
    }
    // Buat gambar lebih cerah
    public void lighter(){
    int height = getHeight();
    int width = getWidth();
    for(int y = 0; y < height; y++) {
    for(int x = 0; x < width; x++) {
    setPixel(x, y, getPixel(x, y).brighter());
    }
    }
    }
    /**
    * Tampilkan three level threshold operation.
    * Untuk mewarnai ulang gambar dg tiga warna: putih, abu2, hitam
    */
    public void threshold(){
    int height = getHeight();
    int width = getWidth();
    for(int y = 0; y < height; y++){
    for(int x = 0; x < width; x++){
    Color pixel = getPixel(x, y);
    int brightness = (pixel.getRed() + pixel.getBlue() + pixel.getGreen()) / 3;
    if(brightness <= 85){
    setPixel(x, y, Color.BLACK);
    }else if(brightness <= 170){
    setPixel(x, y, Color.GRAY);
    }else{
    setPixel(x, y, Color.WHITE);
    }
    }
    }
    }
    }
    
  • Sourcecode ImagePanel:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.*;
    public class ImagePanel extends JComponent {
     
    //Tinggi dan lebar panel sebelumnya
    private int width,height;
     
    // Buffer gambar internal yang digunakan untuk melukis.
    //Untuk tampilan yang sebenarnya,buffer gambar akan disalin ke layar
    private OFImage panelImage;
     
    //Buat imagepanel baru yang kosong
    public ImagePanel ()
    {
    width =360;
    height=240;
    panelImage=null;
    }
    /**
    * Pilih gambar yang akan ditampilkan panel
    * @param image gambar yang ditampilkan
    */
    public void setImage (OFImage image)
    {
    if (image != null)
    {
    width = image.getWidth();
    height= image.getHeight();
    panelImage=image;
    repaint ();
    }
    }
     
    //Menghilangkan gambar pada panel
    public void clearImage(){
    Graphics imageGraphics = panelImage.getGraphics();
    imageGraphics.setColor(Color.LIGHT_GRAY);
    imageGraphics.fillRect(0, 0, width, height);
    repaint();
    }
    // Metode berikut adalah redefinisi metode yg didapat dari superclasses.
    /**
    * Buat ke layout manager berapa besar yg kita inginkan.
    * (Metode ini dipanggil layout managers utk menempatkan komponen).
    * @return Dimensi yg disukai utk komponen ini.
    */
    public Dimension getPreferredSize(){
    return new Dimension(width, height);
    }
    /**
    * Komponen perlu ditampilkan lagi. Salin gambar internal ke layar.
    * (Metode ini dipanggil Swing screen painter setiap kali mau menampilkan komponen)
    * @param g Konteks grafik yg dpt digunakan utk menggambar pd komponen.
    */
    public void paintComponent(Graphics g){
    Dimension size = getSize();
    g.clearRect(0, 0, size.width, size.height);
    if(panelImage != null) {
    g.drawImage(panelImage, 0, 0, null);
    }
    }
    }
     
    
    
  • Sourcecode ImageFileManager:
    import java.awt.image.*;
    import javax.imageio.*;
    import java.io.*;
    public class ImageFileManager
    {
    //Sebuah konstanta untuk format gambar yang digunakan untuk menulis
    //Format yang tersedia adalah "jpg" dan "png"
    private static final String IMAGE_FORMAT ="jpg";
     
    /**
    * Membaca file gambar dari disk, dan menampilkan nya menjadi sebuah
    * gambar.
    * Metode ini bisa membaca format file JPG dan PNG.
    * Jika ada masalah (misalnya file tersebut tidak ada,tidak sesuai
    * dengan format yang dapat dikodekan, atau kesalahan baca lainnya) metode ini
    * tidak menampilkan apa-apa.
    *
    * @param imageFile File gambar yang akan loading.
    * @return Objek gambar atau null yang tidak dapat dibaca.
    */
    public static OFImage loadImage (File imageFile){
    try {
    BufferedImage image = ImageIO.read (imageFile);
    if (image==null||(image.getWidth(null)<0)){
    //kita tidak bisa memasukkan gambar- kemungkinan karna format salah
    return null;
    }return new OFImage (image);
    }
    catch (IOException exc){
    return null;
    }
    }
     
    /**
    * Tulis file gambar ke disk.Format file adalah JPG.
    * @param image Gambar akan disimpan
    * @param file File yang akan disimpan
    */
    public static void saveImage (OFImage image, File file){
    try {
    ImageIO.write(image,IMAGE_FORMAT,file);
    }
    catch (IOException exc){
    return;
    }
    }
    }
    

Screenshot akhir program ketika dijalankan:


Terima kasih telah berkunjung. Mohon maaf apabila ada kesalahan dalam penulisan. πŸ’ͺ😁