Thursday, July 28, 2011

JTextField Text Alignments

Design Free Website with Free Internet Marketing Tools

Output:
Code:

/**
 * File: jtextfieldTextAlignment.java
 * Tiltle: JTextField Text Alignments
 * Author: http://java-program-sample.blogspot.com
 */

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;

public class jtextfieldTextAlignment extends JFrame {
 
 //Initializing JTextField
 private JTextField left, right, center;

 //Setting up GUI
    public jtextfieldTextAlignment() {
     
     //Setting up the Title of the Window
     super("JTextField Text Alignments");

     //Set Size of the Window (WIDTH, HEIGHT)
     setSize(250,105);

     //Exit Property of the Window
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

     //Constructing JTextField with a size of 20 with a specified string "Enter Text Here..."
     left = new JTextField("Left",20);
     right = new JTextField("Right",20);
     center = new JTextField("Center",20);
     
     //Aligning JTextField Text in Horizontal
     left.setHorizontalAlignment(SwingConstants.LEFT);
     right.setHorizontalAlignment(SwingConstants.RIGHT);
     center.setHorizontalAlignment(SwingConstants.CENTER);

     //Setting up the container ready for the components to be added.
     Container pane = getContentPane();
     setContentPane(pane);
     
     //Setting up the container layout
     FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
     pane.setLayout(flow);

     //Adding the JTextField component to the container
     pane.add(left);
     pane.add(right);
     pane.add(center);

     /**Set all the Components Visible.
      * If it is set to "false", the components in the container will not be visible.
      */
     setVisible(true);
    }
    
 //Main Method
    public static void main (String[] args) {
     jtextfieldTextAlignment jtfa = new jtextfieldTextAlignment();
 }
}

Important Part of the Program:

//Constructing JTextField with a size of 20 with a specified string "Enter Text Here..."
     left = new JTextField("Left",20);
     right = new JTextField("Right",20);
     center = new JTextField("Center",20);
     
     //Aligning JTextField Text in Horizontal
     left.setHorizontalAlignment(SwingConstants.LEFT);
     right.setHorizontalAlignment(SwingConstants.RIGHT);
     center.setHorizontalAlignment(SwingConstants.CENTER);

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Hostgator Discount Code