居中JTextField(不是字段内的文本!)



如何将JTextField居中

注意!我不想在JTextField中居中(这是使用setHorizontalAlignment(JTextField.CENTER)实现的),而是我想在它所在的空间中居中实际的JTextField,就像jLabel.setHorizontalAlignment(SwingConstants.CENTER)会做的那样。

我建议使用GridBagLayout。

panel.setLayout(new GridBagLayout());
GridBagConstraints center = new GridBagConstraints();
center.anchor = GridBagConstraints.CENTER;
center.fill = GridBagConstraints.NONE;
panel.add(textField, center);

Null Layout:表示没有Layout。项目必须手动定位和排列这个布局应该只在窗口不会也不能调整的大小,因为窗口中的项目将保持不变他们被安置在哪里?http://www.tech-recipes.com/rx/1205/java-null-layout-manager-swing/

  • http://www.tech-recipes.com/rx/1205/java-null-layout-manager-swing/
  • http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html

第一个链接使用.setLocation(x, y)来定位控件,第二个链接使用.setBounds(...)。你需要自己做居中

最新更新