【问题标题】:How to decrease a height of a rectangle? (Java, AWT)如何减小矩形的高度? (Java,AWT)
【发布时间】:2013-12-25 06:25:37
【问题描述】:

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

} 

请帮帮我。

最好的问候 帕维尔

【问题讨论】:

  • 它适用于增加反应角。 (使用 ++i 在 actionPerformed 中)。这对我来说真的很奇怪。

标签: java animation awt 2d paint


【解决方案1】:

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

试试这个:

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。

【讨论】:

  • +1 用于首先调用超级方法。 -1,因为自定义绘画应该在paintComponent()方法中完成,而不是paint()方法。
猜你喜欢
  • 2016-03-20
  • 2018-02-22
  • 1970-01-01
  • 2020-10-09
  • 2021-08-16
  • 2018-09-12
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
相关资源
最近更新 更多