我无法弄清楚如何调用已在Welcome.Java(也是JFrame)中的Login.Java(是一个JFrame)中实现的类
这是我在Login.Java中调用的类。
public class Session {
public Session(String sUsername, String sPassword, String sName, String sAge, String sSex)
{
String Username = sUser;
String Password = sPassword;
String Name = sName;
String Age = sAge;
String Sex = sSex;
}
}
这是实现该类的Login.Java代码。
if(rs.next()) {
Username=rs.getString("Usernames");
Password=rs.getString("Passwords");
Name=rs.getString("Names");
Age=rs.getString("Ages");
Sex=rs.getString("Sexes");
Session S1 = new Session(Username, Password, Name, Age, Sex);
}
在Welcome.Java中,我想像这样调用S1。
S1.Name
或
S1.Username
答案 0 :(得分:0)
如果S1 Session类实例是Login(扩展JFrame)类的私有成员,则没有常规方法可以从Login类外部访问S1成员。您需要使用公共访问器方法(setter和getter)。
如果要从Welcome类访问Login的S1对象,则需要传递对Welcome构造函数的引用,和/或Login的S1成员需要具有公共可见性。
Welcome welcome = new Welcome(login.getS1())
答案 1 :(得分:0)
请记住,组织这样的代码(Subclassing JFrame,公共字段而不是Session类中的getter)在java中被认为是不好的做法。这是最简单的工作示例。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
final Wellcome app = new Wellcome();
app.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
app.setVisible(true);
});
}
}
class Wellcome extends JFrame {
public Wellcome() throws HeadlessException {
setSize(300, 300);
final JButton loginBtn = new JButton();
loginBtn.setAction(new AbstractAction("Login") {
@Override
public void actionPerformed(ActionEvent e) {
final Login login = new Login();
final Session session = login.logIn();
// use you session as you wish
System.out.println(session.username);
}
});
final JPanel contentPane = new JPanel();
contentPane.add(loginBtn);
setContentPane(contentPane);
}
};
class Login extends JDialog {
private final JTextField username;
private final JTextField password;
private final JTextField age;
public Login() {
setModalityType(ModalityType.APPLICATION_MODAL);
setLayout(new GridLayout(5, 2));
username = addField("User", new JTextField());
password = addField("Password", new JPasswordField());
age = addField("Age", new JTextField());
pack();
}
private JTextField addField(String name, JTextField field) {
add(new JLabel(name));
add(field);
return field;
}
public Session logIn() {
setVisible(true);
return new Session(username.getText(), password.getText(), age.getText());
}
};
class Session {
public final String username;
public final String password;
public final String age;
public Session(String username, String password, String age) {
this.username = username;
this.password = password;
this.age = age;
}
}