samedi 20 février 2021

How to use conditional statements with JTextField

I'm a beginning programmer at a high school level, and I had a question regarding some of my code. I want to retrieve what a user inputs in a JTextField and use that in a conditional statement to perform a certain action. Whenever I type something in the field, nothing happens. I'm not sure where I'm going wrong, and I'd really appreciate any help. Here is my code:

import java.awt.event.*; 
import javax.swing.*; 

class text extends JFrame implements ActionListener { 
    public JTextField t;
    public text()
    { 
        // create a new frame to store text field and button 
        JFrame f = new JFrame("textfield"); 
  
        // create a label to display text 
        JLabel l = new JLabel("nothing entered"); 
  
        // create a new button 
        JButton b = new JButton("submit");
        b.addActionListener(this);
  
        // create a object of the text class 
        //text te = new text(); 
  
        // addActionListener to button 
        //b.addActionListener(te); 
  
        // create a object of JTextField with 16 columns and a given initial text 
        final JTextField t = new JTextField("",16); 
         
  
        // create a panel to add buttons and textfield 
        JPanel p = new JPanel(); 
        
        JTextField xa = new JTextField("", 16);
        xa.setText("A");
        //String s = t.getText();
        //char chars = s.charAt(0);
         String text=t.getText();
         if (text.equals("A")) {
            System.out.println("Hello");
         } 
      
  
        // add buttons and textfield to panel 
        p.add(t); 
        p.add(b); 
        p.add(l); 
  
        // add panel to frame 
        f.add(p); 
  
        // set the size of frame 
        f.setSize(300, 300); 
  
        f.show(); 
    } 

Aucun commentaire:

Enregistrer un commentaire