I have drawn a box within my JPanel so that it resizes appropriately when the JFrame is resized.

This is how I implement it:

public void drawBox(Graphics g){
    int num1 = getWidth()/4, num2 = getHeight()/4, num3 = getWidth() - num1, 
            num4 = getHeight() - num2;
    g.drawLine(num1, num2, num3, num2);
    g.drawLine(num1, num2, num1, num4);
    g.drawLine(num3, num2, num3, num4);
    g.drawLine(num1, num4, num3, num4);     

What I have done works but is there a better way to do this? I'd like general feedback, cleaner code would be my main priority though.


Naming and Initialization

It's very hard to read when many variables are initialized on a single line.

numN naming pattern is also confusing. Since they correspond to coordinates, why not name them like this?

final int topLeftX = getWidth()/4
final int topLeftY = getHeight()/4
final int bottomRightX = ...

The 4 number may also be extracted into a vairable.

Draw a Rectangle

If I'm not mistaken, with drawLine(args) you are trying to draw a rectangle. It may be replaced with the respective method call, thus reducing the stuff to a single line:

g.drawRect(topLeftX, topLeftY, width, height);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.