简体   繁体   中英

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

I'm beginner in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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