Search code examples
javacanvasborderdimension

How do I draw a border on a canvas in Java, by using an object from the Dimension class?


For an assignment I needed to draw a border around a 500x600 canvas on 20px from the sides, so I did it manually:

//upper line
myCanvas.drawLine(20, 20, 580, 20);

//bottom line
myCanvas.drawLine(20, 480, 580, 480);

//west line
myCanvas.drawLine(20, 20, 20, 480);

//east line
myCanvas.drawLine(580, 20, 580, 480);

But now I have to it using an object from the Dimension class, so that whenever the canvas size changes, the border changes too. So

myCanvas.drawLine(20, 20, (myCanvas.getHeight() - 20), 20)

But how do I do this? Everytime I get: cannot find symbol - method getHeight()


Solution

  • You could simply use a number of Borders (How to use Borders).

    Something like...

    myCanvas.setBorder(new CompoundBorder(new EmptyBorder(20, 20, 20, 20), new LineBorder(Color.BLACK));
    

    Assuming that "canvas" extends from a JComponent of course...