我一直在寻找类似线程的答案,但我无法找出我的代码有什么问题。
我正在尝试制作一个agar.io模拟器而琼脂对象不会绘制。食物吸引但不管我做什么,琼脂都不会画。
琼脂类代码:
import java.awt.*;
import java.awt.event.*;
public class Agar {
//instance field
public static final int DEFAULT_SIZE = 1000, DEFAULT_X =
ArenaPanel.PANEL_WIDTH/2, DEFAULT_Y = ArenaPanel.PANEL_HEIGHT/2;
private int x, y, size;
private Color clr;
public Agar(Color c) {
x = DEFAULT_X;
y = DEFAULT_Y;
clr = c;
}
public void move() {
//blank for now, not used yet
}
//grows by 10% width
public void grow() {
size += 10;
}
public void draw(Graphics fred) {
fred.setColor(clr);
fred.fillOval(0,0,size,size);
fred.setColor(Color.black);
fred.drawOval(0,0,size,size);
}
}
小组类代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class ArenaPanel extends JPanel {
//instance field
public static final int PANEL_WIDTH = 1000, PANEL_HEIGHT = 500;
private ArrayList<Food> food;
private Timer foodAdder;
private Agar agar;
public ArenaPanel() {
//agar stuff
agar = new Agar(getRandomColor());
//food stuff
food = new ArrayList<Food>();
//add some initial food
for (int i = 0; i < 50; i++)
addRandomFood();
//"this will last a while"
foodAdder = new Timer(3000, new FoodAdder());
foodAdder.start();
//listeners
addComponentListener(new ResizeListener());
//more basic stuff
setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
setBackground(Color.white);
}
public void paintComponent(Graphics fred) {
super.paintComponent(fred);
agar.draw(fred);
for (int i = 0; i < food.size(); i++)
food.get(i).draw(fred);
}
//put it here so I can use it for both agar and food
private Color getRandomColor() {
int rand = (int)(Math.random()*7);
Color c;
switch (rand) {
case 0:
c = Color.red;
break;
case 1:
c = Color.orange;
break;
case 2:
c = Color.yellow;
break;
case 3:
c = Color.green;
break;
case 4:
c = Color.cyan;
break;
case 5:
c = Color.blue;
break;
default:
c = Color.pink;
}
return c;
}
private void addRandomFood() {
int x = (int)(Math.random()*PANEL_WIDTH);
int y = (int)(Math.random()*PANEL_HEIGHT);
food.add(new Food(x,y,getRandomColor()));
}
private class FoodAdder implements ActionListener {
public void actionPerformed(ActionEvent e) {
addRandomFood();
repaint();
}
}
private class ResizeListener extends ComponentAdapter {
public void componentResized(ComponentEvent e) {
setPreferredSize(getSize());
}
}
}
我尝试调试(将System.out.println命令放入draw(),paintComponent(),琼脂的构造函数),所有方法实际上都正常运行。所以我想也许它只是没有出现,但即使我尝试将琼脂的颜色改为黑色方形(这应该与彩色圆形食物形成对比)位于0,0但它仍然没有显示。
这可能是什么问题?
答案 0 :(得分:1)
它的大小为零。呼叫方法成长至少一次。