当前位置: 技术问答>java相关
帮我看看这段代码吧
来源: 互联网 发布时间:2015-11-07
本文导语: import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class hf extends JFrame implements ActionListener {private JButton yes,no; private JTextField nameField,ff; private String pwd=""; private JPasswordField pwdField; p...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class hf extends JFrame implements ActionListener
{private JButton yes,no;
private JTextField nameField,ff;
private String pwd="";
private JPasswordField pwdField;
public hf()
{ setTitle("请选择访问方式");
setSize(300, 200);
setLocation(200,180);
setResizable(false);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{System.exit(0);
}
});
Container contentPane=getContentPane();
GridBagLayout gbl=new GridBagLayout();
contentPane.setLayout(gbl);
yes=new JButton("确定");
no=new JButton("退出");
JLabel name = new JLabel("用户名");
nameField=new JTextField("用户名",10);
JPasswordField pwdField=new JPasswordField(10);
JLabel password = new JLabel("密码");
ff=new JTextField(10);
GridBagConstraints gbc=new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
add(name,gbc,0,2,1,2);
add(password,gbc,0,4,1,2);
gbc.anchor = GridBagConstraints.WEST;
add(nameField,gbc,2,2,1,2);
add(pwdField,gbc,2,4,1,2);
add(ff,gbc,4,4,1,2);
gbc.anchor = GridBagConstraints.EAST;
add(yes,gbc,0,8,1,2);
gbc.anchor = GridBagConstraints.CENTER;
add(no,gbc,2,8,1,2);
yes.addActionListener(this);
no.addActionListener(this);
}
public void add(Component c,GridBagConstraints gbc,
int x,int y,int w,int h)
{ gbc.gridx=x;
gbc.gridy=y;
gbc.gridwidth=w;
gbc.gridheight=h;
getContentPane().add(c,gbc);
}
public void actionPerformed(ActionEvent evt)
{
Object source=evt.getSource();
if(source==yes)
{pwd=new String(pwdField.getPassword());
ff.setText(pwd);
}
else if(source==no)
{dispose();
}
}
public static void main(String[] args)
{Frame f=new hf();
f.show();
}
}
|
JPasswordField pwdField=new JPasswordField(10);这一句有问题,去掉JPasswordField 改为pwdField=new JPasswordField(10);即可,你把它变成局部变量了,而不是类成员。