假设我有两个类,第一个类扩展 JPanel 并使用 Graphics 在其上绘制一个游戏板。第二个创建一个 JFrame 并向其中添加面板。
我现在想在单击时将椭圆添加到特定矩形。我知道我将使用二维数组来获得我想要的位置,但我不明白椭圆本身如何绘制到现有面板上,因为我使用了 paint(Graphics g )
绘制游戏板。
如果您需要的话,这里是绘制板本身的代码:
class MyBoard extends JPanel {
private static int height = 6;
private static int width = 7;
private static int squareSize = 100;
private int board[][] = new int[height][width];
public void paint(Graphics g) {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
g.drawRect(j * squareSize, i * squareSize, squareSize, squareSize);
}
}
}
}
谢谢!
最佳答案
您应该记住的前两件事:永远不要覆盖 paint
而是覆盖 paintComponent
并在那里调用 super.paintComponent
,以便边框和一切正常工作正如预期的那样。关于为什么会出现这种情况,引用这个问题:Difference between paint() and paintcomponent()?
现在回答你的问题。假设您有一个现有的逻辑来确定要在哪个正方形中绘制椭圆(假设您有两个 Integer
s elX
和 elY
是正方形的列和行),您可以在完成画板本身后直接去画它。
想象一下这样的示例代码:
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// Draw the board
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
g.drawRect(j * squareSize, i * squareSize, squareSize, squareSize);
}
}
// Draw the ellipse at the correct location using half the size of a normal square.
g.drawOval(elX * squareSize + squareSize / 4, elY * squareSize + squareSize / 4, squareSize / 2 , squareSize / 2);
}
<小时/>
现在是如何实际确定在哪里绘制椭圆的最后部分。
一个简单的解决方案是向面板添加一个 MouseListener
。然后在 mouseClicked
方法中计算您实际点击的位置。
可能看起来像这样:
this.addMouseListener(new MouseListener()
{
@Override
public void mouseClicked(MouseEvent e)
{
int column = e.getX() / squareSize;
int row = e.getY() / squareSize;
board[column][row] = 1;
}
[...] // add the other methods to override
}
然后你稍微调整你的 paintComponent
方法,如下所示:
for (int column = 0; column < width; ++column)
{
for (int row = 0; row < height; ++row)
{
if (board[column][row] == 1)
{
g.drawOval(column * squareSize + squareSize / 4, row * squareSize + squareSize / 4, squareSize / 2, squareSize / 2);
}
}
}
现在你在点击的地方画了一个椭圆。您还可以检查单击的方 block 是否已将 1
设置为值并将其重置为 0
以具有某种切换机制或增加它并根据整数绘制不同的东西值(value)...这一切都取决于你:)
关于java - 在已使用 Paint 方法的 JPanel 上绘制形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49278731/