我对 Java 很陌生,我正在尝试创建一个程序,在该程序中计算机随机绘制圆形、矩形和线条,然后计算它们正下方显示的数量。
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JPanel;
public class Shapes extends JPanel{
` private int noOfCircles;
private int noOfLines;
private int noOfRect;
public void paintComponent(Graphics g){
Random rand = new Random();
super.paintComponent( g );
int x = 10;
int y = 10;
noOfCircles = 0;
noOfLines = 0;
noOfRect = 0;
for(int i = 0; i<10; i++){
int choice = rand.nextInt(3);
if(choice == 0){
noOfLines++;
g.drawLine(x, y, i*10+50, i+100);
}
else if(choice == 1){
noOfRect++;
g.drawRect(i*20, y*20, x*10, y *10);
}
else{
noOfCircles++;
g.drawOval(x*10, i*20, x*10, y*10);
}
x+=5;
y+=5;
}
System.out.println(status());
}
public String status(){
String message = String.format("Circles : %d; Rect : %d; Lines : %d;", noOfCircles, noOfRect, noOfLines);
return message;
}
}
和
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JFrame;
public class ShapesTest {
public static void main( String args[] ){
Shapes panel = new Shapes();
JFrame app = new JFrame();
JLabel statusBar = new JLabel();
String message = panel.status();
statusBar.setText(message);
statusBar.setSize(400, 20);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.add(panel);
app.add(statusBar, BorderLayout.SOUTH);
app.setSize( 400, 400 );
app.setVisible(true);
}
}
问题是 Shape 类在调用它们时总是返回 noOfCircles、noOfLines、noOfRect = 0 。我不明白它实际上是如何工作的