package test;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class swing_sample extends JFrame
{
//declaring our swing components
JLabel l_name,l_pass;
JFrame e;
JTextField t_name;
JPasswordField t_pass; //A special JTextField but hides input text
JButton button;
Container c;
//a inner class to handling ActionEvents
public handler2 handle;
//a separate class for processing database connection and authentication
database db;
private JLabel lblNewLabel;
swing_sample()
{
super("Login form");
c=getContentPane();
//extra classes
db=new database();
handle =new handler2();
//swing components
l_name=new JLabel("Username");
l_name.setBounds(189, 69, 153, 45);
l_pass=new JLabel("Password");
l_pass.setBounds(189, 151, 126, 36);
t_name=new JTextField(10);
t_name.setBounds(321, 75, 126, 33);
t_pass=new JPasswordField(10);
t_pass.setBounds(321, 147, 126, 40);
button=new JButton("Login");
Image img50=new ImageIcon(this.getClass().getResource("/aaaa.png")).getImage();
button.setIcon(new ImageIcon(img50));
button.setBounds(262, 239, 137, 53);
//adding actionlistener to the button
button.addActionListener(handle);
getContentPane().setLayout(null);
//add to contaienr
c.add(l_name);
c.add(t_name);
c.add(l_pass);
c.add(t_pass);
c.add(button);
lblNewLabel = new JLabel("");
Image img40=new ImageIcon(this.getClass().getResource("/aaaaa.png")).getImage();
lblNewLabel.setIcon(new ImageIcon(img40));
lblNewLabel.setBounds(10, 75, 169, 137);
getContentPane().add(lblNewLabel);
//visual
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(631,412);
}
public static void main(String args[])
{
swing_sample sample=new swing_sample();
}
//an inner class .You can also write as a separate class
class handler2 implements ActionListener
{
//must implement method
//This is triggered whenever the user clicks the login button
public void actionPerformed(ActionEvent ae)
{
//checks if the button clicked
if(ae.getSource()==button)
{
char[] temp_pwd=t_pass.getPassword();
String pwd=null;
pwd=String.copyValueOf(temp_pwd);
System.out.println("Username,Pwd:"+t_name.getText()+","+pwd);
//The entered username and password are sent via "checkLogin()" which return boolean
if(db.checkLogin(t_name.getText(), pwd))
{
//a pop-up box
JOptionPane.showMessageDialog(null, "You have logged in successfully","Success",
JOptionPane.INFORMATION_MESSAGE);
}
else
{
//a pop-up box
JOptionPane.showMessageDialog(null, "Login failed!","Failed!!",
JOptionPane.ERROR_MESSAGE);
}
}//if
}//method
}//inner class
}//class
这是我忘记密码的Java应用程序,它还有一个主要工作的数据库类,只想问一下如何使按钮识别输入键输入,一旦识别,它就会执行动作块。