无法使此方法起作用

时间:2015-11-27 17:22:02

标签: java

一旦我添加actionPerformed方法,我有问题让这个小程序工作......有什么建议吗?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class JGreet3 extends JApplet implements ActionListener
{

   public void init()
   {
      Container con = getContentPane();
      JLabel greeting = new JLabel("Greetings!");
      Font bigFont = new Font("Times Roman", Font.ITALIC, 24);
      greeting.setFont(bigFont);

      JLabel firstLabel = new JLabel("Please enter your first name:");
      JLabel lastLabel = new JLabel("Please enter your last name:");
      JTextField firstField = new JTextField("", 10);
      JTextField lastField = new JTextField("", 10);
      JButton viewButton = new JButton("View Greeting");

      viewButton.addActionListener(this);

      FlowLayout flow = new FlowLayout();
      con.setLayout(flow);
      con.add(firstLabel);
      con.add(firstField);
      con.add(lastLabel);
      con.add(lastField);
      con.add(viewButton);

      firstField.requestFocus();

      con.add(greeting);

   }

   public void actionPerformed(ActionEvent thisEvent)
   {
      String firstName = firstField.getText();
      String lastName = lastField.getText();
      greeting.setText("How are you, " + firstName + " " + lastName + "?");
   }

}

我得到的错误是找不到firstField.getText,lastField.getText和greeting.setText的符号。

1 个答案:

答案 0 :(得分:1)

您需要将它们设为成员变量。成员变量可访问所有类方法:

public class JGreet3 extends JApplet implements ActionListener {

    JLabel greeting;
    JTextField firstField;
    JTextField lastField;

    public void init() {
        greeting = new JLabel("Greetings!");
        firstField = new JTextField("", 10);
        lastField = new JTextField("", 10);

        ....
    }

    ...

    public void actionPerformed(ActionEvent thisEvent) {
        // Now your textFields are accessible
        String firstName = firstField.getText();
        String lastName = lastField.getText();
        greeting.setText("How are you, " + firstName + " " + lastName + "?");
    }

}