【发布时间】:2015-07-13 03:18:26
【问题描述】:
看看 Circle 类。每次 if 语句评估为 true 时,我都希望计数器加一。我正在尝试使用 set 方法来为我完成这项工作,但是当我在 main 方法中检查 counter 的值时,它并没有计数。有小费吗?
package circle;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JApplet;
public class Shapes extends JApplet {
private int squareLength = 0;
private int count = 0;
private double areaSquares = 0;
private double areaCircle = 0;
public void setPixelDimOfSquare(int width) {squareLength = width;}
public void setCount(int n) {count = n++;}
public int getCount() {return count;}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
//shapes
//adds sphere (xcoord,ycoord,width of framing rect, height of framing rect)
g2.draw(new Ellipse2D.Double(0, 0, 1000, 1000));
//builds square grid and counts number of whole squares in the circle.
for (int i = 0; squareLength*i <= 1000; i++){
for (int j = 0; squareLength*j <= 1000; j++) {
if(new Ellipse2D.Double(0,0,1000,1000).contains(new Rectangle2D.Double(squareLength*i,squareLength*j,squareLength,squareLength))){
setCount(1);
g2.setColor(Color.black);
g2.fillRect(squareLength*i,squareLength*j,squareLength,squareLength);
} else {
g2.drawRect(squareLength*i,squareLength*j,squareLength,squareLength);
}
}
}
System.out.println("Shape: There are " + getCount() + " squares in the circle.");
}
public double areaSquares() {
areaSquares = Math.pow(squareLength,2) * count;
return areaSquares;
}
public double areaCircle() {
areaCircle = Math.PI * Math.pow(1000, 2);
return areaCircle;
}
}
现在是主要的
package circle;
import java.util.Scanner;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class Main {
public static void main(String[] args) {
//Gets the desired number of boxes
//Scanner sc = new Scanner(System.in);
//System.out.print("Please enter number of boxes:");
//double boxes = sc.nextDouble();
// Builds frame for shapes.
Shapes shape = new Shapes();
shape.setPixelDimOfSquare(10);
JFrame frame = new JFrame("Draw Shapes Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(shape);
frame.pack();
frame.setSize(1000,1000);
frame.setVisible(true);
System.out.println("Main: There are " + shape.getCount() + " squares in the circle.");
}
}
【问题讨论】:
-
如果您打算使用基于窗口的容器,
Shapes不应从JApplet扩展。您应该使用更像JPanel的东西并覆盖它的paintComponent方法(并在进行任何自定义绘画之前调用super.paintComponent) -
可能当 "System.out.println("Main: There are " + shape.getCount() + " squares in the circle.");" 什么都没有已经画好了……
-
@MadProgrammer 我会考虑使用绘画组件。 paint() 绝对是在为我绘制形状。我可以在框架中看到它们。
-
A
Applet在概念上是它自己的顶级容器,假设由 Web 浏览器管理,它有自己的初始化和管理要求,超出了基于 Windows 的容器的范围跨度>
标签: java methods get set accessor