繁体   English   中英

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

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

我是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。

暂无
暂无

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

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