[英]Is there a way to implement classes from a file into a new file?
I have a program that is an extremely basic login: 我有一个非常基本的登录程序:
import javax.swing.JOptionPane.*;
import java.lang.Math.*;
import java.lang.System.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.JFrame;
public class UserLog extends JFrame
{
public static void main(String[]Args) throws InterruptedException
{
boolean isValid=false;
while(!isValid)
{
// Components related to "login" field
JLabel label_loginname = new JLabel("Enter your login name:");
JTextField loginname = new JTextField(15);
// loginname.setText("EnterLoginNameHere");
// Pre-set some text
// Components related to "password" field
JLabel label_password = new JLabel("Enter your password:");
JPasswordField password = new JPasswordField();
// password.setEchoChar('@');
// Sets @ as masking character
// password.setEchoChar('\000');
// Turns off masking
JCheckBox rememberCB = new JCheckBox("Remember me");
Object[] array = {label_loginname,
loginname,
label_password,
password,
rememberCB};
Object[] options = {"Login", "Cancel"};
int res = JOptionPane.showOptionDialog(null,
array,
"Login",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //do not use a custom Icon
options, //the titles of buttons
options[0]); //default button title
// User hit Login
if (res == 0)
{
System.out.println( "Login" );
}
// User hit CANCEL
if (res == 1)
{
System.out.println( "Canceled" );
}
// User closed the window without hitting any button
if (res == JOptionPane.CLOSED_OPTION)
{
System.out.println( "CLOSED_OPTION" );
}
// Output data in "login" field, if any
String newloginname = loginname.getText();
String newpassword = new String(password.getPassword());
if (newloginname.equalsIgnoreCase("Cody_Coulter") && newpassword.equals("cheche1"))
{
System.out.println("Login Successful!");
boolean selectedCB = rememberCB.isSelected();
System.out.println( "selectedCB: " + selectedCB );
Thread.sleep(3000);
Object[] array1= {"It's about time to choose"};
Object[] options1= {"Leave", "Keep Going"};
int res1 = JOptionPane.showOptionDialog(null,
array1,
"There",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //do not use a custom Icon
options1, //the titles of buttons
options1[0]); //default button title
if(res1==1)
{
Object[] options2 = {"Answers for Algebra",
"Answers for APUSH",
"Answers for Computer Science"};
Object[] array2={"Pick Your Poison:"};
int res2= JOptionPane.showOptionDialog(null,
array2,
"This",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //do not use a custom Icon
options2, //the titles of buttons
options2[0]); //default button title
if (res2 == 0)
{
JOptionPane.showMessageDialog(null, "Nigguh you a cheatuh" );
}
else
if (res2 == 1)
{
JOptionPane.showMessageDialog(null, "Nigguh, who's dumb enough to need to cheat in APUSH" );
}
else
if (res2 == 2)
{
JOptionPane.showMessageDialog(null, "Nigguh, you dumb" );
}
String name1 = JOptionPane.showInputDialog(null,
"What is your name?");
int length = 0;
length = newpassword.length();
String Pass = "*";
newpassword =newpassword.replaceAll(".","*");
System.out.println("Username: "+newloginname+"\nPassword: "+
newpassword+"\nName: "+name1);
}
}
else {
JOptionPane.showMessageDialog(null,"Wrong Username or Password!");
isValid=false;
}
}
// Output data in "password" field, if any
// Output state of "remember me" check box
}
}
What I want to do is create another program, such as a fileshare, file access, or even a basic game but be able to have this login implemented in order to, of course, login. 我想做的是创建另一个程序,例如文件共享,文件访问,甚至是基本游戏,但能够实现此登录,以便登录。 Is there a way to implement this code without having to copy and paste into another code as a separate class within that file?
有没有一种方法可以实现此代码,而不必复制并粘贴到该文件中作为单独类的另一个代码中? Example:
例:
public class NewGame{
public static void main(String[] args)
{
new UserLog();
}
of course this may not be syntactually correct, but that's the gist of it. 当然,这在语法上可能并不正确,但这就是要点。
Thank you, and if I need to rephrase it or edit the question/format, let me know! 谢谢,如果我需要改写或修改问题/格式,请告诉我! :)
:)
EDIT After making the current main method a regular public class, and call from the newly public class, by the new main 编辑将当前main方法设置为常规公共类,并由新main从新公共类调用
public class gameLogin
{
public static void main(String[]args)
{
userLogin();
}
public class userLogin()
{
// current code, evidently seen in the current main
}
// rest of code
So in order to reference to the original file, userLog, I would have to (in the new file: gameLogin) use userLog(); 因此,为了引用原始文件userLog,我必须(在新文件中:gameLogin)使用userLog();。
or would it be better to use 还是更好用
userLog.userLogin("Munkeeface", "password");
The simplest method would be to simply move all code from your main
into a static utility-class function, and then call that function from your other classes main
s. 最简单的方法是将所有代码从您的
main
移至静态实用程序类函数,然后从其他类main
调用该函数。 For example: 例如:
public class LoginToWebsiteUtil {
public static final void login(String username, String password, ...) {
//CODE GOES HERE
}
}
And use it with: 并用于:
public class LoginToMyWebsite {
public static final void main(String[] ignored) {
LoginToWebsiteUtil.login("myname", "password", ...)
}
}
The only tricky thing will be answering the question: "what variables save state?" 唯一棘手的事情是回答这个问题:“哪些变量保存状态?” Those variables must be declared as static class fields in the utility class.
这些变量必须在实用程序类中声明为静态类字段。 This is because, as soon as the function ends, all state, such as the login-connection, will be terminated.
这是因为,一旦功能结束,所有状态(例如登录连接)将被终止。 In order to keep it around ("hold its state"), these state variables need to have a larger scope than just the lifetime of the function.
为了保持状态不变(“保持其状态”),这些状态变量需要具有比函数的生存期更大的作用域。
For example, instead of 例如,代替
public class LoginToWebsiteUtil {
public static final void login(String username, String password, ...) {
Connection conn = getConnectionFromLogin(username, password);
//and so on...
It will have to be 它必须是
public class LoginToWebsiteUtil {
private static Connection conn = null;
public static final void login(String username, String password, ...) {
conn = getConnectionFromLogin(username, password);
//and so on...
Alternatively, you could put all the code from your original main
function into the constructor of a new class, such as 另外,您也可以将原始
main
函数中的所有代码放入新类的构造函数中,例如
public class UserLogin {
private static Connection conn = null;
public UserLog(String username, String password, ...) {
conn = getConnectionFromLogin(username, password);
//CODE HERE
}
}
But, as you can see, you still have the "what holds state?" 但是,正如您所看到的,您仍然拥有“什么保持状态?” issue.
问题。
(This is a good problem. It sounds like this login code is potentially useful in the future for you.) (这是一个好问题。听起来这个登录代码将来可能对您有用。)
From your code the first step (although not the best one) could be: 从您的代码开始,第一步(尽管不是最好的一步)可能是:
public class NewGame{
public static void main(String[] args) {
UserLog.main();
}
Better if you change the signature of your UserLog.main()
method to have a non-static
method of UserLog
, eg 如果将
UserLog.main()
方法的签名更改为具有UserLog.main()
的non-static
方法,则UserLog
,例如
public class UserLog extends JFrame {
public void newMethod(String[] args) throws InterruptedException {
// your code in old main method
}
}
and use this method from another class as follows: 并从另一个类使用此方法,如下所示:
public class NewGame {
public static void main(String[] args) {
UserLog userLog = new UserLog;
userLog.newMethod(args);
}
}
If you don't pass any arguments to newMethod you can remove the params String[] args
in the method definition and in the call userLog.newMethod()
如果您不向newMethod传递任何参数,则可以在方法定义和调用
userLog.newMethod()
删除params String[] args
。
Use a public method in the login class that returns whether the user has logged in or not. 在登录类中使用公共方法,该方法返回用户是否已登录。 In the class that calls it use userLog log=new userLog(), then repeatedly call the method.
在调用它的类中,使用userLog log = new userLog(),然后重复调用该方法。 If it returns true, then the user has successfully logged in.
如果返回true,则表明用户已成功登录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.