gpt4 book ai didi

java - 如何减小矩形的高度? (Java、AWT)

转载 作者:行者123 更新时间:2023-11-30 04:07:14 25 4
gpt4 key购买 nike

我是 Java 初学者。所以,请帮助我解决我的问题。

当矩形的高度增加时,我可以制作动画。但我在减小矩形的高度时遇到问题。请看一下这段代码:

public class Animation extends JPanel implements ActionListener {

Timer timer;
int i = 100;

public Animation() {
timer = new Timer(10, this);
timer.start();
}

public void paint(Graphics g) {

Graphics2D g2d1 = (Graphics2D) g;

g2d1.fillRect(0, 100, 30, i);

}

public static void main(String[] args) {

JFrame frame = new JFrame("animation");
frame.add(new Animation());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 800);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public void actionPerformed(ActionEvent e)
{
--i;
repaint();
}

}

请帮助我。

最诚挚的问候帕维尔

最佳答案

它不会在绘制之间清除屏幕,因此它会在旧的较大矩形上绘制。

试试这个:

public void paint(Graphics g) {
Graphics2D g2d1 = (Graphics2D) g;
g.setColor(getBackground());
g.fillRect(0,0,getWidth(),getHeight()); // draw a rectangle over the display area in the bg color
g.setColor(Color.BLACK);
g2d1.fillRect(0, 100, 30, i);
}

或者:

public void paint(Graphics g) {
super.paint(g); // call superclass method, which does clear the screen
Graphics2D g2d1 = (Graphics2D) g;
g2d1.fillRect(0, 100, 30, i);
}

正如camickr在下面指出的,自定义绘画应该在paintComponent而不是paint中完成,因此您应该将方法名称更改为paintComponent。

关于java - 如何减小矩形的高度? (Java、AWT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20448692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com