I am trying to draw two lines in Canvas in Java by calling two methods separately, but when I draw the second line, the first one disappears (Java clears the screen). How can i avoid this? I want to see two lines. I saw drawing tutorials (how to make a program like Paint on Windows), where the user uses the mouse to draw lines, and when one line is drawn, the other does not disappear. They simply call the drawing method, and it does not clear the screen.
I would be grateful if anyone could help me. Thanks.
View class
import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class CircuitTracePlotView extends JFrame { private CircuitTracePlot circuitTracePlot; public CircuitTracePlotView() { this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.getContentPane().add(circuitTracePlot = new CircuitTracePlot(), BorderLayout.CENTER); this.pack(); this.setSize(250,250); this.setLocationRelativeTo(null); this.setVisible(true); circuitTracePlot.drawLine(); circuitTracePlot.drawOval(); } } class CircuitTracePlot extends Canvas { private final static short LINE = 1; private final static short OVAL = 2; private int paintType; private int x1; private int y1; private int x2; private int y2; public CircuitTracePlot() { this.setSize(250,250); this.setBackground(Color.WHITE); } private void setPaintType(int paintType) { this.paintType = paintType; } private int getPaintType() { return this.paintType; } public void drawLine() { this.setPaintType(LINE); this.paint(this.getGraphics()); } public void drawOval() { this.setPaintType(OVAL); this.paint(this.getGraphics()); } public void repaint() { this.update(this.getGraphics()); } public void update(Graphics g) { this.paint(g); } public void paint(Graphics g) { switch (paintType) { case LINE: this.getGraphics().drawLine(10, 10, 30, 30); case OVAL: this.getGraphics().drawLine(10, 20, 30, 30); } } }
Main class
import javax.swing.SwingUtilities; import view.CircuitTracePlotView; public class Main { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { CircuitTracePlotView cr = new CircuitTracePlotView(); } }); } }
source share