Program Description:
This program is just a simple java code to illustrate on how to re-size the JTextField in a simple way using simple code. Similar to JPanel, the way on how to change JTextField size is through the method setPreferredSize(); and the class Dimension.
Output:
Code:
/** * File: resizeJTextField.java * Tiltle: Simple way in Resizing JTextField * Author: http://java-program-sample.blogspot.com/ */ //Java Core Package import javax.swing.*; //Java Extension Package import java.awt.*; public class resizeJTextField extends JFrame { //Constructing JTextFields JTextField size1 = new JTextField("RESIZING JTEXTFIELD"); JTextField size2 = new JTextField("RESIZING JTEXTFIELD"); JTextField size3 = new JTextField("RESIZING JTEXTFIELD"); JTextField size4 = new JTextField("RESIZING JTEXTFIELD"); //Setting up GUI public resizeJTextField() { //Setting up the Title of the Window super("Simple way in Resizing JTextField"); //Set Size of the Window (WIDTH, HEIGHT) setSize(500,435); //Exit Property of the Window setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Setting up the container ready for the components to be added. Container pane = getContentPane(); setContentPane(pane); //Setting up the layout of the container pane.setLayout(new FlowLayout(FlowLayout.CENTER)); //Setting the JTextField text to center size1.setHorizontalAlignment(SwingConstants.CENTER); size2.setHorizontalAlignment(SwingConstants.CENTER); size3.setHorizontalAlignment(SwingConstants.CENTER); size4.setHorizontalAlignment(SwingConstants.CENTER); //Spicify the size of the JTextField using the method setPreferredSize() and the class Dimension size1.setPreferredSize(new Dimension(450,150)); size2.setPreferredSize(new Dimension(450,100)); size3.setPreferredSize(new Dimension(450,75)); size4.setPreferredSize(new Dimension(450,50)); //add the JTextFields in the container pane.add(size1); pane.add(size2); pane.add(size3); pane.add(size4); /**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) { resizeJTextField pjtf = new resizeJTextField(); } }
Important Part of the Program:
//Spicify the size of the JTextField using the method setPreferredSize() and the class Dimension size1.setPreferredSize(new Dimension(450,150)); size2.setPreferredSize(new Dimension(450,100)); size3.setPreferredSize(new Dimension(450,75)); size4.setPreferredSize(new Dimension(450,50));