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);
}
}
请问为什么我将添加监听器的步骤从构造方法移到外面后程序就错了,我同学说类中只能定义方法,而不能直接调用方法,是不是啊?如果是的话,又是为什么呢?
直接不行,可以这样
{//加上方法块
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);
}
});
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。