【要点】
Box的布局;
窗体的居中;
登陆完成后dispose方法关闭窗体;
import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import com.kx.Adapter.*; import com.kx.SetupGUI.AppMainFrame; public class LoginMainFrame extends JFrame { private static final long serialVersionUID = 1L; private final static int HEIGHT=150; private final static int WIDTH=250; private String inUsername,inPassword; public LoginMainFrame(){ setTitle("登陆窗口");//同super("登录窗口") this.setResizable(false);//也可以不用this,以后都不用 SetupUI(); MyWindowAdapter mwa=new MyWindowAdapter(); addWindowListener(mwa); //指的是super或者LoginMainFrame Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize(); setLocation(screenSize.width/2-WIDTH/2, screenSize.height/2-HEIGHT/2); setSize(WIDTH, HEIGHT); } public void SetupUI(){ //Pane:镶板;ContentPane:内容镶板 Container container=getContentPane(); //JFrame.getContentPane(); //container.setLayout(new GridLayout()); container.setLayout(new FlowLayout()); Box hor1=Box.createHorizontalBox(); Box hor2=Box.createHorizontalBox(); Box hor3=Box.createHorizontalBox(); Box hor4=Box.createHorizontalBox(); Box hor5=Box.createHorizontalBox(); Box ver1=Box.createVerticalBox(); Box ver2=Box.createVerticalBox(); JLabel lblTitle=new JLabel("登陆窗口"); lblTitle.setFont(new Font("",Font.BOLD,18)); container.add(hor1); hor1.add(lblTitle); JLabel lblUserID=new JLabel("登录名:"); final JTextField txtUserID=new JTextField(); hor2.add(lblUserID); hor2.add(txtUserID); hor2.setSize(300, 80); JLabel lblPassword=new JLabel("密 码:"); final JPasswordField txtPassword=new JPasswordField(); hor3.add(lblPassword); hor3.add(txtPassword); hor3.setSize(300, 80); JButton btnSubmit=new JButton("确认"); btnSubmit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("确认"); inUsername=txtUserID.getText(); inPassword=txtPassword.getText(); LoginCheck(inUsername,inPassword); } }); JButton btnClear=new JButton("清空"); btnClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.print("清空"); txtUserID.setText(""); txtPassword.setText(""); } }); hor4.add(btnSubmit); hor4.add(btnClear); ver1.add(hor1); ver1.add(hor2); ver1.add(hor3); ver1.add(hor4); container.add(ver1); } public void LoginCheck(String UserID,String Password){ if(UserID.equals("")||UserID==null){ JOptionPane.showMessageDialog(null,"没有输入用户名。","登陆系统:提示",JOptionPane.ERROR_MESSAGE); } else if(Password.equals("")||Password==null){ JOptionPane.showMessageDialog(null,"没有输入密码。","登陆系统:提示",JOptionPane.ERROR_MESSAGE); } else if(UserID.equals("admin")&&Password.equals("admin")){ System.out.print("成功"); AppMainFrame amf= new AppMainFrame(); amf.F.setVisible(true); this.dispose(); //用于登陆后关闭。 } } public static void main(String[] args) { LoginMainFrame lmf=new LoginMainFrame(); lmf.setVisible(true); } }