【问题标题】:JAVA: get String value from Class1 and call to the other Class2JAVA:从 Class 1 获取 String 值并调用另一个 Class 2
【发布时间】:2015-11-11 12:35:47
【问题描述】:

我正在尝试将该名称字符串从 LoginForm 获取到 MainForm,因此我现在可能是使用其名称登录的用户。我的问题是,我无法将从 LoginForm 类中的数据库中检索到的名称传递给 MainForm。

如果我执行这段代码,为什么会这样;

public class LoginForm extends JFrame{
    ...
    .
    public LoginForm(){
       ...
       .
       MainForm thisoh = new MainForm();
       thisoh.getthisnow(rs.getString("Given_Name"));
       ...
       .
    }
}

然后,在另一个班级;

public class MainForm extends JFrame {
   private String fname;
       String getthisnow(String usrname) {
          this.fname = usrname;
          return fname;
          }
       public MainForm() {
          initComponents();
          txt_HomeWelcome.setText(fname);//JLabel
          ...
          .
       }
}

JLabel 变成 null.. :-( 它应该显示 LoginForm 中的名称,对吗?我错过了什么吗?请帮忙!>.fname。那就是我的问题。

【问题讨论】:

  • 有什么问题?
  • 执行:rs.getString("Given_Name");给出错误或什么?或者你是什么意思?
  • 如果您尝试在新的MainForm() 上将标签设置为Jlabel.setText(user),您不应该为MainForm 分配一个变量吗? myForm = new MainForm(),myForm.setVisible(true),然后是myForm.setText(user)?
  • 如果“Given_Name”是列名,可以。实际上,这就是您读取 resultSet 对象的方式。 Here is 更详细的答案。但是,如果您尝试使用结果集按用户名过滤,我认为这是不可能的。另外,请更清楚您要实现的目标以及您遇到的错误。
  • 当您说“系统”时,您的意思是像 Windows 吗?还是您自己的解决方案?

标签: java


【解决方案1】:

您需要在这里做的是将您的用户名传递给您的主窗体并将值设置为某处的标签。

new MainForm(rs.getString("Given_name")).setVisible(true);

然后在主窗体中

public class MainForm extends JFrame {
    private String username;
    public MainForm(String username){
        this.username = username;

        //you set the value of your label to username
        // here or somewhere else in your form
         mLabel.setText(username);
    }
}

【讨论】:

  • 这一行出现错误:new MainForm(rs.getStrin("Given_name")).setVisible(true);
  • 修正错字。应该是 getString
  • 是的,我认出了它...但仍然错误...我认为 resultSet 的事情...我设法制作另一个 ResultSet 但仍然错误...呃*!
  • 确保 Given_name 是您数据库中的一个非空列,并且拼写方式与您在 getString() 中传递它的方式完全相同。如果还是不行。它表明您的 SQL 查询而不是您的 Swing 逻辑中存在问题
  • 我添加了您的答案以获得它的结果...请参阅。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-21
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
相关资源
最近更新 更多