How to add keyListner to a JOptionPane.showInputDialog()? - java

I want to add keyListner on Input Dialog. When i press a key it will gives key code of pressed key. Below is complete code for JTextField its working for JTextField. I tried it on Input Dialog via String n = JOptionPane.showInputDialog("enter a key") but it says that keyListner unidentified for String operation.
*please edit my code for Input dialog
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();
}
}

You can try something like below :
Here you can create a text field by adding keyListener and that text field can be passed to the 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;
}

Here's a hint for what you can do:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class KeyListnerExample extends JFrame implements KeyListener{
JTextField KeyCodeT;
public KeyListnerExample(){
JPanel panel = new JPanel();
KeyCodeT = new JTextField();
KeyCodeT.setOpaque(false);
panel.setLayout(new GridLayout(1,1));
panel.add(KeyCodeT);
JOptionPane.showOptionDialog(null, panel, "Enter Key Code", JOptionPane.CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
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();
}
}
As you can see, I created a JPanel and added text field to it instead. Its easier to manage that way. Then finally used JOptionPane's OptionDialog to display stuff.
You can also use KeyCodeT.setBorder(null); if you dont want that black border. But that will give you an absurd dialog where you will have to make a guess-click in the middle.
EDIT: (Practically what #kamel2005 said in his answer).

Create a JPane Control that contains the control that will broadcast the key event to your key Listener.
for example JTextField and then add your key listener to text field.
the Pane can be passed as a parameter to "JOptionPane"

JPanel jPane = new JPanel();
TextField field = new TextField();
jPane.add(field);
field.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
});
if (JOptionPane.showConfirmDialog(null,jPane,"Panel Title", JOptionPane.OK_CANCEL_OPTION)== JOptionPane.OK_OPTION) {
System.out.println(field.getText());
}

Related

Using a buffer between input and a JTextField

Instead of using a document filter, or a FormatMask I am trying something different.
Here is the requirements. Have a JTextField only accept/have one character of input allowed into it at a time, the only allowed input is numbers 1-9 think of the game Sudoku, all other input is invalid and should not be allowed. I tried handleing this with both of the above ideas and still kept getting error beeps for backspace and delete keys when using focus on the JTextField.
So I thought why not have something as a buffer that can ignore all input data I did not want to accept here is my solution.
import java.awt.Component;
import java.awt.GridLayout;
import javax.swing.*;
import java.awt.event.*;
public class MaskField
{
JFrame thisframe;
JPanel jPanel1 = new JPanel();
JTextField jTextField1 = new JTextField();
public MaskField()
{
thisframe = new JFrame();
jTextField1.addFocusListener(new FocusListener(){
#Override
public void focusLost(FocusEvent e){}
#Override
public void focusGained(FocusEvent e)
{
JTextField thisfield = (JTextField)e.getSource();
thisfield.getParent().requestFocus();
}
});
jPanel1.addKeyListener(new KeyAdapter()
{
#Override
public void keyReleased(KeyEvent e){}
#Override
public void keyTyped(KeyEvent e){}
#Override
public void keyPressed(KeyEvent e)
{
JPanel thispanel = (JPanel)e.getSource();
Component[] complist = thispanel.getComponents();
JTextField thisfield = (JTextField)complist[0];
text = thisfield.getText();
if(Character.isDigit(e.getKeyChar()) && !"0".equals(Character.toString(e.getKeyChar())))
{
thisfield.setText(Character.toString(e.getKeyChar()));
}
if(e.getKeyCode() == 127 || e.getKeyCode() == 8)
thisfield.setText("");
}
});
jPanel1.setLayout(new GridLayout(1,1));
jTextField1.setText("");
jPanel1.add(jTextField1);
thisframe.add(jPanel1);
thisframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisframe.setVisible(true);
thisframe.pack();
}
public static void main(String args[])
{
new MaskField();
}
}
I would greatly appreciate any different ideas about how to handle this because getting and changing the JTextField data is so verbose.

