简体   繁体   中英

How do I set the TextField's value

My simple question is that why isn't It working? It's got problem with tf1.getText(), but I don't get It why. So what I Want is, that I have a button and when I write a text in tf1 and then push the button tf2 will output the same text with some modification. Or do I need an another Listener that sets tf1 and if so how should I implement It? Thank you!

public class CaesarFrame extends JFrame{
    JTextField tf1;
    JTextField tf2;
    JButton jb;
    JComboBox box;
    JLabel label;
    JPanel j1;
    JPanel j2;
    
    class OkButtonActionListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            String k= tf1.getText();          //HERE IS THE PROBLEM
            caesarCode c=new caesarCode(k);
            tf2.setText(c.get());
        }
    }
    
    public CaesarFrame() {
        JFrame frame=new JFrame("Swinglab");
        frame.setPreferredSize(new Dimension(400,110));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        String[] characters=new String[26];
        for(int i=65;i<91;i++)//COMBOBOX->
            characters[i-65]=String.valueOf((char)i);
        JComboBox box = new JComboBox(characters);
        JTextField  tf1=new JTextField("",20);
        JTextField  tf2=new JTextField("",20);
        JButton jb=new JButton("Code!");
        ActionListener listen=new OkButtonActionListener();       //ACTIONLISTENER
        jb.addActionListener(listen);
        JLabel label= new JLabel("Output: ");
        JPanel j1=new JPanel();
        JPanel j2=new JPanel();
        j1.add(box);//ITT IS LEEBTNE LAYOUTOT ADNI
        j1.add(tf1);
        j1.add(jb);
        j2.add(label);
        j2.add(tf2);
        tf2.setEditable(false);
        frame.add(j1,BorderLayout.NORTH);
        frame.add(j2,BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }
}

As Stultuske said in a comment, you are redeclaring the global fields tf1 and tf2 in your constructor. This means the tf1 you see on your JPanel lives only in your constructor method and is not the same as the global tf1 field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM