java - 相对于背景图像的跨平台布局

标签 java swing layout cross-platform

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

这种方法在单一平台上按预期工作;但是,当我在不同的平台上运行应用程序时,JTextField 会根据外观调整/移动。如果我将布局管理器设置为 null,JTextField 仍保留在适当的位置,但我会丢失 JTextField 的大小调整。理想情况下,我想保留 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 上:

enter image description here

在 Linux 上:

enter image description here

最佳答案

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

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

关于java - 相对于背景图像的跨平台布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17535646/

相关文章:

Java Scanner - 将换行符读取到字符串中?

java - Int 中的构造函数 String

html - 试图理解 float 和文本

algorithm - UI 的快速布局算法

java - Sugar ORM 如何将数据添加到表中的一行

java - 为什么 java AudioSystem.getTargetEncodings( AudioFormat ) 返回的 Encoding 与我们提供的 AudioFormat 的编码不同?

java - 无法使用 pdfbox 打印任何内容

java - HTMLDocument 文本中位置或偏移量的含义

java - Eclipse 上的 JOptionPane 错误

android - AVD 忽略布局大/文件