gpt4 book ai didi

Java Swing 计时器窗口不会填充

转载 作者:行者123 更新时间:2023-12-01 18:06:24 25 4
gpt4 key购买 nike

大家。我有4节课; FrameViewerOne 是我运行应用程序的地方,FrameBuilderOne 包含大部分代码,包括二分搜索和许多其他内容,Person 类实现比较,我用compareTo() 方法覆盖它,而我的 TimerLockout 类是我切换到的窗口,该窗口应该填充,将用户锁定 15 秒,并在计时器滴答时显示倒计时。这应该是在用户 3 次错误尝试后发生的。当计时器达到 0 秒时,我希望它关闭 TimerLockout 类并重新打开(setVisible)原始框架。不幸的是,我的代码可以编译,但无法填充计时器。感谢您的宝贵时间,我们将不胜感激任何帮助/建议!

以下是说明: 1) 使用“计数器”允许用户尝试失败 3 次。 2) 如果用户连续三次未能输入正确信息,则系统将锁定15秒。 2.1) 您应该仅以秒为单位显示倒计时窗口,而不是整个系统时间。

//FRAMEVIEWERONE CLASS
import javax.swing.JFrame;//The Frame class is part of the javax.swing package.Swing is the nickname for the gui onterface library in java.
import java.io.*;
public class FrameViewerOne
{
public static void main(String[] args)throws IOException{//This is a warning to the compiler that we are throwing an exception! Proper syntax is to have this AFTER the method header.
{
JFrame Frame1 = new FrameBuilderOne();
Frame1.setVisible(true);
Frame1.setSize(200,300);
Frame1.setTitle("Lab One GUI");
Frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//This adds the x button on the top right. If you omit this step, the program will keep running even after you close the frame.
}
}
}

//FRAMEBUILDERONE CLASS
import javax.swing.*;//The asterik(*) tells Java to import everything that is being used in the package.
import java.awt.event.*;//Has the ActionEvent and KeyEvent. awt: Abstract Window Toolkit
import java.awt.event.ActionListener;
import java.util.*;//This does not have an asterik because I am only importing a specific tool (Scanner) from the java package,util. Scanner is the namespace of the package
import java.io.*; //Always use IOException when working with files. FileNotFoundException is a specific IO Exception. Exceptions are objects.
import javax.swing.BoxLayout;
import javax.swing.JPasswordField;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;

public class FrameBuilderOne extends JFrame{
private JButton loginBtn, exitBtn;
private JPanel newPanel, userNamePanel, passWordPanel, studentIdPanel, buttonPanel;
private JTextField usernameTextField;
private JPasswordField passwordTextField;
private JTextField studentIdTextField;
private JLabel usernameLabel, passwordLabel, studentIdLabel;
ArrayList<Person> personAry;
private int attempts;

public FrameBuilderOne()//Constructor
{
createPanel();//Method Call
personAry = checkInfo(new File("USERDATA.txt"));
Collections.sort(personAry);
}

private void createPanel()//Actual Method being called
{
newPanel = new JPanel();//The reserve word, new, denotes that a constructor method is being called
newPanel.setBorder(new EtchedBorder());
newPanel.setBorder(new TitledBorder(new EtchedBorder()));
newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.Y_AXIS));

userNamePanel = new JPanel();
usernameLabel = new JLabel("Username:");
userNamePanel.add(usernameLabel);

usernameTextField = new JTextField(10);
userNamePanel.add(usernameTextField);

newPanel.add(userNamePanel);

passWordPanel = new JPanel();
passwordLabel = new JLabel("Password:");
passWordPanel.add(passwordLabel);

passwordTextField = new JPasswordField(10);
passWordPanel.add(passwordTextField);

newPanel.add(passWordPanel);
passwordTextField.setEchoChar('*');

studentIdPanel = new JPanel();
studentIdLabel = new JLabel("Student ID:");
studentIdPanel.add(studentIdLabel);
studentIdTextField = new JTextField(10);
studentIdPanel.add(studentIdTextField);

newPanel.add(studentIdPanel);

buttonPanel = new JPanel();
loginBtn = new JButton("Login");
buttonPanel.add(loginBtn);

exitBtn = new JButton("Exit");
buttonPanel.add(exitBtn);

newPanel.add(buttonPanel);

ActionListener LoginListener = new ButtonsListen();//Create One Method since since both login and exit buttons share the same/similar task.
loginBtn.addActionListener(LoginListener);
exitBtn.addActionListener(LoginListener);

add(newPanel);
}

