Java使用图像的JProgressBar

3

我正在使用Java制作一款游戏,并为血条使用JProgressBar。 我想使用图像(而不是颜色)来替换JProgressBar,但我一直无法做到。 我尝试使用paint方法、paintComponent方法、创建一个新类,但都没有成功。 请问有人可以帮助我吗?


如果你只是要覆盖它,为什么不直接使用JLabel呢? - user1181445
我能否设置JLabel的大小,使其看起来像一个生命条? - user1976336
为了更快地获得更好的帮助,请发布一个SSCCE - Andrew Thompson
1个回答

6

如果不想创建自己的 ProgressBarUI 实现,您可以简单地创建自己的...

这个例子基本上是以单个药水图像制作一个“药水条”,然后根据当前进度呈现一个子图像。

只需稍微修改即可仅显示整个药水...

enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.NumberFormat;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ProgressPane {

    public static void main(String[] args) {
        new ProgressPane();
    }

    public ProgressPane() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private float progress = 1f;
        private BufferedImage potion;
        private BufferedImage potionBar;

        public TestPane() {
            try {
                potion = ImageIO.read(getClass().getResource("/Potion.png"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            setOpaque(false);

            setForeground(Color.BLUE);
            setBackground(Color.GRAY);

            Timer timer = new Timer(500, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    progress -= 0.01;
                    if (progress <= 0.001) {
                        ((Timer) e.getSource()).stop();
                    }
                    repaint();
                }
            });
            timer.setRepeats(true);
            timer.setCoalesce(true);
            timer.start();
        }

        @Override
        public void invalidate() {
            super.invalidate();
            potionBar = null;
        }

        @Override
        public Dimension getPreferredSize() {
            FontMetrics fm = getFontMetrics(getFont());
            return new Dimension(200, Math.max(50, fm.getHeight() + 4));
        }

        protected void createPotionBar() {

            if (potionBar == null) {
                if (getWidth() > 0 && getHeight() > 0) {
                    FontMetrics fm = getFontMetrics(getFont());
                    int height = Math.max(50, fm.getHeight() + 4);
                    potionBar = new BufferedImage(getWidth() - 4, height, BufferedImage.TYPE_INT_ARGB);
                    Graphics2D g2d = potionBar.createGraphics();
                    int x = 0;
                    int y = (height - potion.getHeight()) / 2;
                    while (x < getWidth() - 4) {
                        g2d.drawImage(potion, x, y, this);
                        x += potion.getWidth();
                    }
                    g2d.dispose();
                }
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            createPotionBar();
            super.paintComponent(g);

            int width = getWidth() - 4;
            int height = getHeight() - 4;
            int x = 2;
            int y = 2;

            g.setColor(getBackground());
            g.fillRect(x, y, width, height);
            g.setColor(Color.BLACK);
            g.drawRect(x, y, width, height);

            int progressWidth = (int) (width * progress);
            BufferedImage progressImage = potionBar.getSubimage(0, 0, progressWidth, potionBar.getHeight());
            g.drawImage(progressImage, x, y, this);

            FontMetrics fm = g.getFontMetrics();
            String value = NumberFormat.getPercentInstance().format(progress);
            x = x + ((width - fm.stringWidth(value)) / 2);
            y = y + ((height - fm.getHeight()) / 2);

            g.setColor(Color.WHITE);
            g.drawString(value, x, y + fm.getAscent());

        }
    }
}

+1 哦,我喜欢... :) 对于游戏来说很不错,而且更好的是我不需要自己写它,只需复制粘贴 :P - David Kroukamp
是否可以将前景设置为另一张图片?这样红色药水图片就可以被蓝色药水图片或类似的图片覆盖吗?我意识到前景已经是一张BufferedImage,但它似乎是以一张空白图片的形式构建的。 - Cardinal System

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接