How to resize image Height to JFrame Height?
我的图像对于我的 JFrame 来说太高了,即使它已最大化。我想动态调整它的大小,以便图像永远不会被 JFrame 的顶部或底部剪裁。我已将图像作为 ImageIcon 插入到 JLabel 中。我试过设置最大尺寸无济于事。如何确保图像的高度永远不会大于 JFrame?理想情况下,我希望保持高宽比不变。图像是纵向的。有什么想法吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class myClass extends JFrame { private void initGUI(){ pane = getContentPane(); pane.setLayout(new BorderLayout()); next = new JButton("Next"); previous = new JButton("Previous"); page = new JLabel(loadImg()); page.setMaximumSize(this.getSize()); pane.add(next, BorderLayout.EAST); pane.add(previous, BorderLayout.WEST); pane.add(page, BorderLayout.CENTER); } } |
I would ideally like to keep the ratio of height to width constant.
查看 Darryl 的拉伸图标。它会根据可用空间缩小/增长,同时保持宽/高比。
您可以尝试覆盖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | page = new JLabel(loadIMG()){ @Override paintComponent(Graphics g) { //So we don't kill default behaviour super.paintComponent(g); int scaledWidth, scaledHeight; //pseudo-code scale and store into scaledWidth and scaledHeight; render with g.drawImage(icon, x, y, scaledWidth, scaledHeight, null); } }; |