簡體   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