开发者社区> 问答> 正文

java类中方法调用问题

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);
}
}

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

展开
收起
蛮大人123 2016-03-12 17:16:03 2142 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    直接不行,可以这样

     {//加上方法块
     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);
        }
    });
     }
    2019-07-17 19:01:14
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载