3

我创建了一个超类(ImagePanel),它扩展了 JPanel 并将图像绘制为背景。在我的 ImagePanel 子类中,我使用 GroupLayout(通过 NetBeans GUI 设计器)用与底层图像对齐的 JTextField 覆盖面板。

这种方法在单个平台上按预期工作;但是,当我在不同的平台上运行应用程序时,JTextField 会根据外观调整大小/移动。如果我将布局管理器设置为空,JTextFields 将保持在适当的位置,但我失去了 JTextFields 的大小调整。理想情况下,我想保留 JTextFields 的位置,但是否根据 L&F 调整它们的大小?我该如何以不同的方式处理这个问题?

/**
 * Extends JPanel adding the ability to paint a background image.
 */
public class ImagePanel extends JPanel implements Serializable
{
    public static final String PROP_IMAGEFILE = "imageFile";

    //~--- fields -------------------------------------------------------------

    private ImageIcon imageIcon;
    private String imageFile;

    /**
     * Constructs a new ImagePanel.
     */
    public ImagePanel()
    {
        // required by Beans specification.
    }

    /**
     * Get the path to the image file used to paint the background.
     *
     * @return the path.
     */
    public String getImageFile()
    {
        return imageFile;
    }

    /**
     * Set the path to the image file used to paint the background.
     *
     * @param imageFile the image file path.
     */
    public void setImageFile(String imageFile)
    {
        String oldImageFile = this.imageFile;

        this.imageFile = imageFile;

        imageIcon = new ImageIcon(getClass().getResource(imageFile));

        firePropertyChange(PROP_IMAGEFILE, oldImageFile, imageFile);
    }

    /**
     * Overridden to draw image background image.
     */
    @Override
    public void paintComponent(Graphics g)
    {
        /* Draw image on the panel */
        super.paintComponent(g);

        if (imageIcon != null)
        {
            /* create image icon to get image */
            Image image = imageIcon.getImage();

            if (image != null)
            {
                g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
            }
        }
    }
}

在 Windows 上:

在此处输入图像描述

在 Linux 上:

在此处输入图像描述

4

1 回答 1

0

我不确定复合布局在这种情况下的效果如何,它很可能是您确实需要空布局的 1% 的情况之一(尽管应尽可能避免这种情况)。如前所述,miglayout 可能会与一些游戏一起使用,但您可能需要做的是硬编码比率值而不是位置值。计算代表每个组件的位置和大小的图像百分比,并在绘制图像后,使用这些比率值以编程方式布置组件。

可以编写一个新的布局管理器来完成同样的事情(并且可能比上面的空布局方法更受欢迎。add(); 方法可以采用 5 个变量(组件、位置 x 的比率值、位置 y 的比率值、大小位置 x 的值,位置 y 的大小值);我不太了解如何编写布局管理器,但它是一个选项。

于 2013-11-13T14:49:03.987 回答