public ArrayList<Person> checkInfo(File data)
{
Scanner userInput;
ArrayList <Person> loginAry = new ArrayList<Person>();
try
{
userInput = new Scanner(data);//The reason why this isn't System.in is because you aren't taking input from the keyboard. You are scanning the file.
while (userInput.hasNextLine())
{
String finder = userInput.nextLine();
String [] loginInfo = finder.split(",");//This is a delimeter
String usernameInfo = loginInfo [0];
String passwordInfo = loginInfo [1];
long studentIdInfo = Long.parseLong(loginInfo[2]);

Person moreInfo = new Person(usernameInfo, passwordInfo, studentIdInfo);
loginAry.add(moreInfo);
}
userInput.close();
}
catch (FileNotFoundException e){
JOptionPane.showMessageDialog(null, "Error" + e.getMessage());
}
return loginAry;
}

public class Verify
{
/**
* This method implements the binary search within the personAry which contains the user's attributes.
* @param Person info - this is the information of the object Person which contains the username, password, and studentID.
* @return - this method returns true if info within Person is found. This returns it to the other method which displays the appropriate message to the user.
*/
public boolean validate(Person info)
{
int low = 0;
int high = personAry.size()-1;
int mid;
while(low <= high)
{
mid = (low + high) / 2;
Person middlePerson = personAry.get(mid);
int position = middlePerson.compareTo(info);
if(position < 0)
{
low = mid + 1;
}
else if(position > 0)
{
high = mid - 1;
}
else
{
return true;
}
}
return false;
}
}

public boolean validatePassword(String passwordSaver)//Check the password minimum, case sensitivity, and number in password
{
int caseCount=0;
int numCount=0;
if(passwordSaver.length() < 10)
{
JOptionPane.showMessageDialog(null, "Password must have ten characters");
}
else if(passwordSaver.length() >= 10)
for(int i = 0; i < passwordSaver.length(); i++)
{
char current = passwordSaver.charAt(i);
if(Character.isUpperCase(current)) {caseCount++;}
else if(Character.isDigit(current)){numCount++;}
}
if(caseCount == 0)
{
JOptionPane.showMessageDialog(null, "Password must have at least one uppercase character");
return false;
}
else if (numCount == 0)
{
JOptionPane.showMessageDialog(null, "Password must have at least one uppercase character");
return false;
}
else
{
return true;
}
}
public void createTimerClass()
{
this.setVisible(false);
TimerLockout Frame2 = new TimerLockout(this);
}

public class ButtonsListen implements ActionListener{
public void actionPerformed(ActionEvent e){

if(e.getSource()==loginBtn)
{
String username = usernameTextField.getText();
String id_str = studentIdTextField.getText();
long number = Long.parseLong(id_str);
String password;

char[] passArray = passwordTextField.getPassword();
password = new String(passArray);//Study this, write it out

Person txtFieldInfo = new Person(username, password, number);

Verify verifyLogin = new Verify();

if (!validatePassword(password))//also tells the user what went wrong
{
attempts++;
if(attempts == 3)
{
createTimerClass();
attempts = 0;
}
}

if (verifyLogin.validate(txtFieldInfo))
{
JOptionPane.showMessageDialog(null, "Login Successful");//JOptionPane is in the swing package. You must include null, before the message you want to display.
}

else
{
JOptionPane.showMessageDialog(null,"Invalid Login Information");
}
}

if (e.getSource()==exitBtn)
{
JOptionPane.showMessageDialog(null, "Program Shutting Down");
System.exit(0);
}
}
}
}

//PERSON CLASS
public class Person implements Comparable <Object>//The Comparable interface automatiically populates an empty CompareTo method behind the scenes.
{
private String username;
private String password;
private Long StudentID;

public Person(String User, String Pass, Long ID)
{
this.username = User;
this.password = Pass;
this.StudentID = ID;
}
public int compareTo(Object otherPerson)//Within the CompareTo method, you must pass in an object. This is overriding the empty CompareTo Method.
{
Person other = (Person) otherPerson;//You need to cast an object. tempStorage is going to store the username, password, and studentID.

if(other.StudentID > this.StudentID)
{
return 1;
}
else if(other.StudentID < this.StudentID)
{
return -1;
}
else
{
return 0;
}
}

public String getPassword ()
{
return this.password;
}

public String getUsername()
{
return this.username;
}

public Long getStudentID()
{
return this.StudentID;
}
}

