GUI使用JFrame,& JPanel绘制自定义形状

时间:2014-12-06 06:06:49

标签: java swing graphics jframe jpanel

我几乎创建了一个Shape课程,RectangleCircleTriangle延伸ShapeSquare课程延伸{ {1}}。我有代码使用这个主类,但我很难将它转换为GUI,因为我不知道怎么做3号才能使它聚集在一起以及如何制作{{1 }和Circle

  1. Project6类必须扩展g.drawOval(with given x,y & radius)
  2. Project6构造函数必须设置GUI窗口。
  3. 新的抽象方法:draw triangle(given x,y, base and height)应添加到基类和派生类中。
  4. 必须使用JFrame方法
  5. 设置自定义public void display(Graphics g);
  6. 新的JPanel方法必须在GUI窗口上绘制形状,并从paintComponent方法的循环中调用。

  7. display(Graphics g)

    我是否在每节课结束时添加这样的内容? I.E. paintComponentimport 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(); CircleSquare类?

    Triangle

    我无法改变数组的设置方式,但这不应该是扩展JFrame的类吗?

    Rectangle

    我是GUI的新手,所以这有点难,但是这会用于绘制形状吗?但是我得到一个错误,说非静态方法get()不能从静态上下文引用

     @Override
     public void draw(Graphics g) {
      g.drawRect(getXPos(), getYPos(), width, height);
      }
    

1 个答案:

答案 0 :(得分:1)

  1. 您的类扩展了一个永不显示的JFrame
  2. 您应该在JPanel的paintComponent方法中绘制形状,这是添加到JFrame的方法。
  3. 我会使用ArrayList<Shape>,而不是数组,因为这样我就可以在我的集合中添加尽可能多的Shapes而不必担心空项目。
  4. 然后我会在paintComponent方法中重复遍历集合,并使用Graphics2D对象绘制每个Shape。
  5. 关于你的上一个问题,"Do I add something like this at the end of each of my classes? ie(Circle, square, triangle, rectangle class?..."不,不需要“绘图”方法,因为你将使用paintComponent方法进行绘图。