Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem in generating the border of a rectangle in Java?

I am using java.awt.geom.Rectangle2D.Double class to generate a rectangle. I want to generate a rectangle which is filled with a color (say green) and have a border (outline).

Now the problem is if I call

g2.draw(new Rectangle2D.Double(....)); // g2 is an instance of Graphics2D

then it doesn't fill the rectangle and when I call

g2.fill(new Rectangle2D.Double(....)); // g2 is an instance of Graphics2D

then id doesn't generate border.

like image 213
Yatendra Avatar asked Jan 08 '10 12:01

Yatendra


People also ask

How do you outline a rectangle in Java?

In Java, to draw a rectangle (outlines) onto the current graphics context, we can use the following methods provided by the Graphics/Graphics2D class: drawRect(int x, int y, int width, int height) draw3DRect(int x, int y, int width, int height, boolean raised) draw(Rectangle2D)

How do I add a border to a JFrame?

Yes you can draw the borders around the undecorated JFrame. Just simply get the root pane of the JFrame and set its borders by setBorder(Border border) method. As far as I know, this will only shrink down the root pane so it can draw the border inside the frame itself.

How do you add a border to a JPanel?

createLineBorder() − To create a line border. JPanel. setBorder(border) − To set the desired border to the JPanel.


2 Answers

To do this, render the rectangle twice, first the fill and then the border (draw).

Rectangle2D rect = new Rectangle2D.Double(...);
g2.setColor(Color.white);
g2.fill(rect);
g2.setColor(Color.black);
g2.draw(rect);
like image 88
Samuel Sjöberg Avatar answered Sep 20 '22 12:09

Samuel Sjöberg


How about doing both? Draw the filled rectangle first and then draw the outline one over the top.

like image 44
Dan Dyer Avatar answered Sep 19 '22 12:09

Dan Dyer