Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −

Advertisements