【问题标题】:java make image resize with containing paneljava使用包含面板调整图像大小
【发布时间】:2014-01-11 07:33:09
【问题描述】:

我有一个带有包含图像标签的面板。

我知道如何调整图像大小,但我想在调整包含面板大小时自动触发调整大小 - 以保持大致相同的相对大小。

我应该在哪里调用我的调整大小函数?

    public JPanel slidePane;
    public JLabel iconLbl;

    iconLbl = new JLabel();
    iconLbl.setIcon(getImage(slides.get(0),this));
    iconLbl.setA lignmentX(Component.CENTER_ALIGNMENT);
    slidePane.add(iconLbl);

//

    public static ImageIcon getImage(String ImageName, SlideShow ss) {
        java.net.URL imgURL = ss.getClass().getClassLoader().getResource(ImageName);
        ImageIcon image = new ImageIcon( imgURL);     
        //JOptionPane.showMessageDialog(null, "Width: " + image.getIconWidth() + " Height: " + image.getIconHeight());
        BufferedImage bi = new BufferedImage(image.getIconWidth(), image.getIconHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.createGraphics();
        image.paintIcon(null, g, 0,0);
        g.dispose();
        BufferedImage resizedimage;

        try {
            JOptionPane.showMessageDialog(null,"SIZING: "+ss.starterModule.Tabs.getWidth()+" "+ ss.starterModule.Tabs.getWidth());
            resizedimage = myResize(bi,ss.starterModule.Tabs.getWidth(), ss.starterModule.Tabs.getWidth());

        } catch (Exception e) {
            resizedimage=myResize(bi,600, 700);
        }
        ImageIcon resizedicon=new ImageIcon(resizedimage);

        return resizedicon;

    }

    public static BufferedImage myResize(BufferedImage image, int width, int height) {
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
        Graphics2D g2d = (Graphics2D) bi.createGraphics();
        g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
        g2d.drawImage(image, 0, 0, width, height, null);
        g2d.dispose();
        return bi;
    }

【问题讨论】:

  • 通常您会使用布局管理器为您执行此操作。尝试使用诸如 NetBeans 或 Eclipse 之类的 GUI 构建器来构建您的表单。

标签: java image autoresize resizable


【解决方案1】:

使用这样的布局管理器:

iconLbl = new JLabel() {
  @Override
  public void paintComponent(Graphics g) {
    g.drawImage(...);
  }
}
sidePanel.setLayout(new BorderLayout());
sidePanel.add(iconLbl, BorderLayout.CENTER);

有不同的布局管理器,但如果过于复杂,我建议使用类似 NetBeans 或 Eclipse 中的 GUI 构建器。

drawImage() 函数可以根据需要动态缩放图像,因此您不需要 myResize()。有关参数,请参见 Graphics.drawImage()。

【讨论】:

  • 我认为这不是那种问题。标签本身可能会调整大小,但图标不会
  • 是的,再想一想,布局管理器不会调整图标的大小(但仍然需要)。接下来,您需要在 JLabel 中覆盖 paintComponent() 并在绘制之前调整图像大小。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-01
  • 2023-04-02
  • 2018-04-20
  • 2015-04-16
  • 1970-01-01
  • 2014-07-08
相关资源
最近更新 更多