如何获取 JPanel 坐标的 x 和 y 偏移量?
我正在尝试使用面板所在框架的绘制方法在正方形(面板)中间绘制一个圆圈(我希望圆圈移动到其他正方形,这样我就无法在面板上绘制本身)
现在听起来很简单...当我尝试相对于面板的 x 和 y 坐标绘制圆时,似乎存在一个偏移量,使得我的圆坐标总是从中间稍微偏移(也尝试用一个矩形)。
但是我发现 x 偏移量恒定为 8,但 y 偏移量正在变化,所以我无法修复该硬编码...
我的构造函数和绘制方法如下所示:
public Client() {
tokens = new int[8][8];
field = new JPanel[8][8];
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// setResizable(false);
setBounds(100, 100, WIDTH, HEIGHT);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(8, 8, 0, 0));
// Draw field
int row = -1;
for (int i = 0; i < 64; i++) {
if (i % 8 == 0)
row++;
JPanel panel = new JPanel();
if ((i + row) % 2 == 0)
panel.setBackground(Color.BLACK);
else
panel.setBackground(Color.WHITE);
field[row][i % 8] = panel;
contentPane.add(panel);
}
}
private void resizeToken(){
tokenWidth = field[0][0].getWidth();
tokenHeight = field[0][0].getHeight();
xOffset = 8;
//this one is wrong and just placed as example
yOffset = 37;
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paint(g);
resizeToken();
// draw all tokens
tokens[1][1] = PLAYER_ONE;
for (int row = 0; row < 8; row++) {
for (int i = 0; i < 8; i++) {
if (tokens[row][i] != EMPTY_FIELD) {
JPanel p = field[row][i];
if (tokens[row][i] == PLAYER_ONE)
g2.setColor(Color.RED);
else
g2.setColor(Color.BLUE);
g2.fillOval(p.getBounds().x+xOffset, p.getBounds().y-yOffset, tokenWidth, tokenHeight);
}
}
}
if (movingToken != null)
g2.fillOval(movingToken.x, movingToken.y, tokenWidth, tokenHeight);
}
最佳答案
第一件事:
不要使用 JFrame 的绘制方法。 相反,请使用您尝试绘制圆圈的 jpanel 的 PaintComponent。
第二件事:
圆基本上是矩形内的椭圆,它与矩形的边界相接触 矩形。
所以理论上你只需要画一个矩形即可。要画一个覆盖整个面板的圆形
Ellipse2D 圆 = new Ellipse.Double(0,0,panelWidth,panelHeight);
public void paintComponent(Graphics g){
super.paintComponent(g);//this is very important
Graphics2D g2 = (Graphics2D) g;
....
Ellipse2D circle = new Ellipse.Double(0,0,panelWidth,panelHeight);
g2.draw(circle);
}
关于java - 获取 JPanel 坐标的 x 和 y 偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20856958/