Thursday, November 24, 2011

JTextField Horizontal Alignment

    package org.best.example;
    /*
            JTextField Horizontal Alignment Example
            This java example shows how to get or set horizontal alignment of
            JTextField's text using Java Swing JTextField class.
    */
    
    
    import java.awt.FlowLayout;
    import javax.swing.JApplet;
    import javax.swing.JTextField;
    
    /*
    <applet code="JTextFieldHorizontalAlignmentExample" width=200 height=200>
    </applet>
    */
    
    public class JTextFieldHorizontalAlignmentExample extends JApplet{
          
            public void init(){
                  
                    //set flow layout for the applet
                    this.getContentPane().setLayout(new FlowLayout());
    
                    //create new JTextField
                    JTextField field = new JTextField("JTextField Horizontal Alignment Example", 10);
                  
                    /*
                     * To get horizontal alignment of JTextBox's text use,
                     * int getHorizontalAlignment()
                     * method of JTextField class.
                     *
                     * Return value is one of the following values,
                     * JTextField.LEFT, JTextField.CENTER, JTextField.RIGHT
                     * JTextField.LEADING, Or JTextField.TRAILING
                     */
                  
                    int horizontalAlignment = field.getHorizontalAlignment();
                  
                    switch(horizontalAlignment){
                  
                            case JTextField.LEFT:
                                    field.setText("Left");
                                    break;
                            case JTextField.RIGHT:
                                    field.setText("Right");
                                    break;
                            case JTextField.CENTER:
                                    field.setText("Center");
                                    break;
                            case JTextField.LEADING:
                                    field.setText("Leading");
                                    break;
                            case JTextField.TRAILING:
                                    field.setText("Trailing");
                                    break;
                    }
                    /*
                     * To set horizontal alignment of JTextField's text use,
                     * void setHorizontalAlignment(int alignment)
                     * method of JTextField class.
                     */
                  
                    //field.setHorizontalAlignment(JTextField.CENTER);
                  
                    add(field);
                  
            }
    }

No comments: