program2

program2

View Answers

July 21, 2009 at 4:13 PM

Hi Friend,

We have used translate(int x,int y) method to translate the rectangle.Try the following code:

import java.awt.*;
import javax.swing.*;

public class RectangleExample extends JPanel {

public void paint(Graphics g) {
super.paint(g);
int x=20,y=20,width=80,height=50;
Graphics2D g2d = (Graphics2D) g;
int area=width*height;
int p=width+height;
int perimeter=p*2;
g2d.setColor(new Color(150, 150, 150));
g2d.fillRect(x, y, width, height);
g2d.translate(150, 50);
g2d.fillRect(x, y, width, height);
g2d.drawString("Area= "+area+", Perimeter= "+perimeter+".",50,100);

}
public static void main(String[] args) {
JFrame frame = new JFrame("RectangleExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new RectangleExample());
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Thanks









Related Tutorials/Questions & Answers:
program2 - Java Beginners
program2  Q; Use the point class to define a rectungle class where a rectangle lies. I. Calculate the parameter and area of the rectangle. II. Translate the rectangle along the X-axis, Y-Axis and X-Y axis.  

Ads