如何使JLabel与图像填充BorderLayout.CENTER [英] How to make JLabel with image fill BorderLayout.CENTER

查看:159
本文介绍了如何使JLabel与图像填充BorderLayout.CENTER的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JFrame,并将LayoutManager设置为BorderLayout,然后继续添加带有图像的JLabel。但是,当我调整框架大小时,JLabel不会调整大小。我没有向North,S,E等添加任何组件。我希望简单地让标签内的图像填满整个框架,当然让我的菜单保持圆滑。

Ive got a JFrame and set the LayoutManager to BorderLayout and then proceeded to add my JLabel with an image. However when i resize the frame the JLabel doesnt resize. I have not added any components to North, S, E and so on. I was hoping to simply have the image inside the label fill up the entire frame leaving my menu in tact of course.

推荐答案

原谅如果这看起来很傲慢,我就没事了。

Forgive me if this seems arrogant, but I have nothing else to go on.

我做了一个快速的样本


查看图片周围的红线,即 JLabel '的边界。正如您所看到的,标签已经过重新调整以填充整个区域。

See the red line around the image, that's the JLabel's border. As you can see, the label is been re-sized to fill the entire area.

这是我用来生成样本的代码

This is the code I used to produce the sample

public class LayoutFrame extends JFrame {

    public LayoutFrame() throws HeadlessException {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Image image = null;
        URL url = getClass().getResource("/layout/issue78.jpg");
        try {
            image = ImageIO.read(url);
        } catch (IOException ex) {

            ex.printStackTrace();

        }

        JLabel label = new JLabel(new ImageIcon(image));
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setVerticalAlignment(JLabel.CENTER);
        label.setBorder(new LineBorder(Color.RED, 4));

        setLayout(new BorderLayout());

        add(label);

    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {

                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                LayoutFrame frame = new LayoutFrame();
                frame.setSize(200, 200);
                frame.setLocationByPlatform(true);
                frame.setVisible(true);

            }
        });

    }

}

显然,你我需要提供你自己的形象;)。

Obviously, you'll need to supply your own image ;).

不要忘记,标签不会为你缩放内容,如果这是你的目标,你会需要实现自己的组件来实现这一目标。

Don't forget, the label WON'T scale the content for you, if that's your goal, you'll need to implement your own component to achieve this.

如果您仍有问题,我建议(在没有进一步证据的情况下)您的标签可能不是在容器中你认为它或容器布局管理器不是你想象的那样。

If you're still having problems, I would suggest (in the absence of further evidence) that your label may not be in the container you think it is or the containers layout manager is not what you think it is.

更新

我不知道你为什么会遇到组件丢失或菜单问题的原因。混合重量和重量轻的组件??

I don't know why you're having issues with components going missing or issues with you menu. Are mixing heavy and light weight components??

带菜单栏的示例

在仔细阅读你的问题后,我设计了一个简单调整图像窗格样本。为了速度,我依靠我的库,但实现你自己的代码代替我的调用应该相当容易

After reading your question a little closer, I've devised a simple resizing image pane sample. For speed, I've relied on my libraries, but it should be reasonably easy to implementation your own code in place of my calls

public class ImagePane extends JPanel {

    protected static final Object RESIZE_LOCK = new Object();

    private BufferedImage image;
    private BufferedImage scaledImage;
    private Timer resizeTimer;

    public ImagePane() {

        URL url = getClass().getResource("/layout/issue78.jpg");
        try {
            image = ImageIO.read(url);
        } catch (IOException ex) {

            ex.printStackTrace();

        }

        resizeTimer = new Timer(250, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                // Simple thread factory to start a slightly lower 
                // priority thread.
                CoreThreadFactory.getUIInstance().execute(new ResizeTask());

            }

        });

        resizeTimer.setCoalesce(true);
        resizeTimer.setRepeats(false);

    }

    @Override
    public void setBounds(int x, int y, int width, int height) {

        super.setBounds(x, y, width, height);

        resizeTimer.restart();

    }

    @Override
    protected void paintComponent(Graphics g) {

        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;
        if (scaledImage != null) {

            // This simply returns a rectangle that takes into consideration
            //the containers insets
            Rectangle safeBounds = UIUtilities.getSafeBounds(this);

            System.out.println("scaledImage = " + scaledImage.getWidth() + "x" + scaledImage.getWidth());

            int x = ((safeBounds.width - scaledImage.getWidth()) / 2) + safeBounds.x;
            int y = ((safeBounds.height - scaledImage.getHeight()) / 2) + safeBounds.y;

            g2d.drawImage(scaledImage, x, y, this);

        }

    }

    protected class ResizeTask implements Runnable {

        @Override
        public void run() {

            synchronized (RESIZE_LOCK) {

                if (image != null) {

                    int width = getWidth();
                    int height = getHeight();

                    System.out.println("width = " + width);
                    System.out.println("height = " + height);

                    // A simple divide and conquer resize implementation
                    // this will scale the image so that it will fit within
                    // the supplied bounds
                    scaledImage = ImageUtilities.getScaledInstanceToFit(image, new Dimension(width, height), ImageUtilities.RenderQuality.High);

                    System.out.println("scaledImage = " + scaledImage.getWidth() + "x" + scaledImage.getWidth());

                    repaint(); // this is one of the few thread safe calls

                }

            }

        }

    }

}

这篇关于如何使JLabel与图像填充BorderLayout.CENTER的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