-1
我在eclipse上使用swing進行java庫管理項目。當我點擊登錄按鈕時沒有任何反應。 mysql jdbc驅動程序已加載,我正在獲取連接,但沒有出現標籤。請告訴我應該怎麼做。這是我的代碼。如何讓JFrame登錄表單工作?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class Loginscreen implements ActionListener {
JFrame logframe;
JButton bt;
JLabel lid, lpass, lmsg;
JTextField tid;
JPasswordField pass;
JPanel p1;
Font ft, ft2;
Connection conn;
public Loginscreen() {
logframe = new JFrame("Login");
logframe.setSize(1366, 720);
logframe.setVisible(true);
lid = new JLabel("User ID");
lpass = new JLabel("Password");
lmsg = new JLabel();
ft = new Font("Arial", Font.BOLD, 30);
ft2 = new Font("Arial", Font.PLAIN, 20);
tid = new JTextField();
pass = new JPasswordField();
p1 = new JPanel();
bt = new JButton("Login");
logframe.add(p1);
p1.setLayout(null);
p1.setBackground(new Color(160, 82, 45));//Background Color Set
lid.setBounds(450, 200, 500, 30);
p1.add(lid);
lid.setFont(ft);
tid.setBounds(650, 200, 200, 30);
p1.add(tid);
tid.setFont(ft2);
lpass.setBounds(450, 300, 500, 30);
p1.add(lpass);
lpass.setFont(ft);
pass.setBounds(650, 300, 200, 30);
p1.add(pass);
bt.setBounds(600, 430, 100, 50);
p1.add(bt);
bt.setFont(new Font("Segoe Script", Font.BOLD, 22));
bt.setBackground(new Color(173, 216, 230));
lmsg.setBounds(450, 510, 500, 30);
p1.add(lmsg);
bt.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == bt) {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_lib", "root", "admin");
String i = tid.getText();//get the user id
char[] pwd = pass.getPassword();//get the password
String spwd = new String(pwd);//converting char to string
String query = "select * from tbl_user where id=? and password=?";
PreparedStatement p = conn.prepareStatement(query);
p.setString(1, i);
p.setString(2, spwd);
ResultSet rs = p.executeQuery();
int count = 0;
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
lmsg.setText("Invalid User ID or Password");
} else {
lmsg.setText("Invalid User ID or Password");
}
rs.close();
conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
}
只需要注意,在添加所有組件之前,不應該使框架可見。 – Berger
你能打印你的'spwd'和'i'嗎? –
你的程序適合我 –