我创建了一个超类(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 上: