Java文本字段显示不正确,它看起来像一条狭缝
我创建了一个JLabel
,它显示一个背景图像,然后我添加了三个按钮和一个JTextField
,并且JLable
的布局是GridBagLayout
,但主要问题是JTextField
的大小。我犯了什么错?我试过preferredSize
和setBounds
。我是新来的
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);
# 1 楼答案
首先,如果您希望人们花时间查看您的代码,那么您应该:
当框架中没有足够的空间以首选尺寸显示零部件时,会发生这种情况。GridBagLayout将以最小尺寸显示组件,这就是为什么会得到一个非常小的文本字段
由于使用了pack(),因此基本代码看起来很合理。但是,您可能会在其他地方使用setSize(…)覆盖pack()或者别的什么
如果您需要更多帮助,请发布一个适当的SSCCE来演示您的问题
# 2 楼答案
1)可以为
JTextField
指定列计数,如:t = new JTextField("TextField",20);
2)借助
GridBagConstraints
参数:weightx
和fill
3)避免使用:
阅读有关How to Use GridBagLayout的更多信息
例如: