textfield tableNum不会将String从另一个类传递到tableLabel [英] The textfield tableNum doesn't pass String into tableLabel from another class

查看:131
本文介绍了textfield tableNum不会将String从另一个类传递到tableLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从textfield(tableNum)获取输入并将其传递给另一个类的标签(tableLabel)。我不确定如何将值从文本字段精确传递给标签。
任何帮助将不胜感激。

I am trying to get the input from the textfield (tableNum) and pass it into a label (tableLabel) from another class. I am not sure how to exactly pass the value from the textfield to the label. Any help would be appreciated.

//从第一类中提取

num_Table = new JTextField();

num_Table.addKeyListener(new KeyAdapter() {
    @Override
        public void keyTyped(KeyEvent e) {                                  
             char c=e.getKeyChar();
            if(!(Character.isDigit(c) ||      (c==KeyEvent.VK_BACK_SPACE)||c==KeyEvent.VK_DELETE)){
            e.consume();                                                                        
            }
        }
});
num_Table.setBounds(334, 161, 83, 26);
contentPane.add(num_Table);
num_Table.setColumns(10);

num_TableSub_Btn = new JButton("Submit");
num_TableSub_Btn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        num_Table.setText("");
    }
});
num_TableSub_Btn.setBounds(487, 161, 83, 29);
contentPane.add(num_TableSub_Btn); 

//从第二类中提取

tableLabel = new JLabel("New label");
tableLabel.setBounds(16, 6, 61, 16);
contentPane.add(tableLabel);


推荐答案

传递 numTable 作为第二类构造函数的参数。添加 DocumentListener numTable ,而不是 KeyListener 。在 DocumentListener 中,调用 setText()更新标签。

Pass numTable as a parameter to the constructor of your second class. Add a DocumentListener to numTable, not a KeyListener. In your DocumentListener, call setText() to update the label.

numTable.addDocumentListener(new MyDocumentListener());
…
class MyDocumentListener implements DocumentListener {

    public void insertUpdate() {
        update();
    }
    public void removeUpdate() {
        update();
    }
    public void changedUpdate(DocumentEvent e) {}

    public void update() {
        tableLabel.setText(numTable.getText());
    }
}

这篇关于textfield tableNum不会将String从另一个类传递到tableLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