tags:

views:

749

answers:

3

I'm working with JTextField and the code for the text field. I'm trying to make a textfield as big as the notepad but the cursor always appears in the middle. I want to put in the starting of the textfield.

tf=new JTextField(50);
tf.setCaretPosition(0);

f.setLayout(new BorderLayout());
f.add(tf,BorderLayout.CENTER);
+2  A: 

Try setting the text alignment:

JTextField textfield = new JTextField("Initial Text");

// Left-justify the text
textfield.setHorizontalAlignment(JTextField.LEFT);

// Center the text
textfield.setHorizontalAlignment(JTextField.CENTER);

// Right-justify the text
textfield.setHorizontalAlignment(JTextField.RIGHT);
OMG Ponies
+1: the right answer
dfa
I'm not going to mark it down since it's still useful information, but it's *not* the right answer -- `JTextField` defaults to horizontal alignment, and the poster's problem is with vertical alignment (as you can quickly see if you run the code).
David Moles
Oops -- that should be: "defaults to _center_ horizontal alignment".
David Moles
+2  A: 

Not a very clear question. Since you are adding the text field to the center of a BorderLayout, the text field will automatically resize both vertically and horizontally to fill the space available in the frame.

By default the cursor will appear on the left horizontally and in the center vertically. So I guess the vertical alignment is what you are complaining about. Well, I don't know any way to solve the problem since this is the way the text field UI works.

If you change the font size of the text then it will appear bigger and the caret will appear more to the top.

I suggest you use try using a JTextArea. The Single Line Text Area may work the way you want.

camickr
+1  A: 

Since JTextField holds only a single line of text, you might be better off sizing the JTextField more appropriately.

As far as I know there is no good way to do exactly what you asked for. Note that while there is setHorizontalAlignment(), there is no corresponding setVerticalAlignment(). setAlignmentY() doesn't do it either (that sets the alignment of components added to a container, which doesn't make sense for a JTextField).

You can fake it by placing the JTextField in the north of the BorderLayout, as follows:

tf.setBorder(null);
f.setBackground(Color.WHITE);
f.add(tf, BorderLayout.NORTH); 
f.add(Box.createVerticalGlue(), BorderLayout.CENTER);

But I suspect what you really want may be multiple lines, in which case you should be using a JTextArea.

David Moles