【发布时间】:2014-01-18 08:48:14
【问题描述】:
如何获取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);
}
【问题讨论】:
-
1) 为了尽快获得更好的帮助,请发帖 SSCCE。 2)您可能需要将侦听器添加到感兴趣的组件,而不是框架。比“可能”更好,请参阅第 1 点。
标签: java swing coordinates paint java-2d