0

I am interested in drawing a Rectangle object using AWT methods (I know, it's old). I have looked at other code on the forum that has answers, but they are not working for me. Here is what I am looking to do...

paint(Graphics g) {
    Rectangle r = new Rectangle(5,5,20,20);
    g.drawRect(r.getX(),r.getY(),r.getWidth(),r.getHeight());
}

But what I have to do is:

g.drawRect((int)r.getX().........);

and cast every value to an int. Am I doing something wrong? The code examples that I found have the solution without the casting. If I don't cast, I get an error. Surely, there should be something more simple.

Thanks in advance.

Nick
  • 25
  • 8
  • Based on the documentation, Rectangle constructors accepts int values. https://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html – Nasser Tahani Apr 03 '18 at 13:56
  • Yes. The constructor accepts int values, but the get functions return doubles. drawRect accepts ints. – Nick Apr 03 '18 at 14:09

3 Answers3

0

From javadoc here we can see that those methods return a double value, and the method drawRect in Graphics uses integers as parameters, as documented here, so you have to cast the double to an integer.

Coreggon
  • 505
  • 2
  • 5
  • 17
  • I understand that. Here, the answer was upvoted 14 times, but is incorrect, then? https://stackoverflow.com/questions/11745595/how-to-create-a-rectangle-object-in-java-using-g-fillrect-method – Nick Apr 03 '18 at 14:10
  • @Nick That's indeed odd. I added a comment there. Let's see how this sorts itself out. – Marco13 Apr 03 '18 at 21:31
0

You can cast Graphics to Graphics2D to use its draw() method to draw 'java.awt.shap' objects like this:

paint(Graphics g) {
   Grahpics2D g2 = (Graphics2D) g;
   Shape s = new Rectangle(5,5,20,20);
   g2.draw(s);
}
Nasser Tahani
  • 725
  • 12
  • 33
  • 1
    java.awt.Component doesn’t have a `paint(Graphics2D)` method, so writing a method with that signature will be meaningless. Perhaps you meant to recommend casting the Graphics object given to `paint(Graphics)` to a Graphics2D object? – VGR Apr 03 '18 at 15:05
0

This is an easy way to do it. I figured it out:

paint(Graphics g) {
    Rectangle r = new Rectangle(5,5,30,30);
    g.drawRect(r.x,r.y,r.width,r.height);
}
Nick
  • 25
  • 8
  • Assuming that this is "pseudocode". You would not need to create the `Rectangle` object just to call the `drawRect` method. But broadly speaking, casting the `Graphics` to `Graphics2D` gives you many nice new options, including the option to just to `graphics2D.draw(new Rectangle(...))` and much more. – Marco13 Apr 03 '18 at 21:33