这段代码好奇怪。
1.它能编译通过。
2.但是这一段有点奇怪
if((psw1==psw2))
{
JOptionPane.showMessageDialog(frame, "alert");
System.out.println(psw1);
}
什么问题呢?
1.不论psw1==psw2是否成立,shouwMessageDialog 永远没有执行(或许执行了,但没弹出对话框).我试过把 if()去了,或把 showMessageDialog 放到 Main()里,打还是没反应。
2.不论psw1==psw2是否成立,、System.out.println(psw1);都会被执行。。
这是怎么回事?是bug吗?还是我犯了其他 隐秘的错误?
欲知真相,
敬请关注以下源码。
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class winReg implements ActionListener{
private JFrame frame = new JFrame("register");
private Container c = frame.getContentPane();
private JTextField username = new JTextField();
private JPasswordField password = new JPasswordField();
private JPasswordField password2= new JPasswordField();
private JButton confirm = new JButton("confirm");
private JButton cancel = new JButton("cancel");
public winReg(){
frame.setSize(600,400);
c.setLayout(new BorderLayout());
initFrame();
confirm.addActionListener(this);
cancel.addActionListener(this);
frame.setVisible(true);
}
private void initFrame() {
//顶部
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.add(new JLabel("new register"));
c.add(titlePanel,"North");
//中部表单
JPanel fieldPanel = new JPanel();
fieldPanel.setLayout(null);
JLabel l1 = new JLabel("user name:");
l1.setBounds(50, 20, 50, 20);
JLabel l2 = new JLabel("password:");
JLabel l3 = new JLabel("confirm password:");
l2.setBounds(50, 60, 100, 20);
l3.setBounds(50, 90, 150, 20);
fieldPanel.add(l1);
fieldPanel.add(l2);
fieldPanel.add(l3);
username.setBounds(230,20,120,20);
password.setBounds(230,60,120,20);
password2.setBounds(230,90,120,20);
fieldPanel.add(username);
fieldPanel.add(password);
fieldPanel.add(password2);
c.add(fieldPanel,"Center");
//底部按钮
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(confirm);
buttonPanel.add(cancel);
c.add(buttonPanel,"South");
}
public static void main(String[] args){
JOptionPane.showMessageDialog(frame, "alert", "alert", JOptionPane.ERROR_MESSAGE);
new winReg();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if((e.getSource()==confirm)){
String usn=username.getText();
String psw1=password.getPassword();
String psw2=password.getPassword();
//check wether psw same
if((psw1==psw2))
{
JOptionPane.showMessageDialog(frame, "alert");
System.out.println(psw1);
}
}
}
}