gpt4 book ai didi

java - 如何将对象设置在画面中央?

转载 作者:行者123 更新时间:2023-11-30 02:40:45 24 4
gpt4 key购买 nike

我是编程新手。我不知道如何将对象放在框架的中心。这就是我走了多远:

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

最佳答案

实际上,您的面板位于框架的中心,但它绘制的内容并非如此。

您应该利用 JPanel宽度高度来使绘图居中。

还将您的尺寸和数字放入变量中,当您在代码中多次使用它们时,不太容易出错。

最后正如@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

}
}

关于java - 如何将对象设置在画面中央?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41803019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com