0

我正在用具有 UI 的 Java 编写程序。我想做一种健康棒的东西。我必须使用JLabelHealthBarUnder 和 HealthBarOver。我想将它们放在彼此的顶部,以便我可以减小 HealthBarOver 的宽度(从而使健康栏的外观)。什么是最好的布局。我正在使用BorderLayout,但它不会让我重新调整组件的大小。

谢谢你

4

2 回答 2

1

你“可以”做这样的事情......

在此处输入图像描述

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;

public class SlidingLabels {

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

    public SlidingLabels() {
        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 BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel lower = new JLabel();
        private JLabel upper = new JLabel();

        private float progress = 1f;
        private boolean ignoreUpdates;

        public TestPane() {
            setLayout(new GridBagLayout());
            lower.setOpaque(true);
            lower.setBackground(Color.GRAY);
            lower.setBorder(new LineBorder(Color.BLACK));
            lower.setPreferredSize(new Dimension(200, 25));

            upper.setOpaque(true);
            upper.setBackground(Color.BLUE);
            upper.setBorder(new LineBorder(Color.BLACK));
            upper.setPreferredSize(new Dimension(200, 25));

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1;
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.fill = GridBagConstraints.NONE;
            add(upper, gbc);
            gbc.fill = GridBagConstraints.HORIZONTAL;
            add(lower, gbc);

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

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void updateProgress() {
            ignoreUpdates = true;
            int width = (int) (getWidth() * progress);
            upper.setPreferredSize(new Dimension(width, 25));
            revalidate();
            repaint();
            ignoreUpdates = false;
        }

        @Override
        public void invalidate() {
            super.invalidate(); 
            if (!ignoreUpdates) {
                updateProgress();
            }
        }

    }
}

但它使用了许多令人讨厌的技巧,并且可能早晚会在你脸上炸毁......

应该使用一个JProgressBar

在此处输入图像描述

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;

public class ProgressBar {

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

    public ProgressBar() {
        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 BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JProgressBar pb;
        private float progress = 1f;

        public TestPane() {
            setLayout(new GridBagLayout());

            pb = new JProgressBar();
            pb.setBorderPainted(false);
            pb.setStringPainted(true);
            pb.setBorder(new LineBorder(Color.BLACK));
            pb.setForeground(Color.BLUE);
            pb.setBackground(Color.GRAY);

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1;
            gbc.insets = new Insets(4, 4, 4, 4);
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            add(pb, gbc);

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

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void updateProgress() {
            pb.setValue((int) (100 * progress));
        }

    }
}

但是,如果这不能满足您的需求,您最好编写自己的进度组件......

在此处输入图像描述

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;

        public TestPane() {

            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 Dimension getPreferredSize() {
            FontMetrics fm = getFontMetrics(getFont());
            return new Dimension(200, fm.getHeight() + 4);
        }

        @Override
        protected void paintComponent(Graphics g) {
            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);

            g.setColor(getForeground());
            g.fillRect(x, y, (int) (width * progress), height);
            g.setColor(Color.BLACK);
            g.drawRect(x, y, (int) (width * progress), height);

            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());

        }

    }
}

强烈推荐最后两个示例之一,随着时间的推移,它们更易于实现和维护。第一个会在你脸上爆炸,非常不愉快

ps-Kleo,请不要伤害我:(

于 2013-02-28T02:48:43.913 回答
0

我也会使用这个小方法来提供更手动的方法:

  private void addComponent(Container container, Component c, int x, int y,int width, int    height) {

    c.setBounds(x, y, width, height);
    container.add(c);
}

并这样称呼它:

    addComponent(container such as JPanel, component such as a JButton, x position, yposition, width, height);
于 2013-02-28T00:48:08.260 回答