//TimerLockout Class
import javax.swing.Timer;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
public class TimerLockout extends JFrame
{
private Timer timerLock;
private final int STARTING_TIME = 15;
private int currentTime = 15;
private final int ENDING_TIME = 0;
private FrameBuilderOne Frame1;
private JPanel secondPanel;
private JLabel timerMessage;

public TimerLockout(FrameBuilderOne previousFrame)
{
TimeListener listener = new TimeListener();
timerLock = new Timer(1000, listener);
Frame1 = previousFrame;
createSecondPanel();
}

private void createSecondPanel()
{
JPanel secondPanel = new JPanel();

timerMessage = new JLabel("You Are Temporarily Locked Out");
secondPanel.add(timerMessage);

ActionListener TimeListener = new TimeListener();
}

public class TimeListener implements ActionListener
{
public void actionPerformed(ActionEvent t)
{

while(currentTime >= STARTING_TIME)
{
currentTime--;
}
if(ENDING_TIME == 0)
{
Frame1.setVisible(true);
dispose();
}
}
}
}`

最佳答案

Unfortunately, my code compiles but I can't get the timer to populate

你从未真正启动计时器...

public class TimerLockout extends JFrame {
//...
public TimerLockout() {
TimeListener listener = new TimeListener();
timerLock = new Timer(1000, listener);
createSecondPanel();
// This would be helpful
timerLock.start();
}

I don't understand why the timer window isn't showing after 3 failed login attempts.

你永远不会让框架可见......

public void createTimerClass() {
this.setVisible(false);
TimerLockout Frame2 = new TimerLockout();
// ??
}

也许像...

TimerLockout Frame2 = new TimerLockout();
Frame2.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Frame2.pack();
Frame2.setLocationRelativeTo(null);
Frame2.setVisible(true);

But my TimerLock frame is empty/is really, really small (prediction)

这是因为您从未真正将 secondPanel 添加到 TimerLockout

public TimerLockout() {
TimeListener listener = new TimeListener();
timerLock = new Timer(1000, listener);
createSecondPanel();
add(secondPanel);
timerLock.start();
}

When TimerLockout throws a NullPointerException?! (prediction)

这是因为您在 createSecondPanel 中隐藏了 secondPanel,因此当您将其添加到框架时,实例字段为 null。 ..

private void createSecondPanel() {
// Well, there's your problem?!
//JPanel secondPanel = new JPanel();
secondPanel = new JPanel();

timerMessage = new JLabel("You Are Temporarily Locked Out");
secondPanel.add(timerMessage);
}

My TimerLockout window closes after 1 second?! (prediction)

这是因为您的TimeListener中的逻辑是错误的

public class TimeListener implements ActionListener {

public void actionPerformed(ActionEvent t) {

System.out.println(">> currentTime = " + currentTime + "; STARTING_TIME = " + STARTING_TIME);
while (currentTime >= STARTING_TIME) {
currentTime--;
}
System.out.println("<< currentTime = " + currentTime + "; STARTING_TIME = " + STARTING_TIME);
if (ENDING_TIME == 0) {
dispose();
}
}
}

让我们做一些基准测试

+--------+---------------+-------------+-------------+
| loop | STARTING_TIME | currentTime | ENDING_TIME |
+--------+---------------+-------------+-------------+
| <init> | 15 | 15 | 0 |
+--------+---------------+-------------+-------------+
| 1 | 15 | 15 | 0 |
+--------+---------------+-------------+-------------+
| 2 | 15 | 14 | 0 |
+--------+---------------+-------------+-------------+
| 3 | 15 | 14 | 0 |
+--------+---------------+-------------+-------------+

等等,什么?为什么currentTime更新时间更长?因为一旦 currentTime 不再是 >= STARTING_TIME,它就永远不会递减......此外,第一次 Timer 调用 ActionListener,您将处理该帧(不停止 Timer),因为 ENDING_TIME 始终为 0 >

相反,它应该更像......

public class TimeListener implements ActionListener {

public void actionPerformed(ActionEvent t) {
currentTime--;
if (currentTime <= ENDING_TIME) {
dispose();
timer.stop();
}
}
}

一个更简单的解决方案是简单地为 TimerLockOut 类使用 modal JDialog 而不是 JFrame,这意味着您不再需要调整主窗口的可见性状态,因为该对话框将阻止您与子窗口交互,直到它被处理为止

另一个选择是使用 JLayer/JXLayer API 并生成“锁定”效果,for exampleexample或者您可以设置一个使用鼠标事件的glassPanefor example

关于Java Swing 计时器窗口不会填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36123446/

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