java 变量预备问题

来源:百度知道 编辑:UC知道 时间:2024/06/08 14:18:57
这是程序中的一部分代码

class PasswordChooser extends JPanel
{
public PasswordChooser()
{
setLayout(new BorderLayout());

// construct a panel with user name and password fields

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 2));
panel.add(new JLabel("User name:"));
panel.add(username = new JTextField(""));
panel.add(new JLabel("Password:"));
panel.add(password = new JPasswordField(""));
add(panel, BorderLayout.CENTER);

// create Ok and Cancel buttons that terminate the dialog

okButton = new JButton("Ok"); 123123
okButton.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
ok = true;
dialo

因为Java的执行过程已经定义了,先是类的成员变量->类的构造函数.
因为你的okbutton是成员变量,所以先准备了,而你的cancelbutton是在构造函数里面,所以没有提前准备,如果你把cancelbutton定义成成员变量,就会先准备.