Dynamically resize jframe/image or scroll

不羁岁月 提交于 2019-11-29 16:10:48

To warp the label with a scroll pane you could implement the following changes:

    //frame.setLayout(new FlowLayout()); - comment out -  use default (Borderlayout)
    JLabel lbl= new JLabel();
    lbl.setIcon(icon);
    JScrollPane jsp = new JScrollPane(lbl); //warp the label with a scrollpane 
    //frame.add(lbl); 
    frame.add(jsp); //add scrollpane to frame instead of lbl

You can find more information here.

Carrying on from your previous question, your basic question comes down to two issues.

  1. How to determine when the component has changed size
  2. Scaling the image to meet the new requirements.

To be frank, there are any number of examples available on both subjects, you just need to combine them. You could start by having a look at:

The following is a modification of the ImagePanel I presented in your previous question which will scale the image based on the size of the component while maintaining the aspect ratio.

public class ImagePane extends JPanel {

    private BufferedImage img;
    private Image scaled;

    public ImagePane(BufferedImage img) {
        this.img = img;
        this.scaled = img;
        addComponentListener(new ComponentAdapter() {

            @Override
            public void componentResized(ComponentEvent e) {
                Dimension size = getSize();
                if (size.width > size.height) {
                    size.width = -1;
                } else {
                    size.height = -1;
                }
                scaled = img.getScaledInstance(size.width, size.height, java.awt.Image.SCALE_SMOOTH);
            }

        });
    }

    @Override
    public Dimension getPreferredSize() {
        return scaled == null ? new Dimension(0, 0) : new Dimension(scaled.getWidth(this), scaled.getHeight(this));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (scaled != null) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.drawImage(scaled, 0, 0, this);
            g2.dispose();
        }
    }
}

The example is provide for brevity, Image#getScaledInstance is neither the fastest nor does it generate the best quality result. The first two examples linked above go into more detail about other possible solutions.

You will also want to calculate and maintain the resulting scaling factor, which would need to be applied to any additional painting operations.

In this case, I might be tempted to simply calculate the scaling factor (instead of scaling the image) and use a AffineTransform in the paintComponent to apply it, but that all comes down to needs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!