public static void main(String[] args) throws PrinterException {
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) tk.getScreenSize().getWidth());
int ySize = ((int) tk.getScreenSize().getHeight());
final String password = "Alphabet";
JFrame screen = new JFrame("INSERT TITLE HERE");
screen.setSize(xSize, ySize);
screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
screen.setResizable(false);
screen.setVisible(true);
final JWindow window = new JWindow(screen);
window.setSize(xSize, ySize);
window.setName("INSERT TITLE HERE");
final JTextArea text = new JTextArea();
text.setText("Type the password > ");
text.setBackground(Color.BLACK);
text.setForeground(Color.green);
window.add(text);
window.setVisible(true);
text.addKeyListener(new java.awt.event.KeyAdapter(){
public void keyReleased(java.awt.event.KeyEvent evt) {
System.out.println(evt.getKeyCode());
if(evt.getKeyCode() == 51){
System.out.println(text.getText());
String passAttempt = text.getText();
int start = passAttempt.indexOf('>') + 2 ;
int end = passAttempt.indexOf('#');
passAttempt = passAttempt.substring(start, end);
if(passAttempt.equals(password)) {
System.out.println("SUCCESSFUL");
text.setText("Login Successful");
window.add(text);
window.setVisible(true);
}
if(!passAttempt.equals(password)) {
System.out.println(passAttempt);
text.setText("Incorrect");
window.add(text);
window.setVisible(true);
}
}
}
});
}
我正在尝试创建一个类似后果的用户界面,我需要在打开 UI 之前让用户输入输入“密码”,但我不知道如何从 JTextArea 读取输入,请帮助!
注意:这里的主要目标是保持使用老式 DOS 程序的感觉,所以我不能使用 JOptionPane 或类似的东西。
编辑:感谢大家的帮助,我最终选择了 keyListener,它运行良好!