When drawing on my extended JPanel I want the size to be variable. I've worked out the code to always outline a 1 pixel margin. My code works but I don't understand why I must adjust the height and width and height of the dimension by -1 when drawing the rectangle.

If I draw a rectangle that has 1,1 as a size it draws a single pixel square so shouldn't drawing the width and the height work without the -1 modifier.

If any one can explain why there is a discrepancy between the size of my extended JPanel or explain a better way to get the exact dimensions of the drawing area I would appreciate it.

public class Engine extends JPanel {
  Engine(){
  }
  @Override
  public void paintComponent(Graphics g){
    Dimension a = this.getSize();
    g.setColor(Color.RED);
    g.drawRect(0, 0, a.width-1, a.height-1);
  }
}
有帮助吗?

解决方案

Remember, most values are 0 based. But instead of having to say, " I want the width of my panel to be 199" so you get a panel that is 200 pixels wide (0-199), Swing allows you to specify 1 based values and makes adjustments internally

If you create a rectangle of 1, 1, 1, 1, your actually creating a rectangle at position 1x1, whose width & height is 1 pixel (1 + 1 would be 2)

其他提示

"or explain a better way to get the exact dimensions of the drawing area I would appreciate it."

Override getPreferredSize() in your JPanel class

@Override
public Dimension getPreferredSize() {
    return new Dimension(300, 300);
}

When you you paint, make use of getWidth() and getHeight(), inherited from the JPanel class. Using these methods, your painting will resize dynamically with the resizing of the panel.

int width = getWidth();
int height = getHeight();
g.fillRect((int)(width * 0.9), (int)(height * 0.9), 
           (int)(width * 0.8), (int)(height * 0.8));

Side Note

  • You should call super.paintComponent inside the paintComponent method so as not to break the paint chain.

  • paintComponent should be protected not public

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
    
    }
    

I've worked out the code to always outline a 1 pixel margin.

Don't do custom painting. Use a Swing Border. See How to Use Borders. You probably want a LineBorder.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top