Java 图像图标大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2244848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:11:05  来源:igfitidea点击:

Java ImageIcon size

javaswing

提问by sutoL

I have uploaded a picture into my GUI which displays on a JLabel. The label dimension is set only 100,100 while the picture is much bigger, so when I upload it into the label it expands.

我已将图片上传到我的 GUI 中,该图片显示在 JLabel 上。标签尺寸仅设置为 100,100,而图片要大得多,因此当我将其上传到标签时,它会展开。

Is there anyway to make it auto resize to the label size?

有没有办法让它自动调整到标签大小?

Below is the action listener for the Upload Picture JButton

下面是上传图片 JButton 的动作监听器

class UploadHandler implements ActionListener 
{
    public void actionPerformed(ActionEvent e)
    {
        int returnVal = fc.showOpenDialog(frame2);
        file = fc.getSelectedFile();
        pathname = file.getPath();
        icon = new ImageIcon(pathname);
        lblDisPic.setIcon(icon);    
    }
}

btnUpload = new JButton("Upload Picture");
lblDisPic = new JLabel();
lblDisPic.setBorder(raisedetched);
lblDisPic.setPreferredSize(d); 

btnUpload.addActionListener(new UploadHandler());

回答by Pool

Sure, just override the paintComponentmethod and you can scale and paint it as you like.

当然,只需覆盖该paintComponent方法,您就可以根据需要缩放和绘制它。

myLabel = new JLabel (/*whatever*/) {

    @Override
    public void paintComponent (Graphics g) {
        super.paintComponent (g);
        g.drawImage (myImageIcon.getImage(), 0, 0, getWidth (), getHeight (), null);
    }
};

Source from here.

来源从这里

EDIT

编辑

To add to your code change:

要添加到您的代码更改:

lblDisPic = new JLabel();

To:

到:

lblDidPic = new JLabel() {

    @Override
    public void paintComponent (Graphics g) {
        super.paintComponent (g);
        if (icon != null) {
            g.drawImage (icon.getImage(), 0, 0, getWidth(), getHeight(), null);
        }
    }
};

回答by coobird

Given the example code, one approach is to resize the image to display on the JLabelbefore the setIconmethod is called.

给定示例代码,一种方法是JLabelsetIcon调用方法之前调整要显示的图像的大小。

One way could be to change the actionPerformedmethod, so the image will be loaded from the specified file, using ImageIO.readmethod to read the image, then resizing the image before an ImageIconis created.

一种方法可能是更改actionPerformed方法,因此将从指定文件加载图像,使用ImageIO.read方法读取图像,然后在ImageIcon创建图像之前调整图像大小。

Image img = ImageIO.read(fc.getSelectedFile());

Then, the loaded image can be resized to the dimension of the JLabel, using Image.getScaledInstance.

然后,所加载的图像可以调整到的尺寸JLabel使用,Image.getScaledInstance

Image resizedImage = 
    img.getScaledInstance(lblDisPic.getWidth(), lblDisPic.getHeight(), null);

Now, one could create an ImageIconto use on the JLabel.

现在,可以创建一个ImageIcon用于JLabel.

lblDisPic.setIcon(new ImageIcon(resizedImage));

The limitation to this method is, that if the JLabelis resized in any way, then the image contained by the JLabelwill not be resized. However, as the JLabelis going to use a scaled-down image of the original, it would mean that the amount of memory required would be reduced (if that a concern) and original image would not have to be resized every time image is being displayed, as would be the case with overriding the paintComponentmethod.

此方法的限制是,如果JLabel以任何方式调整 的大小,则 包含的图像JLabel将不会调整大小。但是,由于JLabel将使用按比例缩小的原始图像,这意味着所需的内存量将减少(如果有问题)并且每次显示图像时都不必调整原始图像的大小,就像覆盖paintComponent方法一样。

The preferred method of achieving the task at hand is going to depend on the requirements of whether the original image is going to be needed at a later time or not.

完成手头任务的首选方法将取决于以后是否需要原始图像的要求。

回答by Nate

You could override the paintIconmethod on the icon itself -

您可以覆盖paintIcon图标本身的方法 -

ImageIcon icon = new ImageIcon(...) {

    @Override
    public void paintIcon( Component c, Graphics g, int x, int y ) {
        g.drawImage(getImage(), x, y, c.getWidth(), c.getHeight(), c);
    }

    @Override 
    public int getIconHeight() {
        // see below...
    }

    @Override
    public int getIconWidth() {
        // see below...
    }

};

Edit -

编辑 -

I realized that the original size of the image is taken into account when the Label decides where to place the x, y location of the icon. You'll need to override the getIconWidth() and getIconHeight() methods, too.

我意识到当 Label 决定放置图标的 x、y 位置时,会考虑图像的原始大小。您还需要覆盖 getIconWidth() 和 getIconHeight() 方法。

However, there's not a good way to override these to return the label size, as there's no reference to the component itself within these methods.

但是,没有一个好的方法来覆盖这些以返回标签大小,因为在这些方法中没有对组件本身的引用。

One approach would be to create a new class that extends ImageIconand pass the component in - not a great choice because this breaks the "reusable between many components" aspects of an Icon.

一种方法是创建一个新类来扩展ImageIcon和传递组件——这不是一个很好的选择,因为这打破了 Icon 的“可在多个组件之间重用”方面。

Another would be to just override these methods in the inner class as above, but put a hardcoded reference to the component as an object field, or as a finallocal variable. Again, this breaks the "reusable between many components" aspect, and seems a bit "hacky" in general, but as it is an one-off inner class, this might be permissable.

另一种方法是像上面一样在内部类中覆盖这些方法,但将对该组件的硬编码引用作为对象字段或final局部变量。同样,这打破了“在多个组件之间可重用”的方面,并且总体上看起来有点“hacky”,但由于它是一次性内部类,这可能是允许的。

回答by Rohit

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

JFileChooser jFileChooser1=new JFileChooser();

int state = jFileChooser1.showOpenDialog(new JFrame());         
       jTextField1.setText("");

           if( state ==JFileChooser.APPROVE_OPTION) {
      JOptionPane.showMessageDialog(
                    null,null);
         File file = jFileChooser1.getSelectedFile();
         s2=file.toString();
          jTextField1.setText(s2);
       jLabel1=new JLabel();
     jLabel1.setName(s2);
  jLabel1.setLocation(50,50);
  jLabel1.setSize(300,300);
    add(jLabel1);

    BufferedImage bi1;

    try
    {   
        bi1=ImageIO.read(file);
        ImageIcon icon1=new ImageIcon(bi1);
        jLabel1.setIcon(icon1);
        Image img = ImageIO.read(jFileChooser1.getSelectedFile());

        Image resizedImage = 
   img.getScaledInstance(jLabel1.getWidth(), jLabel1.getHeight(),Image.SCALE_DEFAULT);
       jLabel1.setIcon(new ImageIcon(resizedImage)); 


  jLabel1.setBorder(BorderFactory.createLineBorder(Color.RED,5));


       pack();   

    }
    catch(Exception e)
    {
  System.out.println(e);
    }


    }
    else if(state == JFileChooser.CANCEL_OPTION) {
      JOptionPane.showMessageDialog(
                  new JFrame(), "Canceled");
    }
  pack();           

  }

回答by Tushar Arora

If you can edit the image in paint then set its size accordingly in paint and then click on save and then the same size of image will come to your JAVA application.

如果您可以在 Paint 中编辑图像,则在 Paint 中相应地设置其大小,然后单击保存,然后相同大小的图像将出现在您的 JAVA 应用程序中。