java类中方法调用问题-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

java类中方法调用问题

蛮大人123 2016-03-12 17:16:03 1433
public class TestTextComponent extends JFrame {
private JTextField textField = new JTextField(15);
private JPasswordField passwordField = new JPasswordField(15);
private JTextArea textArea = new JTextArea(6, 32);
private final static String newline = "\n";
textField.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
textArea.append("用户输入文本是:" + textField.getText() + newline);
textField.setText(null);
}
});passwordField.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    {
        String password = new String(passwordField.getPassword());
        textArea.append("用户输入的密码是:" + password + newline);
        passwordField.setText(null);
    }
});


public TestTextComponent()
{
    /*setLayout(new BorderLayout());
    textArea.setEditable(false);
    textField.setToolTipText("接收文本输入");
    passwordField.setToolTipText("接收密码输入");
    JPanel northPanel = new JPanel();
    northPanel.setLayout(new FlowLayout());
    northPanel.add(textField);
    northPanel.add(passwordField);
    add(northPanel, BorderLayout.NORTH);
    */
    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new FlowLayout());
    centerPanel.add(new JScrollPane(textArea));
    add(centerPanel, BorderLayout.CENTER);
}
public static void main(String[] args)
{
    TestTextComponent frame = new TestTextComponent();
    frame.setTitle("测试文本组件");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}
}

请问为什么我将添加监听器的步骤从构造方法移到外面后程序就错了,我同学说类中只能定义方法,而不能直接调用方法,是不是啊?如果是的话,又是为什么呢?

java方法调用 方法调用问题 java方法调用问题
分享到
取消 提交回答
全部回答(1)
  • 蛮大人123
    2019-07-17 19:01:14

    直接不行,可以这样

     {//加上方法块
     textField.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
    {
    textArea.append("用户输入文本是:" + textField.getText() + newline);
    textField.setText(null);
    }
    });
    passwordField.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e)
        {
            String password = new String(passwordField.getPassword());
            textArea.append("用户输入的密码是:" + password + newline);
            passwordField.setText(null);
        }
    });
     }
    0 0
+ 订阅

云安全开发者的大本营

相似问题
最新问题