我已经搜索过这样的所有问题,但我无法找到解决方案。
public class FormPanel extends JPanel
{
private JLabel namelabel;
private JLabel occlabel;
private JTextField nametext;
private JTextField occtext;
private JButton okButton;
public FormPanel() {
Dimension dim = getPreferredSize();
dim.width = 250;
setPreferredSize(dim);
namelabel = new JLabel("Name : ");
occlabel = new JLabel("Occupation : ");
nametext = new JTextField();
nametext.setPreferredSize(new Dimension(80,20));
occtext = new JTextField();
occtext.setColumns(20);
okButton = new JButton("OK");
Border inner = BorderFactory.createTitledBorder("Add Person : ");
Border outer = BorderFactory.createEmptyBorder(5,5,5,5);
setBorder(BorderFactory.createCompoundBorder(inner,outer));
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.weightx = 1;
gc.weighty = 1;
gc.fill = GridBagConstraints.NONE;
add(namelabel,gc);
gc.gridx = 1;
gc.gridy = 0;
add(nametext,gc);
gc.gridy = 1;
gc.gridx = 0;
add(occlabel,gc);
gc.gridy = 1;
gc.gridx = 1;
add(occtext,gc);
gc.gridy = 2;
gc.gridx = 1;
add(okButton,gc);
}
}
nametext
和occtext
非常小。
我尝试了新的JTextField(20)和字符串版本,
我尝试了setPreferredSize作为上面的类,
我也尝试过setColumn,但没有一个可以工作。
答案 0 :(得分:6)
摆脱setPreferredSize(dim);
。通过在顶级窗口调用pack()
让GUI大小本身,你的问题可能会消失。您将容器的大小限制在可能小于最佳容器的范围内,这样,GridBagLayout将以一种糟糕的方式收缩其组件,包括您的JTextFields。
答案 1 :(得分:0)
如果您使用pack()
,则设置dim.height
可能是个好主意。
Dimension dim = getPreferredSize();
dim.width = 500;
dim.height = 200;
setPreferredSize(dim);
namelabel = new JLabel("Name : ");
nametext = new JTextField();
occlabel = new JLabel("Occupation : ");
occtext = new JTextField();
okButton = new JButton("OK");
Border inner = BorderFactory.createTitledBorder("Add Person : ");
Border outer = BorderFactory.createEmptyBorder(5, 5, 5, 5);
setBorder(BorderFactory.createCompoundBorder(inner, outer));
GridBagLayout gl = new GridBagLayout();
GridBagConstraints gc = new GridBagConstraints();
setLayout(gl);
gc.fill = GridBagConstraints.HORIZONTAL;
gc.gridwidth = 1;
add(namelabel, gc);
gc.gridy = 1;
add(occlabel, gc);
gc.gridx = 1;
gc.gridy = 0;
gc.weightx = .5;
add(nametext, gc);
gc.gridy = 1;
add(occtext, gc);
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.EAST;
gc.gridy = 2;
gc.gridx = 1;
gc.weightx = 0;
gc.insets = new Insets(10,0,0,0);
add(okButton, gc);