【问题标题】:How to make the image scale its size automatically according to the parent JLabel's size, in Netbeans GUI Builder?如何在 Netbeans GUI Builder 中使图像根据父 JLabel 的大小自动缩放其大小?
【发布时间】:2014-04-27 11:01:05
【问题描述】:

背景:- 我需要使用 Netbeans GUI Builder 制作 Swing GUI。第一个子任务是在整个背景中显示图像。

我已关注a tutorial 来完成这项工作。我基本上已经制作了一个 JFrame,将其布局设置为 GridBagLayout,然后向它添加了一个透明的(通过取消选中 opaque 属性)JPanel。 (问题一)

之后,我在 JFrame 中添加了一个 JLabel,删除了它的文本并添加了一个图像。 (问题2)

问题:-

  1. 首先,当我添加 JPanel 时,它没有显示其调整大小的句柄。 我 google了一下,找到this tutorial,在里面可以看到 当他们创建 JPanel 时,它会自动显示其调整大小 手柄,可以拖动来调整它的大小。

    但我的没有(截图如下)那么是否有一些财产或东西可以 进行调整以便我可以调整它的大小? 因为我的意图是使用 这个透明面板上包含组件(按钮等) 背景,所以它应该经过整个屏幕/窗口/JFrame 父母。

  2. 第二,由于我使用的图像有一些 1024x768 尺寸,所以 它似乎比它的父组件大得多。

    由于我是菜鸟,我不确定背景的大小是否 图像需要通过某种方式测量像素宽度和 父级的像素高度,然后转换实际图像的 在某些程序(如 Adob​​e Photoshop)中调整为该大小。但我是 当然必须有更实用的方法来做到这一点。

    我希望图像在最初放置在其父级上时根据父级的大小自动调整大小 J标签。我怎样才能做到这一点?请告诉我最简单的方法, 最好在 GUI Builder 中。

我还想确保图像大小、其父 JLabel 的大小、JPanel 的大小都将在我稍后在使用此应用程序时更改窗口大小时调整到框架,或者如果有办法禁用完全调整窗口大小。


EDIT1 @Braj

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.dev_nna.dbp;


public class JFrameParent extends javax.swing.JFrame {

    /**
     * Creates new form JFrameParent
     */
    public JFrameParent() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        getContentPane().add(jPanel1, new java.awt.GridBagConstraints());

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dev_nna/dbp/scheduler/resources/Abstract-white-and-blue-backgrounds.jpg"))); // NOI18N
        jLabel1.setText("jLabel1");
        getContentPane().add(jLabel1, new java.awt.GridBagConstraints());

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrameParent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrameParent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrameParent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrameParent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFrameParent().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}

【问题讨论】:

  • 可以分享一下你添加图片的代码到JLabel
  • @Braj 完成!请查看问题下的更新。
  • @Zarah, I want the image to automatically resize itself according to the size of the parent when it is initially placed on on its parent JLabel. 你为什么要浪费人们的时间?昨天当您提出问题时,您已经得到了答案 (stackoverflow.com/a/23312532/131872)。你连看答案都不花时间,我为什么还要费心回答你的问题???
  • @camickr 如果您这么认为,我很抱歉,但是,首先,这个问题与那个问题有很大不同。其次,我已阅读、接受并处理了您的答案。请再次阅读我的问题,您会看到我已经在 J​​Label 上添加了图像(根据您的建议)并且正在这样做,遇到问题,并发布了这个问题。我不认为这意味着浪费别人的时间。

标签: java swing user-interface netbeans image-scaling


【解决方案1】:

" 或者是否有办法完全禁用窗口大小。"

您可以将框架的 resizable 属性设置为 false。来自 NetBeans GUI 构建器

  1. 从设计视图或导航窗口中突出显示/选择框架组件。
  2. 转到右侧的属性窗口并查找属性resizable 并确保它未选中

“我还想确保当我改变窗口大小时,图像大小,它的父JLabel的大小,JPanel的大小都会适应框架”

一种方法是将背景绘制到背景面板上,而不是使用带有图标的标签。你可以看到here 的一个例子。对于 GUI Builder,最简单的方法(无需编辑自动生成的代码,如果您不知道自己在做什么,我不建议这样做)是使用 JPanel 表单而不是 @987654327 @ 形式。在JPanel 表单上绘画,然后您可以将该JPanel 表单添加到JFrame 表单。您可以查看here,以轻松将JPanel 表单添加到JFrame 表单。


更新

所以你的JPanel 表单类最终看起来像这样

public class PanelForm extends javax.swing.JPanel {
    private BufferedImage image;

    public PanelForm() {
        try {
            image = ImageIO.read(getClass().getResource("/path/to/image/png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }  
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
    }

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

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new PanelForm());     //  <--- add it here
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

【讨论】:

  • 非常感谢。我将尝试从 GUI 构建器中以第二种方式进行,我希望我能成功。您能否澄清一下“在 JPanel 表单上绘制”是否意味着仅在 JPanel 表单上绘制图像?图像会自行缩放以匹配 JPanel 的大小吗?这是一个重大问题。图像变得比父图像大得多。
  • 是的,如果您查看我链接的答案,您将在我创建JPanelcreateBackgroundPanel 方法中看到,在drawImage 方法中,我传递给它getWidth()getHeight()。这将使图像在拉伸时调整为面板的大小。
  • 并覆盖 JPanel 的 getPreferredSize
  • @Zarah 我对上面的代码做了一点调整。您还需要覆盖面板表单的getPreferredSize(),因为您希望框架出现的初始大小。自动生成的代码将打包框架,如果您不覆盖该方法,您的框架将不会显示为您想要的大小。
  • @Zarah 您可以只使用该面板来添加您的组件,因为它占据整个框架。否则,您不能删除方法实现。但是,您可以从构造函数中删除调用
猜你喜欢
  • 2019-01-27
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-04
  • 2016-05-14
  • 2013-11-22
相关资源
最近更新 更多