gpt4 book ai didi

java - 如何将 keyListner 添加到 JOptionPane.showInputDialog()?

转载 作者:行者123 更新时间:2023-11-30 07:46:54 25 4
gpt4 key购买 nike

我想在输入对话框上添加 keyListner。当我按下一个键时,它会给出按下的键的键码。下面是 JTextField 的完整代码,它适用于 JTextField。我通过 String n = JOptionPane.showInputDialog("enter a key") 在输入对话框上尝试了它但它说 keyListner 无法识别字符串操作。

*请编辑我的输入对话框代码

import java.awt.event.*;
import javax.swing.*;
public class KeyListnerExample extends JFrame implements KeyListener{

String KeyCodeT = JOptionPane.showInputDialog("enter a key");//A Text Field that will display the key code.

public KeyListnerExample(){
KeyCodeT.addKeyListener(this);//Listens for key inputs in the text field
KeyCodeT.setEditable(false);//disallow user input into the Text field.
add(KeyCodeT);//add the text field to the screen
setSize(300,300);//set the screen size
setVisible(true);//show the window on screen.
}
//Called when the key is pressed down.
public void keyPressed(KeyEvent e){
System.out.println("Key Pressed!!!");

e.getKeyCode();
System.out.println("key code is: " +e.getKeyCode());

}

//Called when the key is released
public void keyReleased(KeyEvent e){
System.out.println("Key Released!!!");
KeyCodeT.setText("Key Code:" + e.getKeyCode());//displays the key code in the text box

}
//Called when a key is typed
public void keyTyped(KeyEvent e){


}

public static void main(String[] args){
KeyListnerExample key = new KeyListnerExample();
}

}

最佳答案

您可以尝试如下所示:

在这里,您可以通过添加 keyListener 创建一个文本字段,并且该文本字段可以传递到 JoptionPane 。

public static void main(String[] args) {
JFrame parent = new JFrame();
JOptionPane optionPane = new JOptionPane();
JTextField field = getField();
optionPane.setMessage(new Object[]{"Type something: ", field});
optionPane.setMessageType(JOptionPane.QUESTION_MESSAGE);
optionPane.setOptionType(JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = optionPane.createDialog(parent, "My Customized OptionPane");
dialog.setVisible(true);

}

private static JTextField getField() {
JTextField field = new JTextField();
field.addKeyListener(new KeyListener() {

@Override
public void keyTyped(KeyEvent e) {

}

@Override
public void keyPressed(KeyEvent e) {
System.out.println("Input: " + e.getKeyChar());
}

@Override
public void keyReleased(KeyEvent e) {
}
});
return field;
}

关于java - 如何将 keyListner 添加到 JOptionPane.showInputDialog()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33809616/

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