1

我在我的一个项目中使用了一个paintComponent类,我目前想知道如何从顶部减小矩形的大小,使其向下。

这是代码的一部分:

public Battery(){

    super();
    firstTime = true;
    f = new Font("Helvetica", Font.BOLD, 14);
    m = Toolkit.getDefaultToolkit().getFontMetrics(f);
}

public void paintComponent(Graphics g){

    if(firstTime){

        firstTime = false;
        batteryLevel = 1 +  this.getHeight();
        decr = batteryLevel / 20; 

    }else{

        g.setColor(Color.RED);
        g.fillRect(1, 0, this.getWidth(), this.getHeight());

        g.setColor(Color.GREEN);
        g.fillRect(1, 0, this.getWidth(), batteryLevel);

        g.setColor(Color.BLACK);
        g.setFont(f);
        g.drawString("TEST", (getWidth() - m.stringWidth("TEST")) / 2 , this.getHeight() / 2);
    }

}

public void decreaseBatteryLevel(){

    batteryLevel -= decr; 
    this.repaint();

}    

PS。对不起,如果我做错了什么,我是这个论坛的新手。

4

2 回答 2

1

当您希望可见电池电量下降时,您需要增加与 的值相关的 Y 坐标batteryLevel。你可以使用:

g.fillRect(1, getHeight() - batteryLevel, getWidth(), batteryLevel);
于 2012-12-16T13:36:06.267 回答
1

反而

    g.fillRect(1, 0, this.getWidth(), batteryLevel);

    g.fillRect(1, batteryLevel, this.getWidth(), getHeight() - batteryLevel);

也可能repaint(50L)代替repaint().


如果您的问题意味着:如何为电池电量的变化设置动画。

使用 javax.swing.Timer:

    int toPaintBatteryLevel = batteryLevel;
    // In the paintComponent paint upto toPaintBatteryLevel.

    Timer timer = new Timer(100, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (toPaintBatteryLevl == batteryLevel) {
                return;
            }
            if (toPaintBatteryLevl > batteryLevel) {
                --toPaintBatteryLevel; // Animate slowly
            } else {
                toPaintBatteryLevel = batteryLevel; // Change immediately
            }
            repaint(50L);
        };

    });

    timer.start();

为了便于编码,有一个永久计时器。并且在外部改变了batteryLevel,时间决定了toPaintBatteryLevel,paintComponent 用它来绘制。

于 2012-12-16T13:07:11.660 回答