- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 can we draw a rounded rectangle using the Graphics object in Java?
Graphics Class
- In Java, the drawing takes place via a Graphics object, this is an instance of the java.awt.Graphics class.
- Each Graphics object has its own coordinate system and all the methods of Graphics including those for drawing Strings, lines, rectangles, circles, polygons and etc.
- We can get access to the Graphics object through the paint(Graphics g) method.
- We can use the drawRoundRect() method that accepts x-coordinate, y-coordinate, width, height, arcWidth, and arc height to draw a rounded rectangle.
Example
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class RoundedRectangleTest extends JFrame { public RoundedRectangleTest() { setTitle("RoundedRectangle Test"); setSize(350, 275); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.drawRoundRect(10, 50, 150, 150, 50, 30); // to draw a rounded rectangle. } public static void main(String []args) { new RoundedRectangleTest(); } }
Output
Advertisements