布局管理器,用于背景图像和文本 [英] Layout Manager for background images and text
问题描述
我正在考虑最好的布局管理器来实现下图。我知道绝对定位是我习惯的,但我无法使用它获得背景图像。 GridBagLayout
非常好,但是当我尝试为每个网格获取单独的图像时,我会非常努力。
I'm trying to think of the best layout manager to achieve the picture below. I know absolute positioning is what I am used to, but I can't get the background image using this. GridBagLayout
is excellent, but horrifically hard when ever I try I get a separate image for each grid.
有没有人知道一个简单的方法,或者简单的代码来实现以下目标?
Does anyone know an easy way out of this, or easy code to achieve the following?
推荐答案
你可以通过多种方式实现这一目标。
There are a number of ways you can achieve this.
最简单的方法就是使用现有的 ...
The simplest might be to just use what's already available...
如果您不需要在运行时缩放背景-time(即你可以使用不可调整大小的窗口),只需使用 JLabel
,因为主要容器可以让你的生活变得更加轻松。
If you don't need the background to be scaled at run-time (ie you can get away with a non-resizable window), simply using a JLabel
as the primary container could make your life significantly easier.
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);
}
}
}
更新左对齐示例
在构造函数的末尾添加...
At the end of the constructor, add...
JPanel filler = new JPanel();
filler.setOpaque(false);
gbc.gridx++;
gbc.weightx = 1;
add(filler, gbc);
您可能想看看如何使用GridBagLayout 获取更多详细信息
You might like to take a look at How to use GridBagLayout for more details
这篇关于布局管理器,用于背景图像和文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!