【发布时间】:2015-02-13 17:51:43
【问题描述】:
如何定位 JTextField?我搜索了很多例子,但不幸的是没有一个对我有用。有人能帮我吗?我想用绝对坐标定位它。
代码:
public static class TextDemo extends JPanel implements ActionListener {
protected JTextField textField;
static public String text;
public TextDemo() {
super(new GridBagLayout());
textField = new JTextField(20);
textField.addActionListener(this);
textField.setBounds(10,10,200,40);
//textField.setSize(500,500);
//Add Components to this panel.
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
}
public void actionPerformed(ActionEvent evt) {
text = textField.getText();
}
public static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TextDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add contents to the window.
frame.add(new TextDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
【问题讨论】:
-
我尝试使用
TextField.setBounds(100,100,100,25);,但没有成功 -
你尝试过grouplayout吗?绝对布局是个坏主意。
-
@Johan GroupLayout 不适合人类使用。有很多好的和容易使用的布局。我最喜欢的 2:
BorderLayout和GridBagLayout。我知道很多人只发誓MigLayout(但这不是标准) -
不,您不想使用绝对坐标定位它。不同的用户界面、不同的分辨率、不同的字体、不同的 L&F,只有使用 LayoutManager 才会好看。告诉我们/向我们展示您想要实现的目标,我们将向您展示正确的方法。相信我,绝对定位最终只会成为一场噩梦。
-
@GuillaumePolet 好的,但你是什么意思?我们目前在学校做一个项目,在秋千我们使用分组布局,所以你可以将组件放置在任何地方,但它的缺点是什么?
标签: java swing user-interface jframe jtextfield