+92 332 4229 857 99ProjectIdeas@Gmail.com

JTextField Properties (Java)




The following are some commonly used properties of JTextField, like defining , setting size, pressing key , changing text color etc...

Code



Defining JTextField:


     // JTextField Defining
      JTextField txtInput = new JTextField();
                     
Setting JTextField size: 

    // Setting Size Of JTextField Explicitly
      txtInput.setPreferredSize(new Dimension(100, 50));
              

Enter KeyPressed On JTextField:

    /* If user pressed key on JTextField after writing something"
       If you want to use any object inside anonymous inner class then
       you have to declare it "final"*/
 
     final JTextField txtInput = new JTextField();
     
      txtInput.addKeyListener(new KeyAdapter() {
                          
           public void keyPressed(KeyEvent ke) {
                                 
                 if ( ke.getKeyCode() == KeyEvent.VK_ENTER) {
                                        
                        JOptionPane.showMessageDialog(null, txtInput.getText());
                 }
           }
      });
             

Changing JTextField FontStyle:       

     // Changing Font Style, Making It Italic and specifying font size
     txtInput.setFont(new Font("Comic Sans",Font.ITALIC,14));

Changing JTextField text color:                    
     
    // Changing JTextField Text color
     txtInput.setForeground(Color.BLUE);

Getting Text from JTextField:

    // Getting text from JtextField
     String getText = txtInput.getText();

Setting Text to JTextField: 

   // Setting Text to JTextField
     txtInput.setText("Hello World!!!");

0 comments: