fillRect() 使用哪个坐标?

Which coordinates does fillRect() use?

这是我与 AWT/Swing 的第一个项目。我正在尝试设计一个简单的元胞自动机。我在选择布局管理器时遇到了一些问题,现在我正在使用 GridLayout,因为它最接近我想要的。但是,当尝试在 JPanel 中放置一个单元格时,坐标无法按我预期的那样工作。也许我不应该从 JComponent 扩展并使用 fillRect()?或者 GridLayout 不是我需要的布局?主要问题是点(0,0)似乎是"moving"。 fillRect 与 GridLayout 冲突吗?

注意 1:我试过 GridBagLayout 但没有用(因为我不知道如何配置它)。我也尝试了 add(component, x, y) 方法,但它没有用。

注意 2:我没有 post 关于细胞状态的代码,因为它不相关。

编辑:好吧,我在单个 public class 中写了一个示例,我认为我不能更简洁并重现相同的结果。

解法: https://docs.oracle.com/javase/tutorial/uiswing/painting/refining.html

这是我的代码:

public class Example{
    class Cell extends JComponent{
        private int x = 0;    //Cell position ?
        private int y = 0;
        public Cell(int x, int y){
            this.x = x;
            this.y = y;
        }
        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            //draw cell
            g.setColor(Color.white);
            g.fillRect(x,y,15,15);        
        }
    }
    Example(){
        JFrame frame = new JFrame("title");
        frame.setBackground(Color.black);
        frame.getContentPane().setPreferredSize(new Dimension(300,300));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        JPanel box = new JPanel(new GridLayout(20,20)){
            @Override
            public void paintComponent(Graphics g){
                super.paintComponent(g);
                setBackground(Color.black);
                //draw grid
                for(int i = 0; i <= this.getHeight(); i += 15){
                    g.drawLine(0,0+i,getWidth(),0+i);
                }
                for(int i = 0; i <= this.getWidth(); i += 15){
                    g.drawLine(0+i,0,0+i,getHeight());
                }
            }
        };
        /*box.add(new Cell(0,0)); //TEST 1
        box.add(new Cell(0,0));
        box.add(new Cell(0,0));
        box.add(new Cell(0,0));*/
        box.add(new Cell(0,0));   //TEST 2
        box.add(new Cell(15,0));
        box.add(new Cell(30,0));
        box.add(new Cell(45,0));
        frame.add(box);
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args){
        new Example();
    }
}

这是对应于测试 1 和测试 2 的结果:

TEST 1

TEST 2

所有绘画都是相对于包含自定义绘画的组件完成的,而不是您添加组件的面板。

所以在你的情况下,只需从 (0, 0) 开始绘画。

布局管理器会将 Cell 定位在布局管理器确定的位置。

注:

一种绘画方法,仅供绘画使用。它不应该像您当前的 Box class 那样创建组件。

基本逻辑是:

  1. 创建具有所需布局的面板。
  2. 向面板添加组件。
  3. 添加到面板的组件的 size/location 将由布局管理器决定。因此,在您的 Cell class 中,您需要实现 getPreferredSize() 方法,以便布局管理器可以使用此信息来定位添加到面板的每个组件。

如果你想在面板上的不同位置管理绘画,那么就不要使用真正的组件。相反,您保留要绘制的形状的 ArrayList。每个形状都将包含应绘制的位置。然后在 paintComponent() 方法中遍历 ArrayList 以绘制每个形状。有关此方法的示例,请查看 Custom Painting Approaches.

中的 Draw On Component 示例