我正在处理的项目需要一个文本字段供用户输入椭圆的宽度。当用户单击面板上的某个位置时,它会绘制一个具有指定宽度的椭圆。当我跑它时,宽度从未改变。
这是在initialize():
tTextWidth = new JTextField();
tTextWidth.setBounds(42, 457, 86, 20);
frame.getContentPane().add(tTextWidth);
tTextWidth.setColumns(10);JButton tSetWidth = new JButton("Set Width");
tSetWidth.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SetTextToWidth(tTextWidth.getText());
}
});
这是在initialize()之后:
public void SetTextToWidth(String tWidth)
{
if(tWidth == null)
{
tWidth = "50";
}
int tIntWidth = Integer.parseInt(tWidth);
if(tIntWidth == 0)
{
tIntWidth = 50;
}
RoundSprite tSpriteWidth = new RoundSprite();
tSpriteWidth.SetSpriteWidth(tIntWidth);
}
这是RoundSprite类:
private float mX;
private float mY;
int mWidth;
int mHeight;
Color mColor;
void DrawSprite(Graphics2D g2)
{
AffineTransform tOldTransform = g2.getTransform();
g2.setColor(mColor);
g2.translate(mX, mY);
g2.draw(new Ellipse2D.Double(0, 0, mWidth, mHeight));
g2.setTransform(tOldTransform);
g2.translate(mX - (mWidth / 2), mY - (mHeight / 2));
}
public void SetSpriteWidth(int tWidth)
{
mWidth = tWidth;
}
答案 0 :(得分:2)
所以有两件事......
ActionListener
,大多数情况下是 Enter 键,只是你知道;)
在SetTextToWidth
中正在创建RoundSprite
的新实例,该实例没有屏幕上显示内容的上下文...
我想,这意味着应该更改所有实例RoundSprite
,这不是你想要的。
作为discussed in this simular question,您首先需要定义您实际尝试更改的精灵,然后将您想要的更改应用于该特定实例(并重新绘制输出)......
您可能希望阅读Code Conventions for the Java TM Programming Language,这样可以让人们更轻松地阅读您的代码并让您阅读其他代码