How to make a canvas in Java Swing?


To make a canvas with Java Swing, use the Graphics2D class −

public void paint(Graphics g) {
   Graphics2D graphic2d = (Graphics2D) g;
   graphic2d.setColor(Color.BLUE);
   graphic2d.fillRect(100, 50, 60, 80);
}

Above, we have created a rectangle and also added color to it.

The following is an example to make a canvas in Java −

Example

package my;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo extends JPanel {
   @Override
   public void paint(Graphics g) {
      Graphics2D graphic2d = (Graphics2D) g;
      graphic2d.setColor(Color.BLUE);
      graphic2d.fillRect(100, 50, 60, 80);
   }
   public static void main(String[] args) {
      JFrame frame = new JFrame("Demo");
      frame.add(new SwingDemo());
      frame.setSize(550, 250);
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
}

This will produce the following output −

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements