import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
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);
}
});
}
代码必须写在方法内,不能直接写在类的定义里面。
类中可以调用方法,如果这个方法是静态的,可以直接 类名.方法名()或者对象.方法名(),你自己可以再写一个类,里面写一个 静态方法(不需要主方法),然后在另一个类中调用,需要导包,或者它们在同一个包下的话,不用导,实践出真知,立马可以推翻你同学的理论,如果这个方法不是静态的,就必须创建对象,再去调用,
不知道我们说的俄是不是同一个问题,还有构造方法是用来初始化数据的