Center the text in the textfield

Is there a way to center the text in the text field? Specially vertically.

It seems that when a new text is set, the start position of the text is not recomputed, as the following example demonstrates. Initially all text fields are aligned correctly. But when you then hit the update button, all textfields are updated with a new, longer text which shows the problem. All texts seem to start at the same position which was computed for the previous text and not the recomputed new position for the new text. To temporarily work around this problem, you can reset the alignment of the text fields and then set it back to your desired value. This forces a recomputation of the text start position.
package textfield.alignment;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TextFieldAlignment extends Application {
     TextField lText;
     TextField cText;
     TextField rText;
     public static void main(String[] args) {
          launch(args);
     @Override
     public void start(Stage stage) {
          lText = new TextField("left");
          lText.setAlignment(Pos.BASELINE_LEFT);
          cText = new TextField("center");
          cText.setAlignment(Pos.BASELINE_CENTER);
          rText = new TextField("right");
          rText.setAlignment(Pos.BASELINE_RIGHT);
          Button btn = new Button("update");
          btn.setOnAction(new EventHandler<ActionEvent>() {
               @Override
               public void handle(ActionEvent t) {
                    lText.setText("updated left");
                    cText.setText("updated center");
                    rText.setText("updated right");
//                    applyWorkaround();
          VBox root = new VBox();
          root.getChildren().addAll(lText, cText, rText, btn);
          stage.setScene(new Scene(root, 200, 300));
          stage.show();
     void applyWorkaround() {
          lText.setAlignment(Pos.CENTER);
          lText.setAlignment(Pos.BASELINE_LEFT);
          cText.setAlignment(Pos.CENTER);
          cText.setAlignment(Pos.BASELINE_CENTER);
          rText.setAlignment(Pos.CENTER);
          rText.setAlignment(Pos.BASELINE_RIGHT);          
}

Similar Messages

  • How to center the text displayed in a JList

    Hi,
    The width of the JList display area is wider than the text displayed. I tried to center the text displayed to make it look nicer. I had tried using "setAlignmentX(Component.CENTER_ALIGNMENT)" in my own ListCellRenderer class but did not work. Any idea how to center the text?
    Fai.

    Yes, I am using JLabels in my renderer and the following is the code:
    public class MyCellRenderer extends JLabel implements ListCellRenderer {
         private static final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
         public MyCellRenderer() {
              setOpaque(true);
              setIconTextGap(12);
         public Component getListCellRendererComponent(
              JList list,
              Object value,
              int index,
              boolean isSelected,
              boolean cellHasFocus)
              String entry = (String)value;
              setText(entry);
              setFont(new Font("Ariel", Font.BOLD, 18));
              setAlignmentX(Component.CENTER_ALIGNMENT);
              if(isSelected) {
                   setBackground(HIGHLIGHT_COLOR);
                   setForeground(Color.white);
              } else {
                   setBackground(Color.white);
                   setForeground(Color.black);
              return this;
    Can you point out where to implement the centering logic?
    Thanks,
    Fai.

  • How to center the text in JLabel without image?

    I need to center the text inside JLabel, how do i do it?
    Also I need some advise, what is the best way to mark a clicked card (I'm making a card game)?

    I found this method that controls that text alignment:you can try few more:
    label.setVerticalAlignment(JLabel.CENTER);    //these two would  center the label contents
    label.setHorizontalAlignment(JLabel.CENTER);
    label.setHorizontalTextPosition(JLabel.CENTER);Thanks!

  • How to split text according to the textfield size

    Hi, its very urgent if anybody can help me out..... i am
    working on an e-learning course where all the text is coming
    through XML. Client is very specific about not to use scrollbar.
    They want to use more and back buttons to show the rest of the text
    (they dont want the text to be scrolled either). For that I created
    a function to part the text according to the textfield height in an
    array. (one important point is that user can change font type, font
    size anytime in between the course). Here is a bit of code
    This code is working fine, but it gives undesired output if
    we use html tags in helpText
    please help me out..... please

    Thanks FlashTastic,
    I am sorry for not being able to convey my problem....
    actually problem is not that code is not recognizing the tags but
    the problem is.... let me explain, suppose there is a tag <b>
    and </b> in xml..... code split the text so it split
    <b> and </b> too and stored it in an array.... then it
    adds the text i.e. This is a <b> sample </b> text.....
    til the textheight of the textfield is less than the ._height of
    hte textfield and finally i have a string that fits in the
    textfield perfectly and when the parted text is assigned to the
    textfield it recognize the tag and make that bunch of words or
    sentence bold and that creates the problem.... i hope that this
    time it is more clearer....
    Thanks again.....

  • Access of the Text in the TextField

    In the following code ,how can I access text in the textfield(i.e object x in the following code) in the place of z in the following code:
    BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(z)));
    import java.awt.Color;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.JTextArea;
    public class TextAreaTest1
    public static void main(String[] args)
    TextAreaFrame frame = new TextAreaFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    A frame with a text area and buttons for text editing
    class TextAreaFrame extends JFrame implements ActionListener
    public String TextAreaFrame()
    setTitle("TextAreaTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    Container contentPane=getContentPane();
    contentPane.setLayout(new GridLayout(5,5,0,0));
    buttonPanel = new JPanel();
    JPanel textField=new JPanel();
    buttonPanel.add(new JLabel("enter"));
    // add button to append text into the text area
    JTextField x=new JTextField(20);
    JButton insertButton = new JButton("Insert");
    textField.add(new JLabel("Enter the path"));
    // textArea = new JTextArea(8, 30);
    // contentPane.add(insertButton);
    buttonPanel.add(insertButton);
    textField.add(x);
    String z=x.getText();
    insertButton.addActionListener(this);
    contentPane.add(textField);
    JPanel group=new JPanel();
              final JTextField a=new JTextField(18);
              JRadioButton b1=new JRadioButton("Start");
              group.add(b1);
              group.add(new JLabel("to"));
              group.add(a);
              JRadioButton b2=new JRadioButton("End");
              group.add(new JLabel("to"));
              group.add(b2,new JLabel("to"));
    add(group, BorderLayout.SOUTH);
    contentPane.add(buttonPanel);
    textArea = new JTextArea(8, 30);
    scrollPane = new JScrollPane(textArea);
    add(scrollPane);
    return(z);
    public String getField(){ return x.getTest();}
    public void actionPerformed(ActionEvent event)
         try
         BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(z)));
         String l;
                                  // String text = a.getText();
    System.out.println(+textArea.getLineCount());
         while((l=br.readLine())!=null)
    if(l.indexOf("error")==-1)
    textArea.append(l+"\n");
    textArea.setFont(new Font("Dialog", Font.BOLD, 12));
    textArea.setForeground(Color.blue);
    System.out.println("this");
    /*StringTokenizer st=new StringTokenizer(l);
         //String a="error";
    String[] b=new String[10];
         while(st.hasMoreTokens())
                                                           //if(!st.equals("error"))
    int i=0;
                                  String key=st.nextToken();
                                                           b=key;
                                                           {if(b[i].equals("error"))
                                                           textArea.setFont(new Font("Dialog", Font.BOLD, 12));
                                                           textArea.append(b[i]+"\n");
    System.out.println("this");
                                                           i++;}
                                                           else
                                                                     textArea.setFont(new Font("Serif", Font.PLAIN, 12));
                                                                     textArea.append(b[i]+"\n");
    System.out.println("that");
                                                           i++;
                                                           //if(!key.equals("error"))
    //textArea.append(key+"\n");
                                                           //String val=st.nextToken();
                                                           //textArea.setFont(new Font("Dialog", Font.BOLD, 12));
                                                           //textArea.append(ky+"\n");
                                                           //Font f=new Font("Serif",Font.BOLD,40);
                             //textArea.setColor(new JColorChooser());
         //textArea.append(val+"\n");
                                            if(l.indexOf("error")!=-1)
                                                 textArea.setFont(new Font("Serif", Font.PLAIN, 12));
                                                 //textArea.setColor(Color.black);
                                                 textArea.setForeground(Color.red);
                                                 textArea.append(l);
                                       System.out.println("that");
                        catch(Exception ex)
    public static final int DEFAULT_WIDTH = 400;
    public static final int DEFAULT_HEIGHT = 400;
    private JTextArea textArea;
    private JScrollPane scrollPane;
    private JPanel buttonPanel;
    private JButton wrapButton;

    1) Swing related questions should be posted in the Swing forum.
    2) Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.
    3) Use a more descriptive variable name. "x" means nothing.
    4) Define the text field reference name as a class variable, not a local variable.

  • Can I center the text in vertical direction in JTextArea

    for example , if the JTextArea is 50 pixels high, and the text 's height is 20 pixels,
    then how can I center the text in vertical direction in this JTextArea which means
    there is a extra space whose height is 15 pixels over and under the text?

    Exactly what are you trying to do?
    JTextAreas are usually in a scroll pane, you add multiple lines ie height can change
    are you going to make it uneditable etc
    if it is just for a display (uneditable), perhaps a 'tall' JTextField might give you the desired effect

  • Center the text in JOptionPane

    Hi!
    Is it possible to center the text in JOptionPane? I tried it with HTML but it's not working.
    Greetings
    Burricall

    String msg = "<html><body>The aim of the game is to get the highest number from all three rounds.<br>"+
    "A dice is lost at the end of each round.<br>"+
    "You are able to roll the dices agian at the end of each round but only ones at the end of each round.<br>"+
    "<center>Click on 'Ok' button to start the game.</center></body></html>";
    JOptionPane.showMessageDialog(null,msg);
    this must work
    regards
    tigerkumar
    Edited by: tigerkumar on Oct 4, 2007 9:55 AM

  • How to set the textfield not to scroll the text?

    hi to all....
    what will i do if i want the textfield not
    to scroll the text if the text is very long..
    what if i wanted the text will just display
    "this is a test..." a three dots will be display
    before reaching the end of the textfield...
    i tried geting the width of the text but what
    if the string contains so much letters such as letter
    "i" good if it will contain letters with big spaces to
    occupy.. but if letter "i" it would be small...
    pls. tell me.
    thanks in advance
    Kent

    well, u can do this...
    catch the keyPressed event which is generated when u press the VK_RIGHT button ( ->, right arrow key) (which u will for scrolling) and consume the event as soon as u reach the width of the text field.
    bye

  • Employees  has the same cost center long text as the previous record

    Hiiii Experts,
                          in ABAP-HR 2 employees have got the same cost centr text (kostl) with different perner.we shouldnt get  the same cost centres long text for diff pernr(employee numbers). please solve this.
    thanks and regards,
    Vishal

    Employee 01605429 has the same cost center long text as the previous record.
    01605304;A;MIKE.GESSLERMichael;Gessler;19000101;0500192745;;NUSA;NUSA SLS Solon Prepared Foods Sales;CD SOLON HQ
    01605429;A;DANA.SHERMAN;Dana;Sherman;19000101;0500193070;;NBSNA;NBS Solon Employee HR Services;CD SOLON HQ
    There are records in the file with no const center which should not be included in the file.  We need to know why they were extracted and why
    don't they have a cost center. See below.
    10252768;A;CHARISSA.HALFORD1Charissa;Halford;19000101;;;NPFC;;
    10252770;A;MATTHEW.CANADAY1;Matthew;Canaday;19000101;;;NPFC;;

  • Place in the center the column texts

    Hi BW knowledge broadcasters,
    I am looking for the method to place in the center the column texts. It seems it could be in the css implemented in the WAD web template. But I don't know neither for the queries built directly with the Query Designer.
    Thanks in advance.
    Geo

    One problem you will encounter is that the column headers and the rows have the same class associated to them and if you set this to center, your rows will also be centered.  You will need to either use the Table API to change the class of just the column headers or possibly with javascript.  To find the class, run the query in the web, right-click and select view source, search for the text in the columns and find the associated class referenced in the HTML. 
    Here is a link to all of the styles in the standard BWReports.css:
    <a href="http://help.sap.com/saphelp_bw33/helpdata/en/3f/ca453afbf37b54e10000000a11402f/content.htm">http://help.sap.com/saphelp_bw33/helpdata/en/3f/ca453afbf37b54e10000000a11402f/content.htm</a>
    This is specific to BW 3.x.  In 2004s, the styles are now driven from the Portal theme. 
    Thanks,
    Jeff

  • How do i center the text of a JLabel?

    How do i center the text of a JLabel?

    http://java.sun.com/j2se/1.4/docs/api/javax/swing/JLabel.html#setHorizontalTextPosition(int)

  • How do I center the text in full width accordion panel?

    Hello!
    Is it possible to center the text to follow the full width accordion widget?
    When you expand to fill the screen, the text are fixed and doesn't follow the center headline...
    I created a page so you see what I'm talking about:  http://fullwidthissue.businesscatalyst.com/index.html
    Please respond if you know what to do or if it's impossible..
    Thanx

    This believe this can be fixed within the <head> of the document. I had the same problem and it took me a bit to figure this solution.
    Step 1
    Find the <div> ID that muse gives to the content portion of the accordion element. you can find this by using a web browser that lets you inspect the code.
    Step 2 once you have that code replace u6174. with your specific <div> then past this into your <Head> of the muse document. Almost forgot.....Get a general idea of the minimum size around your content this example it was a width of 750px. and change the width accordingly on this code.
    <style>
    #u6174{
    width: 750px;
    padding-left: 0px;
    padding-right: 0px;
    margin-right: auto;
    margin-left: auto;
    border-right-width: 0px;
    border-left-width: 0px; "}
    </style>
    you can see a sample of this here:
    Alain Hunkins
    At the bottom is this solution working.
    Let me know if that helps.

  • How to compare Date in the TextField or DateTime with Date/Time field?

    Hi All,
    I am facing an issue with respect Date comparinson. I tried to look into entire discussions but failed to get the answer.
    My issue is: I wanted to comparet Date/time field value with Date value which is in TextField.
    The functionality of my form is:
    I have dropdown list which lists the registered customer ids binded to XML Datasource. On selection of the customer id from the dropdown I am displaying customer registration date in the TextField or say Date/Time field as below code in dropdown change event.
    RegistrationDetails.PurchaseEntry.txtRegDate.rawValue = regDataNode.CREATION_DATE.value; (this is TextField control)
    In form I have an Date/Time field in which use will select the date of item purchase. In the validation part I want to make sure that, the purchase date selected in Date/Time field must be greater than the Customer Registraiton Date. I able to compare if the customer selects the date from two different Date/Time fields. But how to compare the dates which one is in Date/Time field and Date is in TextField?
    I have tried using Num2Date and Date2Num with "YYYY-MM-DD"  format to compare but not succeed!
    Can you guys help me in this? Thanks in advance
    Regards.

    Hi,
    Yes, I am able to display the date which I have assigned to the text box. In the message box it show the value as '31/05/2009', since in this format i am assigining the date in the text box.
    Here is the code which I am assigning the value:
    RegistrationDetails.PurchaseEntry.txtRegDate.rawValue = regDataNode.CREATION_DATE.value;
    Do I need to change the format while assigning value in text box?
    You have told that, you have attached your test form, nothing is the reply. Can you repost the file?
    Regards.

  • HELP!How to show # and * in the textfield

    I am trying to show a # and * in the textfield in this telephone keypad interface. What's wrong with my coding? How can I show # and *? Whenever I press # and * on the keypad I get a Null or Infinity statement, when I just want # and * to show up instead. I had converted a calculator applet into a telephone applet to make into an keypad interface.
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class TelephoneApplet extends Applet implements ActionListener
    private Button keysArray[];
    private Panel keyPad;
    private TextField lcdField;
    private double result;
    private boolean first;
    private boolean foundKey;
    static boolean clearText;
    private int prevOperator;
    public void init()
    lcdField = new TextField(20);
    keyPad = new Panel();
    keysArray = new Button[12];
    first = true;
    result = 0.0;
    clearText = true;
    prevOperator = 0;
    setBackground(Color.magenta);
    lcdField.setEditable(false);
    for ( int i=0; i<=9; i++ )
    keysArray[ i ] = new Button(String.valueOf(i));
    keysArray[10] = new Button( "*" );
    keysArray[11] = new Button( "#" );
    // set keyPad layout to grid layout
    keyPad.setLayout(new GridLayout(4,3,10,10));
    for ( int i=1; i<=9; i++ ) //adds buttons 1-9 to Panel
    keyPad.add( keysArray[i] );
    /* for (int i = 4; i <= 6; i++) //adds buttons 4, 5, and 6 to Panel
    keyPad.add( keysArray[i] );
    for (int i = 7; i <= 9; i++) //adds buttons 7, 8, 9, and divide to Panel
    keyPad.add( keysArray[i] );
    keyPad.add( keysArray[10] ); //adds star button to Panel
    keyPad.add( keysArray[ 0 ] ); //adds 0 key to Panel
    keyPad.add( keysArray[11] ); //adds infinity button to Panel
    for (int i = 10; i >= 11; i--)
    keyPad.add( keysArray[i] ); //adds keys to Panel
    setLayout(new BorderLayout());
    add( lcdField, BorderLayout.NORTH );
    add( keyPad, BorderLayout.CENTER );
    for(int i = 0; i < keysArray.length; i++)
    keysArray.addActionListener(this);
    public void actionPerformed( ActionEvent e)
    foundKey = false;
    //Search for the key pressed
    for (int i = 0; i < 12 && !foundKey; i++)
    if(e.getSource() == keysArray[i]) //key match found
    foundKey=true;
    switch(i)
    case 0: case 1: case 2: case 3: case 4: //number buttons
    case 5: case 6: case 7: case 8: case 9:
              //0 - 9
    if(clearText)
    lcdField.setText("");
    clearText = false;
    lcdField.setText(lcdField.getText() + keysArray[i].getLabel());
    break;
    case 10:
    case 11:
    clearText = true;
    if (first) // first operand
    if(lcdField.getText().length()==0)
    result = 0.0;
    else
    result = Double.parseDouble(lcdField.getText());
    first = false;
    prevOperator = i;
    else //second operand already entered, so calculate total
    switch(prevOperator)
    case 10: //divide button
    result /= Double.parseDouble(lcdField.getText());
    break;
    case 11: //multiply button
    result *= Double.parseDouble(lcdField.getText());
    break;
    lcdField.setText(Double.toString(result));
    if(i==14) //equal button
    first = true;
    else
    prevOperator = i; //save last operator
    break;

    you need to change the following piece of code
    case 10:   // * pressed
    case 11:   // # pressed
    clearText = true;
    if (first) // first operand
    if(lcdField.getText().length()==0)
    result = 0.0;
    else
    result = Double.parseDouble(lcdField.getText());
    first = false;
    prevOperator = i;
    else //second operand already entered, so calculate total
    switch(prevOperator)
    case 10: //divide button
    result /= Double.parseDouble(lcdField.getText());
    break;
    case 11: //multiply button
    result *= Double.parseDouble(lcdField.getText());
    break;
    lcdField.setText(Double.toString(result));
    if(i==14) //equal button
    first = true;
    else
    prevOperator = i; //save last operator
    break;
    }its gets excuted when you press the * or # buuton

  • Chinese characters are displayed as blank box on the TextField in Taiwan Android 4.4.2/AIR4.0

    Chinese characters are displayed as blank box on the TextField in Taiwan Android 4.4.2/AIR4.0, such as Nexus7, HTC One,  but in mainland China Nexus7(Android 4.4.2/AIR4.0) showed normal
    AIR SDK is 4.0.0.1628.
    Hope it can be fixed as soon as possible.
    Here is test code:
    package
              import flash.display.Sprite;
              import flash.display.StageAlign;
              import flash.display.StageScaleMode;
              import flash.text.Font;
              import flash.text.TextField;
              import flash.text.TextFieldAutoSize;
              import flash.text.TextFormat;
              public class TestFont extends Sprite
                        public function TestFont()
                                  stage.scaleMode = StageScaleMode.NO_SCALE;
                                  stage.align = StageAlign.TOP_LEFT;
                                  var sprite:Sprite = new Sprite();
                                  var value1:String = "简体中文测试";
                                  var value2:String = "繁體中文測試";
                                  var txt11:TextField = createTextField(null, "11 "+value1);
                                  txt11.x = 10;
                                  txt11.y = 10;
                                  sprite.addChild(txt11);
                                  var txt12:TextField = createTextField(null, "12 "+value2);
                                  txt12.x = txt11.x + txt11.width;
                                  txt12.y = txt11.y;
                                  sprite.addChild(txt12);
                                  var txt21:TextField = createTextField("STHeitiTC-Medium","21 "+value1);
                                  txt21.x = 10;
                                  txt21.y = txt11.y + txt11.height;
                                  sprite.addChild(txt21);
                                  var txt22:TextField = createTextField("MSYH","22 "+value2);
                                  txt22.x = txt21.x + txt21.width;
                                  txt22.y = txt21.y;
                                  sprite.addChild(txt22);
                                  var lastY:int = txt22.y + txt22.height;
                                  var fonts:Array = Font.enumerateFonts(true);
                                  var index:int = 0;
                                  for each (var font1:Font in fonts)
                                            index++;
                                            var txtF:TextField = createTextField(font1.fontName, index + "/" + fonts.length + " " + font1.fontName + " "+value1 +" " + value2);
                                            txtF.x = 10;
                                            txtF.y = lastY;
                                            sprite.addChild(txtF);
                                            lastY += txtF.height;
                                  addChild(sprite);
                        public function createTextField(font:String, value:String):TextField{
                                  var txt:TextField = new TextField();
                                  txt.autoSize = TextFieldAutoSize.LEFT;
                                  var format:TextFormat = new TextFormat();
                                  if(font != null){
                                            format.font = font;
                                            txt.defaultTextFormat = format;
                                            txt.setTextFormat(format);
                                  txt.text = value;
                                  var dformat:TextFormat = txt.defaultTextFormat;
                                  if(dformat != null){
                                            txt.text = value + " |" + dformat.font;
                                  if(font != null){
                                            txt.setTextFormat(format);
                                  return txt;

    I am in mainland China, my Nexus7 can display chinese characters, but my friend in Taiwan, his android4.4.2 display chinese characters as blank.
    I don't understand the reason.
    By the way, TextFormat.font don't work, whatever I set any fonts, display are the same.
    My screenshots:
    Taiwan's screenshots:

Maybe you are looking for

  • XML data source and relative path

    Hi, I'm developing my reports in a Windows environment and deploying it on a Linux. My problem is, I cannot seem to specify a relative path for my XML datasource. Since, my deployement is in Linux, I cannot have the standard "C:\myreport\def.xml". Is

  • FRM - 40735 Error

    Hi, In Oracle EBS 11i ->HRMS module , when opening any form showing error message like FRM -40735 and ora 6508. And the error is only in this module. In other modules the forms are working. it has no error. What is the reason for this? Can any soluti

  • HT4623 MyiPhone 3GS on setting general does not have the place for software update adn I need to update to iOS5.1

    My iphone 3GS does not have in General the place for software update and for some my apps it request that I do iOS5.1 but I cannot do it tell me how

  • Heap errors in Windows NT 4.0

    Running a Java app under JRE version 1.4.1_03-b02 on a PC running NT 4.0 with 256 MB RAM. The app runs 7x24 doing OCR and business logic. The app uses JNI to talk to a C++ DLL, uses Oracle JDBC thin driver, Javacomm 2.0. It has been stable for severa

  • Link to reinstall Photoshop Elements 7.0

    Is it possible to get a link to reinstall Photoshop Elements 7.0 as there is a file missing in mine and it will not open?