NewProgrammer
NewProgrammer

Reputation: 1

How to make image stay after resizing?

I'm new to Java, and I'm trying to figure out how to make sure my image stays on the screen after resizing the window. I've tried looking for the answer before posting, but I can't seem to find what I'm looking for.

What is the best way to do this would be and how I should do it?

Here is what I deem the "important" code:

public void mouseDragged(MouseEvent DrawingEvent) {
    Graphics g = getGraphics();
    g.drawLine(DrawPoint.x, DrawPoint.y, DrawingEvent.getX(), DrawingEvent.getY());
    DrawPoint = new Point(DrawingEvent.getX(), DrawingEvent.getY());
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
}
}

Upvotes: 0

Views: 77

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

To get the image to stay:

  • Don't use a Graphics object obtained by calling getGraphics() on a Swing component. These objects are short-lived and risk causing disappearing images or NullPointerExceptions.
  • Instead draw with the Graphics object given by the JVM to your JPanel's paintComponent method, just as the Swing drawing tutorials tell you.
  • You can draw on a BufferedImage, and then display that image within your JPanel's paintComponent method -- likely the easiest way to achieve what you're trying to do.
  • Or you can create an ArrayList of non-GUI logical objects such as Points or Line2D, and then use these collections to direct how to draw within the JPanel's paintComponent method.

For example

Upvotes: 2

Related Questions