java定义对象数组

import java.awt.*;import javax.swing.*;
public class CreatBall extends JPanel {
public static Balls ball[];
int x,y,radius;
Color c;

public static void main(String args[]){

JFrame f = new JFrame("ceshi");
f.add(new CreatBall());
f.setSize(300,200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}

public CreatBall(){

super();

ball[0] = new Balls(10,10,20,Color.black);
ball[1] = new Balls(40,40,20,Color.blue);

}

public void paint(Graphics g){

super.paint(g);

this.drawBall(x, y, radius, g, c);
}

public void drawBall(int x,int y,int radius,Graphics g,Color c){

for(int i = 0;i<=1;i++){

g.setColor(ball[i].getColor());
g.fillOval(ball[i].getX(), ball[i].getY(), ball[i].getRadius(), ball[i].getRadius());
}
}

}

import java.awt.*;
import javax.swing.*;
public class Balls {

private int x,y,radius;
private Color color;

Balls(int x,int y,int radius,Color color){

this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
}

public int getX(){

return x;
}
public int getY(){

return y;
}
public int getRadius(){

return radius;
}
public Color getColor(){

return color;
}

}
为什么无法运行啊。。。。。

第1个回答  2013-03-13
package com.panel.test;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CreatBall extends JPanel {
private static final long serialVersionUID = 1L;
public static Balls ball[] = new Balls[2]; // 此处要初始化数组,否则在构造方法里报空指针错误
int x, y, radius;
Color c;
public CreatBall() {
super();
ball[0] = new Balls(10, 10, 20, Color.black);
ball[1] = new Balls(40, 40, 20, Color.blue);
}
public static void main(String args[]) {
JFrame f = new JFrame("ceshi");
f.add(new CreatBall());
f.setSize(300, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
this.drawBall(x, y, radius, g, c);
}
public void drawBall(int x, int y, int radius, Graphics g, Color c) {
for (int i = 0; i <= 1; i++) {
g.setColor(ball[i].getColor());
g.fillOval(ball[i].getX(), ball[i].getY(), ball[i].getRadius(),
ball[i].getRadius());
}
}
}
class Balls {
private int x, y, radius;
private Color color;
Balls(int x, int y, int radius, Color color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getRadius() {
return radius;
}
public Color getColor() {
return color;
}
}

// Create 单词拼错了,不是creat,而是create.
//Balls 和 CreatBall类放在一个文件里面的话,不能用public修饰,分开的话可以。追问

还是无法运行啊。。你的代码

追答

不太清楚你原来的配置,试试多调试,多看看java基础。

本回答被提问者采纳
第2个回答  2013-03-13
你的createball是继承Jpanel类
createball的构造方法里根本就没把balls加在面板里呀
public CreatBall(){
super();
ball[0] = new Balls(10,10,20,Color.black);
ball[1] = new Balls(40,40,20,Color.blue);
}
你只是把这个ball实例化了而以
第3个回答  2013-03-13
List<User> users=new ArrayList<User>();