Event call doesn't work with key bind or click - what's the logical error?

I'm trying to call this event below; I create the frame with TabBuilder (since is part of my application) then it calls the Search screen which is popping up; but the event of the search with key bind or simple click on the button is not working and of course I'm doing something wrong but I don't know what since I'm a little bit new in Java. Please could anyone help me?
SearchScreen:
public class SearchScreen extends EventSearch{
public static void main (String[] args){
SearchScreen s= new SearchScreen();
}
public void SearchScreen(){
TabBuilder tb = new TabBuilder();
tb.searchTab();
}
}
EventSearch:
public class EventSearch extends TabBuilder{
String userQuery;
String key = "ENTER";
KeyStroke keyStroke = KeyStroke.getKeyStroke(key);
public EventSearch(){
btSearch.addActionListener(this);
txtSearch.getInputMap().put(keyStroke, key);
txtSearch.getActionMap().put(key, enterAction);
}
Action enterAction = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
try{
System.out.println("worked");
} catch (IOException e1) {
e1.printStackTrace(); //print failure
JOptionPane.showMessageDialog(null, "HTTP request failure.");
}
}
};
}
TabBuilder:
public class TabBuilder implements ActionListener {
protected JButton btSearch;
JMenuItem close, search;
protected JTextField txtSearch;
protected JFrame searchFrame = new JFrame();
public void TabBuilder(){
}
public void searchTab(){
JLabel lbSearch;
JPanel searchPane;
btSearch= new JButton("Search");
lbSearch= new JLabel("Type Keywords in english to be searched below:");
lbSearch.setHorizontalAlignment(SwingConstants.CENTER);
txtSearch= new JTextField();
searchPane=new JPanel();
searchPane.setBackground(Color.gray);
searchPane.add(lbSearch);
searchPane.add(txtSearch);
searchPane.add(btSearch);
searchPane.setLayout(new GridLayout(3,3));
btSearch.setEnabled(true);
searchFrame.add(searchPane);
searchFrame.setTitle("SHST");
searchFrame.setSize(400, 400);
searchFrame.setVisible(true);
searchFrame.setDefaultCloseOperation(1);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==search){
SearchScreen s = new SearchSreen();
}
}
}
You write this actionListener
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==search){
TabBuilder tb = new TabBuilder();
tb.searchTab();
}
}
and you added to btnSearch.addActionListener(this) , your actionListener never would do anything.
And for your KeyBinding happens something similar , you add the action to the txtSearch and then you are asking if the source is the e.getSource()==btSearch
And for KeyBindings you can use Constants to specify when they have to be binded.
JComponent.WHEN_FOCUSED, JComponent.WHEN_IN_FOCUSED_WINDOW , JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
For example :
txtSearch.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, key);
How to use KeyBindings

Java 1.7 issue, Enter key pressed work differently

I have following code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TesttxtF {
/**
* #param args
*/
public static void main(String[] args) {
TextField txt1 = new TextField();
TextField txt2 = new TextField();
DefaultFocusManager manager = new DefaultFocusManager() {
#Override
public void processKeyEvent(Component focusedComponent, KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_ENTER:
if (e.getID() == KeyEvent.KEY_PRESSED)
super.focusNextComponent(focusedComponent);
else
super.processKeyEvent(focusedComponent, e);
break;
default:
super.processKeyEvent(focusedComponent, e);
break;
}
}
};
FocusManager.setCurrentManager(manager);
JPanel panel = new JPanel();
panel.add(txt1);
panel.add(txt2);
txt1.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
System.out.println("Key keyTyped");
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("Key keyReleased");
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed");
}
});
txt1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action performed");
}
});
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel, null);
frame.setSize(100, 100);
frame.setVisible(true);
}
}
When run with
jdk1.6.0_18 -> output as following when pressing enter key
Key Pressed
Key keyTyped
Action performed
jdk1.7.0_12 -> output as following when pressing enter key
Key Pressed
What is wrong with java 7 then ?
when i typed any number and clear the console. Then press the Enter key focus changed to next component but actionperformed never fired in java 7. How i can fix it ? i had checked with java 7 update 25 also. i got same result. Can anybody help ?

