by Dinesh Thakur

The JTextField is a text field of a single line. Class inherits from the javax.swing.text.JTextComponent. Its methods include:

• public JTextField (int NumCols): creates a JTextField NumCols occupying columns. If it contains the text exceeds this size will not be lost even if it can not display all simultaneously;
• public JTextField (String text, int NumCols): same as above but also present an initial text;
• public void setFont (Font font): sets the font with which the text is displayed;
• public String getText () returns its content in left;
• public String getSelectedText (): returns the selected text inside;
• public void copy (): Copies the selected text to the system clipboard;
• public void cut (): same as above but also removes the selected text;
• public void setEditable (boolean b) Enables or disables the ability to change the text content.

 

import java.awt.*;

import javax.swing.*;
import java.awt.event.*;
public class JavaExampleTextFieldAlignmentInJApplet extends JApplet
{
    JTextField Txt = new JTextField("Welcome To Java");
    JButton BtnLft,BtnRght,BtnCntr;
    public void init()
      {
        Container Cntnr = getContentPane();
        Txt.setColumns(30);
        Cntnr.setLayout(new FlowLayout());
        Cntnr.add(new ButtonPanel());
        Cntnr.add(Txt);
      }
        class ButtonPanel extends JPanel implements ActionListener
           {
               public ButtonPanel()
              {
                  BtnLft = new JButton("Left");           
                  BtnRght = new JButton("Right");           
                  BtnCntr = new JButton("Center");           
                  BtnLft.addActionListener(this);
                 BtnRght.addActionListener(this);
                 BtnCntr.addActionListener(this);
                 setLayout(new FlowLayout());
                 add(new JLabel("Alignment"));
                 add(BtnLft);
                 add(BtnRght);
                 add(BtnCntr);
               }
                  public void actionPerformed(ActionEvent e1)
                   {
                        if(e1.getSource() == BtnLft)
                      {
                             Txt.setHorizontalAlignment(Txt.LEFT);
                          }
                         else if(e1.getSource() ==BtnRght)
                          {
                                       Txt.setHorizontalAlignment(Txt.RIGHT);
                                   }
                                        else if(e1.getSource() ==BtnCntr)
                                    {
                                                 Txt.setHorizontalAlignment(Txt.CENTER);
                                            }
                   }
               }
}
/*<APPLET  CODE =JavaExampleTextFieldAlignmentInJApplet.class  WIDTH=360 HEIGHT=290></APPLET>*/

JTextField Alignment in Java Example