private void draw_shape() {
Graphics g = getGraphics();
g.drawLine(0, 0, 100, 100);
repaint();
}
In paint method only those graphics are drawn which is a part of paint method because of which I wanted to draw shapes outside of paint method. This code draws the line but it immediately disappeares, I don't understand why this is happening. please help
The line disappears because Swing (or AWT) will call paint(Graphics) or paintComponent(Graphics g) in order to pain the component.
What you need to do is to put your drawing logic on the paint(Graphics) or paintComponent(Graphics g) method. The latter is more advisable.
If you really need to draw things using another method, store an image as a class field and draw this image on the paint or paintComponent methods.
This doens't work because you are getting the current
Graphics
outside of the Swing repaint thread. Basically:Graphics
repaint()
that will call thepaint()
of the component thus discarding all you didTo make it work you should override the
paint
(paintComponent
for Swing) method of your object:and then just call
repaint()
when something has been modified.Because the
paint
method also paints stuff. You should not draw graphics outside the paint method. You should instead override the paint method, like this:Thanks for the help found the answer