I'm trying to draw 2 triangles with Graphics 2d. When running the first segment, it's totally correct. But if I run the second segment that I add a panel below the "Graph", the triangles disappear. Could anybody help me with the issue?
Here's the code.
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Path2D;
public class Draw_A_Triangle extends JPanel {
public Draw_A_Triangle() {}
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
work(g2d, Color.RED,30,45,60,90,60,90);
work(g2d, Color.blue,15,22.5,30,45,30,45);
}
// set a method to draw the 2 triangles
public void work(Graphics2D g2d, Color c, double x1, double x2, double x3, double y1, double y2, double y3) {
Path2D.Double p = new Path2D.Double();
g2d.setColor(c);
p.moveTo(x1, y1);
p.lineTo(x2, y2);
p.lineTo(x3, y3);
g2d.fill(p);
g2d.draw(p);
}
public static void main(String[] args) {
//set the JFrame
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Draw Triangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.white);
frame.setSize(200, 200);
// //segment 1
// Draw_A_Triangle panel = new Draw_A_Triangle();
// frame.add(panel);
// frame.setVisible(true);
// segment 2
Draw_A_Triangle panel = new Draw_A_Triangle();
JPanel p = new JPanel();
p.add(panel);
frame.add(p);
frame.setVisible(true);
}
}