布局管理器,用于背景图像和文本

我正在尝试考虑最好的布局管理器来实现下图。 我知道绝对定位是我习惯的,但我无法使用它获得背景图像。 GridBagLayout非常好,但是当我尝试为每个网格获得单独的图像时,我会非常努力。

有没有人知道一个简单的方法,或简单的代码来实现以下目的?

在此处输入图像描述

有很多方法可以实现这一目标。

最简单的可能就是使用已有的东西 在此处输入图像描述

如果您不需要在运行时缩放背景(即您可以使用不可resize的窗口),只需使用JLabel作为主容器就可以使您的生活更加轻松。

 public class LabelBackground { public static void main(String[] args) { new LabelBackground(); } public LabelBackground() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { } JFrame frame = new JFrame("Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new LoginPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class LoginPane extends JLabel { public LoginPane() { try { setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/background.jpg")))); } catch (IOException ex) { ex.printStackTrace(); } setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.EAST; gbc.insets = new Insets(2, 2, 2, 2); gbc.gridx = 0; gbc.gridy = 0; JLabel nameLabel = new JLabel("Name: "); nameLabel.setForeground(Color.WHITE); JLabel passwordLabel = new JLabel("Password: "); passwordLabel.setForeground(Color.WHITE); add(nameLabel, gbc); gbc.gridy++; add(passwordLabel, gbc); gbc.anchor = GridBagConstraints.WEST; gbc.gridx++; gbc.gridy = 0; add(new JTextField(20), gbc); gbc.gridy++; add(new JTextField(20), gbc); gbc.gridy++; gbc.insets = new Insets(10, 2, 2, 2); gbc.anchor = GridBagConstraints.EAST; add(new JButton("Submit"), gbc); } } } 

更新了左对齐的示例

在构造函数的末尾,添加…

 JPanel filler = new JPanel(); filler.setOpaque(false); gbc.gridx++; gbc.weightx = 1; add(filler, gbc); 

在此处输入图像描述

您可能希望了解如何使用GridBagLayout获取更多详细信息

有几种方法可以做到这一点。 这些是我现在能想到的:

  1. 创建JComponent的子类。
  2. 重写paintComponent(Graphics g)方法以绘制要显示的图像。
  3. JFrame 的内容窗格设置为此子类。

一些示例代码:

 class ImagePanel extends JComponent { private Image image; public ImagePanel(Image image) { this.image = image; } @Override protected void paintComponent(Graphics g) { g.drawImage(image, 0, 0, null); } } // elsewhere BufferedImage myImage = ImageIO.read(...); JFrame myJFrame = new JFrame("Image pane"); myJFrame.setContentPane(new ImagePanel(myImage)); 

请注意,此代码不会处理重新调整图像大小以适应JFrame ,如果这是您想要的。