简体   繁体   English

如何设置 TextField 的值

[英]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. tf1.getText() 有问题,但我不明白为什么。 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.所以我想要的是,我有一个按钮,当我在 tf1 中写入文本然后按下按钮 tf2 将输出相同的文本并进行一些修改。 Or do I need an another Listener that sets tf1 and if so how should I implement It?或者我是否需要另一个设置 tf1 的侦听器,如果需要,我应该如何实现它? 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.正如 Stultuske 在评论中所说,您正在构造函数中重新声明全局字段 tf1 和 tf2 。 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.这意味着您在 JPanel 上看到的 tf1 仅存在于您的构造函数方法中,与全局 tf1 字段不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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