【问题标题】:Creating multiple panels in a frame?在一个框架中创建多个面板?
【发布时间】:2014-02-26 07:32:15
【问题描述】:

我试图在用户输入的任何位置画鱼,但它会说

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);
 }
} 

【问题讨论】:

    标签: java user-interface methods panel


    【解决方案1】:
    • 不要做很多 JPanel,只做一个绘图 JPanel。
    • 创建一个既不是 JPanel 也不是组件但具有 draw(Graphics g) 方法的 Fish 类,以便在被要求时可以在当前位置绘制自身。
    • 给您的 JPanel 一个 ArrayList&lt;Fish&gt; 并用 Fish 对象填充列表。
    • 在您的 JPanel 的 paintComponent(Graphics g) 方法(不是 paint 方法)中,循环遍历 ArrayList 对它包含的每个 Fish 对象调用 draw(g)
    • 请务必调用 super.paintComponent(g) 作为您绘图 JPanel 的 paintComponent(Graphics g) 方法的第一行,以便删除旧绘图。
    • 您的 for 循环逻辑已关闭。如果您要在 for 循环内创建对象,则需要将它们添加到 从循环内的东西中。否则你要做的就是创建对象并丢弃它们,永远不要使用它们。
    • 您需要学习并坚持 Java 命名约定。类名(例如 DrawFish)应以大写字母开头,方法和变量应以小写字母开头。

    【讨论】:

      【解决方案2】:

      退出循环后,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。 希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-03
        • 1970-01-01
        • 1970-01-01
        • 2021-12-20
        • 1970-01-01
        • 1970-01-01
        • 2011-02-26
        • 1970-01-01
        相关资源
        最近更新 更多