如何从另一个类访问 textarea?

PNC*_*PNC 3 java awt jpanel jbutton jtextarea

主类:

public class tuna {
    public static void main(String[] args) {   
        JFrame frame1 = new JFrame();           
        frame1.setVisible(true);
        frame1.add(new apple());
        frame1.setSize(200  , 240);    
    }
}
Run Code Online (Sandbox Code Playgroud)

二级

public class apple extends JPanel{
    JTextArea ta = new JTextArea();
    Border blackline = BorderFactory.createLineBorder(Color.black); 
     apple(){
         setBorder(blackline);
         System.out.println("apple");
         ta.setText("hello");
         ta.setEditable(false);
         add(ta);
         add(new doctor());
         repaint();
         revalidate();      
    }
}
Run Code Online (Sandbox Code Playgroud)

三级

    public class doctor extends JPanel implements ActionListener{
    public JButton butt = new JButton("change");
    Border blackline = BorderFactory.createLineBorder(Color.black); 
    public doctor(){
        setBorder(blackline);
        add(butt);
    }   
    @Override
    public void actionPerformed(ActionEvent e){     
        if(e.getSource() == butt)
        {   
           System.out.println("she");
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

为什么每次按下按钮时它都不会在控制台中打印“她”。我需要我的程序在每次按下按钮时更改文本区域内的文本。例如,当我按下按钮时,它应该在文本区域中附加“world”,请帮助我!

Mad*_*mer 5

想想看,谁负责更新JTextAreaapple或者doctor

如果您回答,apple那么您是对的,apple应该保持对组件的控制并控制对它的访问。

在扩展中,doctor没有理由知道或关心apple或它可以做什么,它只需要能够向感兴趣的各方提供某些条件已更改的通知,它不应该关心其他类如何处理该信息,因为它超出了其一般责任范围。

这是观察者模式的一个经典示例,其中一个(或多个)感兴趣的一方观察另一方的变化并对其采取行动。

现在的问题是,如何最好地实现这一目标?有许多解决方案,您可以推出自己的侦听器interface,也可以使用预先存在的侦听器,例如,ChangeListener或者您可以使用组件提供的内置功能。您选择哪个取决于您的要求,为简单起见,我使用的是最后一个...

当您创建 的实例时doctor,您可以向其添加一个PropertyChangeListener...

doctor doc = new doctor();
doc.addPropertyChangeListener("change", new PropertyChangeListener() {
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        Object newValue = evt.getNewValue();
        if (newValue instanceof String) {
            ta.setText(newValue.toString());
        } else if (newValue == null) {
            ta.setText(null);
        }
    }
});
add(doc);
Run Code Online (Sandbox Code Playgroud)

在你的butt ActionListener,你会触发一个PropertyChangeEvent......

@Override
public void actionPerformed(ActionEvent e){     
    if(e.getSource() == butt)
    {   
        // If you want to, you could pass the "old" value
        firePropertyChange("change", null, "she");
    }
}
Run Code Online (Sandbox Code Playgroud)

作为一个可能的例子......