【发布时间】:2014-05-13 14:39:53
【问题描述】:
我创建了一个JLabel,它显示了一个背景图像,然后我添加了三个按钮和一个JTextField,JLable 的布局是GridBagLayout,但主要问题是JTextField。我的错误是什么?我试过preferredSize 和setBounds。我是GridBagLayout 的新手。
p = new JPanel();
ImageIcon img = new ImageIcon("C:/Users/manpreet/Desktop/G.L.E.W/3.jpg");
l = new JLabel(img);
practice = new JButton("Practice (No Time Limit)");
Challenge = new JButton("Challenge (60 Seconds)");
l.setLayout(g);
practice.setFont(new Font("Garamond", Font.BOLD, 20));
practice.setForeground(Color.yellow);
practice.setBackground(Color.black);
Challenge.setBackground(Color.black);
Challenge.setFont(new Font("Garamond", Font.BOLD, 20));
Challenge.setForeground(Color.yellow);
gbc.gridx = 0;
gbc.gridy = 0;
l.add(practice,gbc);
gbc.gridwidth=1;
Insets insets1 = new Insets(2,2,2,2);
gbc.insets = insets1;
gbc.gridx = 2;
gbc.gridy = 0;
l.add(Challenge,gbc);
gbc.gridx=1;
gbc.gridy = 1;
t = new JTextField("TextField");
//t.setPreferredSize(new Dimension(150,20));
//t.setBounds(5,5,20,20);
start = new JButton("start");
t.setVisible(true);
start.setVisible(true);
l.add(t,gbc);
gbc.gridx=1;
gbc.gridy = 2;
l.add(start,gbc);
p.add(l);
f.add(p);
f.pack();
practice.addActionListener(this);
Challenge.addActionListener(this);
【问题讨论】:
-
删除 f.pack()。这应该可以帮助您朝着正确的方向前进
-
@Sanjeev 不,不要删除 pack()。 pack() 需要以首选大小显示组件。问题是文本字段未以其首选大小显示。
-
所以你想将按钮和文本字段添加到带有图片的标签中?您看到按钮和图像,但 textField 显示为一条线?只是需要澄清一下你所看到的。
-
谢谢大家,但实际上我发现了我的错误,使用 gridwidth=1 后代码工作正常,感谢您的时间。
标签: java swing jtextfield gridbaglayout