简体   繁体   English

如何减少矩形的高度? (Java,AWT)

[英]How to decrease a height of a rectangle? (Java, AWT)

I'm beginner in Java. 我是Java的初学者。 So, please help me with my problem. 所以,请帮助我解决我的问题。

I can do animation when a rectangle's height increases. 当矩形的高度增加时,我可以做动画。 But I have problem with decreasing rectangle's height. 但是我在减小矩形的高度上有问题。 Please look at this code: 请看下面的代码:

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();
}

} 

Please help me. 请帮我。

Best regards Pawel 最好的问候帕维尔

It isn't clearing the screen between draws, so it draws over the old larger rectangle. 它不会在绘制之间清除屏幕,因此会在旧的较大矩形上绘制。

Try this: 尝试这个:

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);
}

Or: 要么:

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);
}

And as camickr pointed out below, custom painting should be done in paintComponent not paint, so you should change the name of the method to paintComponent. 就像camickr在下面指出的那样,自定义绘制应该在paintComponent中完成,而不是在paint中进行,因此您应该将方法的名称更改为paintComponent。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM