我對Java相當陌生,我試圖創建一個程序,在這個程序中,計算機繪製隨機的圓圈,矩形和線條,然後計算它們的正下方顯示的數字。JPanel實際上如何工作?
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不管它們被稱爲時。我不明白它是如何工作
你有程序邏輯的paintComponent方法,通常是一個壞主意的內部,並且在邏輯您重新零出你的int字段在方法的開始。你的實際任務狀態你必須做什麼? – 2013-05-11 15:29:50