Home > other >  When JTextField is full it shows text right-aligned
When JTextField is full it shows text right-aligned

Time:01-29

I have a JTextField where I show a Date, but the Date is a bit bigger than Field and it shows the info like this, shifted to the right:

I want the date shown shifted to the left:

I have been trying with

dateField.setHorizontalAlignment(JTextField.LEFT);
dateField.setHorizontalAlignment(SwingConstants.LEFT);

Nothing works. The same result is always displayed.

CodePudding user response:

Try:

textField.setText(...);
textField.setCaretPosition(0);

This should position the caret at the beginning so that all the text becomes aligned to the left.

Or you make the text field larger. When you create the text field you use code like:

textField = new JTextField(19);

This will make the text field large enough to hold 19 "W" characters.

Should you even be using a text field? If you just want to show a date, then use a JLabel.

CodePudding user response:

Can you show us the code where you are actually setting a value from the Date object (I presume) to the field? This seems more likely a formatting issue of the Date rather than an actual issue with the UI. Try setting a SimpleDateFormat as following to format the String returned by your date before setting it as value on the field.

Date yourDate = ...;
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
dateField.setValue(formatter.format(yourDate));
  •  Tags:  
  • Related