我几乎创建了一个Shape
课程,Rectangle
,Circle
,Triangle
延伸Shape
,Square
课程延伸{ {1}}。我有代码使用这个主类,但我很难将它转换为GUI,因为我不知道怎么做3号才能使它聚集在一起以及如何制作{{1 }和Circle
。
g.drawOval(with given x,y & radius)
类draw triangle(given x,y, base and height)
应添加到基类和派生类中。JFrame
方法public void display(Graphics g);
JPanel
方法必须在GUI窗口上绘制形状,并从paintComponent
方法的循环中调用。display(Graphics g)
我是否在每节课结束时添加这样的内容? I.E. paintComponent
,import javax.swing.*;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Project6 extends JFrame {
private Shape [] thearray = new Shape[100];
public static void main (String [] args) {
Project6 tpo = new Project6();
tpo.run();
}
public void run () {
int count = 0;
thearray[count++] = new Circle(20, 20, 40);
thearray[count++] = new Triangle(70, 70, 20, 30);
thearray[count++] = new Rectangle(150, 150, 40, 40);
thearray[count++] = new Square(100, 100, 50, 75);
for (int i = 0; i < count; i ++ ) {
thearray[i].display();
}
int offset = 0;
double totalarea = 0.0;
while (thearray[offset] != null) {
totalarea = totalarea + thearray[offset].area();
offset++;
}
System.out.println("The total area for " + offset + " Shape objects is " + totalarea);
}
public Project6() {
JFrame frame = new JFrame();
frame.setSize(800, 700);
frame.setTitle("Shapes: Circle, Triangle, Rectangle, Square");
frame.setLocationRelativeTo(null); //Center Frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static class MyPanel extends JPanel {
public static JPanel showJPanel(Graphics g) {
panel = new MyPanel();
return panel;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i = 0; i < thearray.length && thearray[i] != null; i++) {
thearray[i].display();
,Circle
,Square
类?
Triangle
我无法改变数组的设置方式,但这不应该是扩展JFrame的类吗?
Rectangle
我是GUI的新手,所以这有点难,但是这会用于绘制形状吗?但是我得到一个错误,说非静态方法get()不能从静态上下文引用
@Override
public void draw(Graphics g) {
g.drawRect(getXPos(), getYPos(), width, height);
}
答案 0 :(得分:1)
ArrayList<Shape>
,而不是数组,因为这样我就可以在我的集合中添加尽可能多的Shapes而不必担心空项目。"Do I add something like this at the end of each of my classes? ie(Circle, square, triangle, rectangle class?..."
不,不需要“绘图”方法,因为你将使用paintComponent方法进行绘图。