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

        }

    }
}

最後の2つの例のうちの1つを強くお勧めします。これらは、時間の経過とともに実装および保守するのが簡単です最初のものはあなたの顔の中で非常に不快に爆発します

ps-クレオ、私を傷つけないでください:(

于 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 に答える