我试图在用户输入的任何位置画鱼,但它会说
drawFish.java:38: error: cannot find symbol
outer.add(sPanel1);
或
Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container
at java.awt.Container.checkNotAWindow(Container.java:483)
at java.awt.Container.addImpl(Container.java:1084)
at java.awt.Container.add(Container.java:410)
at drawFish.main(drawFish.java:38)
我在想我需要为每条鱼制作一个新面板,但是如何创建一个循环来创建多个面板?如果那就是问题呢?此外,我应该使用一个采用x和y坐标的方法,以便用户可以更改鱼的位置,并在不同的位置绘制一些鱼。但那不是我正在做的事情。我试图制作一个方法,包括x和y的问题,但后来它说变量不公开,因此不能在paint方法中使用。我会很感激所有的解释,因为我想要理解我正在做的一切。
public class drawFish extends JPanel {
int x = Integer.parseInt(JOptionPane.showInputDialog(null, "What is the x location of the fish? "));
int y = Integer.parseInt(JOptionPane.showInputDialog(null, "What is the y location of the fish? "));
int w = 200;
int h = 100;
int a = x + 20;
int b = y + 30;
int d = 50;
public drawFish() {
setPreferredSize(
new Dimension(400,400));
}
public void paint(Graphics g) {
g.setColor(Color.GREEN);
g.fillOval(x, y, w, h);
g.fillOval((w-5), y, d, h);
g.setColor(Color.BLACK);
g.fillOval(a, b, 25, 25);
}
public static void main(String[] args) {
MyFrame frame1 = new MyFrame("Drawing Fish");
JPanel outer = new JPanel();
int fn = Integer.parseInt(JOptionPane.showInputDialog(null, "How many fish would you like to draw? "));
for(int i=0; i<fn; i++){
drawFish sPanel1 = new drawFish();
}
outer.add(sPanel1);
frame1.add(outer);
frame1.pack();
frame1.setVisible(true);
}
}
答案 0 :(得分:3)
draw(Graphics g)
方法,以便在被要求时可以在当前位置绘制自己。ArrayList<Fish>
,并在列表中填入Fish对象。paintComponent(Graphics g)
方法(不是paint方法)中,循环遍历它包含的每个Fish对象上调用draw(g)
的ArrayList。super.paintComponent(g)
作为绘图JPanel的paintComponent(Graphics g)
方法的第一行,以便删除旧图纸。答案 1 :(得分:0)
sPanel1变量的范围在您退出循环后立即结束。
因此替换
for(int i=0; i<fn; i++){
drawFish sPanel1 = new drawFish();
}
outer.add(sPanel1);
与
for(int i=0; i<fn; i++){
drawFish sPanel1 = new drawFish();
outer.add(sPanel1);
}
现在将添加所有面板。
还要考虑使用LayeredPane。 希望这会有所帮助。