如何从一个类检索信息到另一个类

时间:2012-03-14 19:15:07

标签: java extend

我有以下代码从同一个类的文本框中检索信息

btnAddItem.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {

         String tabno = textArea_TableNo.getText();
         String name = textArea_Name.getText();
         String size = textArea_size.getText();
         String quan = textArea_quantity.getText();
         String price = textArea_price.getText();
         textArea.append(tabno + ",    " + name + ",    " + size + ",    " + quan + ",    " + price + "\n");

但我不确定如何在两个类之间完成相同的操作。我可能必须“扩展”我的类,但我已经将类扩展到我的数据库类。我只是不确定我能做到这一点。任何建议让我理解这一点将不胜感激..

1 个答案:

答案 0 :(得分:0)

好吧,你可以有一个公共方法来检索文本,并在另一个类上使用它。例如:

class Class1 {
  private JTextArea textOne;

  //... declare other fields, build GUI, etc

  public String getTextOneText() {
    return textOne.getText();
  }
}

class Class2 {
  private JTextArea textTwo;
  private Class1 class1;
  public Class2( Class1 class1 ) {
    this.class1 = class1; //store reference to class1.
  }
  //use the getData method to append text from the Class1.
  void getData() {
    textTwo.append( class1.getTextOneText() )
  }
}

在此示例中,将Class1实例的引用存储在Class2并使用getData方法应该可以执行您想要的操作。

另一种方法是使用Observer Design Pattern在类之间进行通信。

相关问题