主类:
public class tuna {
public static void main(String[] args) {
JFrame frame1 = new JFrame();
frame1.setVisible(true);
frame1.add(new apple());
frame1.setSize(200 , 240);
}
}
二等
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();
}
}
三等
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");
}
}
}
为什么每次按下按钮时,它都不会在控制台中打印“she”。 我需要我的程序在每次按下按钮时更改文本区域内的文本。 例如,当我按下按钮时,它应该在文本区域中附加“world”,请帮助我!
最佳答案
想一想,谁负责更新JTextArea
,apple
还是doctor
?
如果您的答案是apple
,那么您是对的,apple
应该保持对组件的控制并控制对其的访问。
扩展而言,doctor
没有理由了解或关心 apple
或它能做什么,它只需要能够向感兴趣的各方提供某些条件的通知已更改,它不应该关心其他类如何处理该信息,因为它超出了其一般责任的范围。
这是 Observer Pattern 的经典示例,其中一个(或多个)相关方观察另一方的变化并对其采取行动。
现在的问题是,如何最好地实现这一目标?有很多解决方案,您可以滚动自己的监听器接口(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);
在你的屁股
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");
}
}
作为一个可能的例子......
关于java - 如何从另一个类访问文本区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27341557/