What is Graphics.drawRect() in Java?
The drawRect method draws a rectangle outline for the given position and size.
We use the graphics context’s current color to draw the rectangle’s outline color.
Syntax
public void drawRect(int x, int y, int width, int height)
Parameters
-
x: This is the rectangle’s x coordinate at which the rectangle is started.
-
y: This is the rectangle’s y coordinate at which the rectangle is started.
-
width: This is the rectangle’s width.
-
height: This is the rectangle’s height.
Return value
This method doesn’t return any value.
Code
The code below demonstrates the use of the drawRect method to draw a rectangle outline:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* A panel maintaining a picture of a Do Not Enter sign.
*/
public class Main extends JPanel {
private static final long serialVersionUID = 7148504528835036003L;
/**
* Called by the runtime system whenever the panel needs painting.
*/
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.magenta);
int x = 10;
int y = 10;
int width = 100;
int height = 100;
//draw rect
g.drawRect(x, y, width, height);
}
/**
* A little driver in case you want a stand-alone application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
var panel = new Main();
panel.setBackground(Color.WHITE);
var frame = new JFrame("testing the drawRect() function");
frame.setSize(800, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.setVisible(true);
});
}
}Code explanation
Line 5: We create a DrawRectExample class which extends the Applet class.
Line 6: We override the paint method. Inside the paint method, we set the current graphics color to green and draw a rectangle starting at the (x=10,y=10) coordinate with a width and height of 100.
The output of the code above is: