gpt4 book ai didi

java - 运行 swing.Jframe 类中声明的方法

转载 作者:行者123 更新时间:2023-12-01 10:41:23 25 4
gpt4 key购买 nike

我创建了两个 swing.JFrame。登录 GUI 和用户 GUI。我想要的是,当它切换到登录gui到用户gui时,用户GUI中有一个Jlabel,需要更改为("you'relogin as"+ username);

我在userjframe源代码中尝试了这段代码。

`loggedInAsLable.setText("you're logged in as" + username);` 

在一个方法中,并在用户jframe的主方法中调用。但由于某些原因它不起作用。

当 Jframe 变得可见时,如何运行某些方法?

public class CustomerServiceOfficerUI extends javax.swing.JFrame {

private static Statement st;
ResultSet rs;
Connection con = null;
Login loginUI = new Login(); // gets current user Id
Employee cso = new CustomerServiceOfficer(); //creates new customer service officer object

/**
* Creates new form CustomerServiceOfficer
*/
public CustomerServiceOfficerUI() {
initComponents();
}

public void getCSOdetails() {

try {
Class.forName("com.mysql.jdbc.Driver");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/flyingcarsdb", "root", "");
System.out.println("database connected");

} catch (ClassNotFoundException | SQLException ex) {
System.out.println("Error: " + ex);
}

try {
// Retrieve customer service officer details
st = con.createStatement();
String query = "select * FROM customerserviceofficer WHERE Id = '" + loginUI.getCurrentUserId() + "'";

rs = st.executeQuery(query);

while (rs.next()) {
//Assign the details with setters
cso.setFname(rs.getString("Fname"));
cso.setEmail(rs.getString("Email"));
}

} catch (Exception ex) {
System.out.println("Error : " + ex);
}
loggedInAsLable.setText("you're logged in as : " + cso.getId());
//this is where LABLE is changed, 'cso.getId()' returns the user ID
}

最佳答案

如果您确实需要在 JFrame 可见时更新它(如您的最后一条语句所示),您可以使用 WindowListener 来调用 getCSODetails() 方法。

public CustomerServiceOfficerUI() {
initComponents();
this.addWindowListener(new WindowAdapter() {

@Override
public void windowOpened(WindowEvent e)
{
this.getCSODetails();
}

@Override
public void windowDeiconified(WindowEvent e)
{
this.getCSODetails();
}

@Override
public void windowActivated(WindowEvent e)
{
this.getCSODetails();
}

});
}

我包含了三个激活事件 - 打开、激活和去邮件化;您可以删除其中任何一个,以将更新限制为适合您需要的特定事件。如果您只需要在窗口打开后更新标签,请删除 windowDeiconified()windowActivated() 方法。但请注意,getCSODetails() 方法的设计非常糟糕,只要窗口变得可见/聚焦就调用它,这会导致性能损失,并且 GUI 的响应能力将严重受到数据库性能的影响。我猜想您显示的客户详细信息在登录 session 期间不会更改,因此更合适的做法是执行一次查询,缓存详细信息,然后从缓存中显示它们。

关于java - 运行 swing.Jframe 类中声明的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34392159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com