In Java: I have a class Triangle that inherits from class Shape, within class Sh
ID: 3925491 • Letter: I
Question
In Java:
I have a class Triangle that inherits from class Shape, within class Shape it has a method draw() which simply paints the background a color, in class Triangle it draw a triangle, I'm having problems getting this to work, this is what I have so far:
public class Shape {
//instance variables
private static double x;
private static double y;
private Color color;
public void draw(Graphics g){
JPanel panel = new javax.swing.JPanel();
JFrame app = new JFrame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.add(panel);
app.setSize(400,400);
panel.setBackground(Color.CYAN);
app.setVisible(true);
}
}
public class Triangle extends Shape{
public void draw(Graphics g){
Point p[] = new Point[3];
p[0] = new Point((int)x1, (int)y1);
p[1] = new Point((int)(x1+sideB), 0);
p[2] = new Point((int) (Math.cos(angleA) * sideC), (int) (Math.sin(angleA) * angleC));
int[] xCoord = {p[0].x,p[1].x,p[2].x};
int[] yCoord = {p[0].y,p[1].y,p[2].y};
g.drawPolygon(xCoord,yCoord,3);
}
I have a class draw that extends JPanel to override paint component but I'm not sure how to get it to work with these :(
Obviously the code above doesn't have the bulk of the classes, the other methods and constructors, if anyone needs them for the solution let me know and I will post them..
Explanation / Answer
Define the class Shape to extend the awt.Frame class and override the paint(Grpahics g) method. Refer below:
package chegg.draw;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Shape extends Frame {
public Shape() {
super("Shape");
setSize(400, 400);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
}
@Override
public void paint(Graphics g) {
super.paint(g);
setBackground(Color.BLUE);
}
public static void main(String[] args) {
Shape shape = new Triangle();
shape.setVisible(true);
}
}
Now, define the class Triangle to extend from the Shape class. Override the paint(Grpahics g) method and implement the triangle drawing logic. Refer below:
package chegg.draw;
import java.awt.Graphics;
import java.awt.Point;
public class Triangle extends Shape {
@Override
public void paint(Graphics g) {
super.paint(g);
Point p[] = new Point[3];
p[0] = new Point((int) 100, 100);
p[1] = new Point((int) 300, 100);
p[2] = new Point((int) 200, 300);
int[] xCoord = { p[0].x, p[1].x, p[2].x };
int[] yCoord = { p[0].y, p[1].y, p[2].y };
g.drawPolygon(xCoord, yCoord, 3);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.