Is it Possible to Add ActionListener in the JFormattedTextField?

Hello I'm currently working in my java file.
I'd like to add an event on JFormattedTextField when I press the enter key.
This is my code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.MaskFormatter;
import java.awt.*;
import java.text.ParseException;
public class Test extends JFrame implements ActionListener
{
JFormattedTextField phoneField;
Test()
{
setTitle("JFormatted Text");
setLayout(null);
MaskFormatter mask = null;
try {
mask = new MaskFormatter("##########");
} catch (ParseException e) {
e.printStackTrace();
}
phoneField = new JFormattedTextField(mask);
phoneField.setBounds(20, 20, 150, 30);
phoneField.addActionListener(this);
setVisible(true);
setSize(200, 200);
getContentPane().add(phoneField);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new Test();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== phoneField)
{
System.out.println("The numbers you enter are "+phoneField.getText());
}
}
}
it works but their the user needs to enter 10 digits.
Add an ActionListener to the field. It is better than using the (low level) KeyListener and will conform to whatever that OS accepts as 'end of entry'.
Don't use KeyListener instead use DocumentListener.
It has the following methods which captures the changes in the JTextField
JTextField textField = new JTextField();
textField.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent arg0) {
// Gives notification that a portion of the document has been removed.
}
#Override
public void insertUpdate(DocumentEvent arg0) {
// Gives notification that there was an insert into the document.
}
#Override
public void changedUpdate(DocumentEvent arg0) {
// Gives notification that an attribute or set of attributes changed.
}
});
You could add a keyListener instead.
phonefield.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
if(evt.getKeyCode() == evt.VK_ENTER){
System.out.println("The numbers you enter are "+phoneField.getText());
}
}
});
If this isn't your problem, you should expand a little and clarify.
EDIT:
As comments and other answers pointed out, you should go for an ActionListener instead. Reasoning can be found below.

Mac/Java-7: Why does TextField not get the expected KEY_PRESSED events when Alt is down?

When executing a keyboard event that includes an 'Alt,' Mac/Java-7 does not propagate a KEY_PRESSED against a non-modifier key in the key sequence against TextFields.
This behavior is not reproducible against other modifier keys like Cmd or Ctrl.
For example, when compiling and running the below code and executing a 'Alt + o' keystroke in the TextField, all platforms, except Mac/Java 7, output the following key event sequence (note that there is a KEY_PRESSED for both the 'alt' and the 'o'):
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=18,keyText=?,keyChar=Undefined keyChar,modifiers=?
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=79,keyText=O,keyChar='ø',modifiers=?
java.awt.event.KeyEvent[KEY_TYPED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar='ø',modifiers=?
java.awt.event.KeyEvent[KEY_RELEASED,keyCode=79,keyText=O,keyChar='ø',modifiers=?...
java.awt.event.KeyEvent[KEY_RELEASED,keyCode=18,keyText=?,keyChar=Undefined...
However, on Mac/Java-7 (tested up to patch 10), you get the above without the KEY_PRESSED representing the 'o' (KEY_PRESSED,keyCode=79,keyText=O,keyChar='ø'). The KEY_TYPED event might not be the most helpful substitute because it doesn't have modifiers or a keyCode, at least without tracking some state.
import javax.swing.*;
import java.awt.event.*;
public class ScratchKeyEvent {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JTextField field = new JTextField(10);
field.addKeyListener(createListener());
frame.add(panel);
panel.add(field);
frame.setVisible(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static KeyListener createListener() {
return new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped " + e);
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed " + e);
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased " + e);
}
};
}
}

Categories