如何在框架中心设置对象?

How to set object in center of frame?

我是编程新手。我不确定如何将对象放在框架的中央。这是我走了多远:

public class LetSee extends JPanel {

     public void paintComponent(Graphics g) {

          int row;   // Row number, from 0 to 7
          int col;   // Column number, from 0 to 7
          int x,y;   // Top-left corner of square
          for ( row = 0;  row < 5;  row++ ) {

             for ( col = 0;  col < 5;  col++) {
                x = col * 60;
                y = row * 60;
                if ( (row % 2) == (col % 2) )
                   g.drawRect(x, y, 60, 60);

                else
                   g.drawRect(x, y, 60, 60);

             } 

          } // end for row

      }
 }



public class LetSeeFrame extends JFrame {

    public LetSeeFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1900, 1000);
        setVisible(true);
        LetSee let = new LetSee();
        let.setLayout(new BorderLayout());
        add(let,BorderLayout.CENTER);
        setLocationRelativeTo(null);  
    }

    public static void main(String[] args) {
        LetSeeFrame l = new LetSeeFrame();  
    }
}

实际上您的面板在框架中居中,但它绘制的内容却不是。

您应该使用 JPanelwidthheight 来使绘图居中。

也把你的尺寸和数字放到变量中,当你在代码中多次使用它们时,它会更少error-prone。

最后正如@MadProgrammer 在评论中所说:

Don't forget to call super.paintComponent before you doing any custom painting, strange things will start doing wrong if you don't. Also paintComponent doesn't need to be public, no one should ever call it directly

import java.awt.Graphics;

import javax.swing.JPanel;

public class LetSee extends JPanel {

    public void paintComponent(final Graphics g) {

        super.paintComponent(g);

        int row; // Row number, from 0 to 7
        int col; // Column number, from 0 to 7
        int x, y; // Top-left corner of square

        int maxRows = 5;
        int maxCols = 5;

        int rectWidth = 60;
        int rectHeight = 60;

        int maxDrawWidth = rectWidth * maxCols;
        int maxDrawHeight = rectHeight * maxRows;

        // this is for centering :
        int baseX = (getWidth() - maxDrawWidth) / 2;
        int baseY = (getHeight() - maxDrawHeight) / 2;

        for (row = 0; row < maxRows; row++) {

            for (col = 0; col < maxCols; col++) {
                x = col * rectWidth;
                y = row * rectHeight;
                if ((row % 2) == (col % 2)) {
                    g.drawRect(baseX + x, baseY + y, rectWidth, rectHeight);
                } else {
                    g.drawRect(baseX + x, baseY + y, rectWidth, rectHeight);
                }

            }

        } // end for row

    }
}