在GridLayout布局管理器中动态调整链接到JLabel的图像

时间:2014-03-01 02:42:36

标签: java image swing resize grid-layout

当前的实施布局: implementation layout

((编辑:补充说 代码:))

private JPanel panelCenter;
private List<BufferedImage> listCreatedImages;
public ChooseCircuitPanel(List<BufferedImage> listCreatedImages) {
        this.listCreatedImages = listCreatedImages;
        initiate();
}
private void initiate() {
        setLayout(new BorderLayout(50, 50));
        panelCenter = new JPanel();
        LayoutManager theLayout = new GridLayout(0, 3, 0, 0);
        panelCenter.setLayout(theLayout);
        panelCenter.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        for (BufferedImage bufferedImage : listCreatedImages) {
            ImageIcon theImage = new ImageIcon(bufferedImage);
            JLabel lblForImage = new JLabel(theImage);
            lblForImage.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            panelCenter.add(lblForImage);
        }
        this.add(panelCenter, BorderLayout.CENTER);
}

情况:

我们想在这里展示赛道。应通过将标准贴片彼此相邻放置来显示电路。应该可以调整窗口的大小,然后,电路图块也应该调整大小。

((编辑:更多信息:竞赛电路数据存储在服务器上,桌面应用程序必须通过按正确的顺序放置一些标准磁贴将数据转换为可视化的东西。))

((编辑:我们不允许使用任何外部库。仅使用Java Swing代码可以使用。)

我考虑将图像放在JLabel中,并将这些JLabel放在一个GridLayout作为布局管理器的面板中。

使用GridLayout - 我想 - 应该很容易找到解决方案: GridLayout(= JLabels)中的组件已经缩放并完全按照我的意愿行事。 现在,只需要找到一种方法来调整图像大小,以便填充JLabel

如您所见:目前,图像尺寸固定,根本无法缩放。

我浏览了一下,看到很多解决方案可以归结为使用 Graphics2D super.paintComponent 等。

但是大多数这些解决方案与GridLayout无关。 如此确凿的问题: 是否有更简单的解决方案,除了使用Graphics2D等知道我使用GridLayout?

如果没有,我当然会使用Graphics2D等,但我现在只是在探索我的选择。 :)

((编辑:已解决这些瓷砖现在整齐地贴合在一起。不要在意错位,这是我们的错。)) result

2 个答案:

答案 0 :(得分:2)

没有Swing组件可以执行您想要的操作,因此您需要编写自己的代码。

最简单的方法是在你的JLabel上使用Darryl的Stretch Icon

或者另一种方法是创建自己的自定义组件,在绘制图像时动态缩放图像。像Background Panel这样的代码,它包含允许您缩放或平铺图像的代码。

答案 1 :(得分:1)

鉴于视图的性质,我建议完全放弃图像,而是在Icon中实现渲染。假设您可以使用标签制作图标比例。