gpt4 book ai didi

java - java 线程上的关键事件

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

我需要向用户显示一个随机字符,并从显示该字符的那一刻起检查用户是否在该字符消失并显示另一个字符之前键入它。我能够做到这一点,但是在THREAD测试中使用实际上并没有进行。这是我的代码:

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;

import javax.swing.*;

public class MyThread extends Frame implements Runnable{
String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private JLabel lbl;
JPanel contentPane;
public Random rnd;

public MyThread() {
lbl = new JLabel("Hello world");
contentPane = new JPanel(null);

setFocusable(true);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (KeyEvent.getKeyText(keyCode) == lbl.getText()) {
System.out.println("nice");
}
else
System.out.println("not");

repaint();

}

});

add(lbl);
setSize(200,100);
setLocation(300,300);


rnd = new Random();
setVisible(true);

}

public void run() {

try {
while (true) {
if (lbl.getText() == null)
lbl.setText(Character.toString(abc.charAt(rnd.nextInt(26))));
else
lbl.setText(null);

Thread.sleep(900);
}
}
catch (InterruptedException ex) {
}
}



public static void main(String []args){
new Thread(new MyThread()).start();

}
}

问题是什么以及如何解决?谢谢..

最佳答案

该代码中存在几个问题:

  • 您不必要地将 AWT(例如 Frame)与 Swing 混合
  • 您正在脱离 Swing 事件线程启动 Swing GUI
  • 您正在向 Frame 对象添加 KeyListener
  • 您的代码通过更改事件线程之外的 Swing 组件状态来违反 Swing 线程规则。
  • 您正在将字符串与 == 运算符进行比较,该运算符用于检查引用是否相等,而您对此并不感兴趣。字符串应该与 .equals(...).equalsIgnoreCase(...) 方法进行比较,这些方法检查功能性相等——两个字符串以相同的顺序保存相同的字符,这就是您想要的。
  • 当更好的构造是使用 javax.swing.Timer 或“Swing Timer”时,您正在使用 while (true) 循环。

例如

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class MyGui extends JPanel {
private static final char[] ABC = "ABCDEFGHIJKLMNOPQURSTUVWXYZ".toCharArray();
private static final int PREF_W = 250;
private static final int PREF_H = 150;
private static final int TIMER_DELAY = 900;
private JLabel label = new JLabel();
private DefaultListModel<String> statusListModel = new DefaultListModel<>();
private JList<String> statusList = new JList<>(statusListModel);

public MyGui() {
JPanel centerPanel = new JPanel(new GridBagLayout());
centerPanel.add(label);
setPreferredSize(new Dimension(PREF_W, PREF_H));

statusList.setPrototypeCellValue(" GOOD ");
JScrollPane statusPane = new JScrollPane(statusList);
statusPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

setLayout(new BorderLayout());
add(centerPanel, BorderLayout.CENTER);
add(statusPane, BorderLayout.LINE_END);

new Timer(TIMER_DELAY, new TimerListener()).start();

setFocusable(true);
requestFocusInWindow();

addKeyListener(new MyKeyListener());
}

private class MyKeyListener extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
String keyText = KeyEvent.getKeyText(keyCode).toUpperCase();
if (keyText.equals(label.getText())) {
statusListModel.addElement("good");
} else {
statusListModel.addElement("bad");
}
statusList.ensureIndexIsVisible(statusListModel.size() - 1);
}
}

private class TimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String text = label.getText();
if (text.isEmpty()) {
int randomIndex = (int) (ABC.length * Math.random());
text = String.valueOf(ABC[randomIndex]);
label.setText(text);
} else {
label.setText("");
}
}
}

private static void createAndShowGui() {
JFrame frame = new JFrame("MyGui");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyGui());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

关于java - java 线程上的关键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44855455/

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