我有一个程序,当你点击JPanel上的某个地方时会产生一个椭圆。当我进行测试运行时,它只是在我点击的位置右侧产生了斜线。谁能找到问题呢?谢谢,这是代码:
这是点击的代码:
final SpriteField mSpritePanel = new SpriteField();
mSpritePanel.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
float tX = e.getX();
float tY = e.getY();
int tIntWidth;
int tIntHeight;
int tIntRotate = 0;
if(tTextWidth.getText() == null)
{
tTextWidth.setText("50");
}
try
{
tIntWidth = Integer.parseInt(tTextWidth.getText());
}
catch(NumberFormatException ex)
{
tIntWidth = 50;
}
if(tIntWidth == 0)
{
tIntWidth = 50;
}
if(tTextHeight.getText() == null)
{
tTextHeight.setText("50");
}
try
{
tIntHeight = Integer.parseInt(tTextHeight.getText());
}
catch(NumberFormatException ex)
{
tIntHeight = 50;
}
if(tIntHeight == 0)
{
tIntHeight = 50;
}
if(tTextRotation.getText() == null)
{
tTextRotation.setText("0");
}
try
{
tIntRotate = Integer.parseInt(tTextRotation.getText());
}
catch(NumberFormatException ex)
{
tIntRotate = 50;
}
mSpritePanel.CreateSpriteAt(tX, tY, tIntWidth, tIntHeight, tIntRotate);
mSpritePanel.repaint();
}
});
这是我的SpriteField类的代码:
public class SpriteField extends JPanel
{
final List<RoundSprite> mSpriteList = new ArrayList<RoundSprite>();
public void CreateSpriteAt(float tX, float tY, int tWidth, int tHeight, int tRotation)
{
RoundSprite mSprite = new RoundSprite();
mSprite.SetPosition(tX, tY);
mSprite.SetSpriteWidth(tWidth);
mSprite.SetSpriteHeight(tHeight);
mSprite.SetSpriteRotation(tRotation);
mSpriteList.add(mSprite);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
AffineTransform originalTransform = g2.getTransform();
for (RoundSprite mSprite : mSpriteList)
{
mSprite.DrawSprite(g2);
g2.setTransform(originalTransform);
}
}
}
这是我的RoundSprite类的代码:
public class RoundSprite
{
private float mX;
private float mY;
int mWidth;
int mHeight;
int mRotate;
Color mColor;
void DrawSprite(Graphics2D g2)
{
AffineTransform tOldTransform = g2.getTransform();
g2.setColor(mColor);
g2.translate(mX, mY);
g2.rotate(mRotate);
g2.translate(mX - (mWidth / 2), mY - (mHeight / 2));
g2.draw(new Ellipse2D.Double(0, 0, mWidth, mHeight));
g2.setTransform(tOldTransform);
}
public void SetSpriteWidth(int tWidth)
{
mWidth = tWidth;
}
public void SetSpriteHeight(int tHeight)
{
mWidth = tHeight;
}
public void SetSpriteColor(Color tColor)
{
mColor = tColor;
}
public void SetPosition(float x, float y)
{
mX = x;
mY = y;
}
public void SetSpriteRotation(int tRotate)
{
mRotate = tRotate;
}
}
答案 0 :(得分:4)
RoundSprite
:
public void SetSpriteWidth(int tWidth)
{
mWidth = tWidth; // set the width
}
public void SetSpriteHeight(int tHeight)
{
mWidth = tHeight; // set the width again, leaving mHeight forever 0...
}
这使得所有椭圆都是一维的,因此它们呈现为一条线。
只需改为mHeight = tHeight
,您的程序即可运行。
在RoundSprite#DrawSprite()
方法中,您要拨打g2.translate()
两次。 g2.translate()
是一个相对的,而不是绝对的位置变化,所以你不想在第二次调用它时给出鼠标坐标。
替换这个:
g2.translate(mX - (mWidth / 2), mY - (mHeight / 2));
用这个:
g2.translate(-mWidth/2, -mHeight/2);
将椭圆置于鼠标点击位置的中心位置。