Detectar tecla enter dentro de um JTextField

Pessoal, como posso detectar quando o usuário teclou uma das teclas enter e substituir essa tecla pelo TAB para que o sistema mude o foco para o próximo controle?

Olha se isso te ajuda…

import java.awt.Container;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class TestEnter extends JFrame {
	private static final long serialVersionUID = 6742536347999732501L;

	public void init() {
		final JTextField field = new JTextField("press ENTER");

		final Container container = getContentPane();
		container.add(field);
		field.addKeyListener(new KeyAdapter() {
			public void keyPressed(final KeyEvent e) {
				int key = e.getKeyCode();
				if (key == KeyEvent.VK_ENTER) {
					System.out.println("ENTER pressed");
				}
			}
		});
		
		setSize(150, 70);
		setLocationRelativeTo(null);
		setVisible(true);
	}
	
	public static void main(String[] args) {
		final TestEnter test = new TestEnter();
		test.init();
	}
}

Depois de um tempo, isso me serviu demais.

Agora, queria saber como faço para colocar JTextFiel em um JOptionPane e ao pressionar a tecla E, ele pegar o valor do text digitado e dar sequencia no programa.
É possível essa loucura?

abs

Sim é possível. você pode usar um

JOptionPane.showInputDialog();

Exemplo:


import javax.swing.JOptionPane;

public class JOptionEntrada 
{
   public static void main(String[] args) 
   {
      String fullName = " ";
      fullName = JOptionPane.showInputDialog(null, "Insira seu nome: ");
      
      JOptionPane.showMessageDialog(null, "Seu nome é " + fullName);
   }
}

Mas não sei o motivo quer quer fazer isso, de quando pressionar a tecla E, ele pegar o valor digitando, sendo que no seu texto não vai aceitar a letra E? :?

E se alguém digitar: TEXTO?, antes mesmo do X ele já vai encerrar o JOptionPane, e pegar apenas com o T? :?

[quote=DinhoPereira]Depois de um tempo, isso me serviu demais.

Agora, queria saber como faço para colocar JTextFiel em um JOptionPane e ao pressionar a tecla E, ele pegar o valor do text digitado e dar sequencia no programa.
É possível essa loucura?

abs[/quote]

Oi,

Não é loucura. Você pode fazer da seguinte maneira:

//Criar a mensagem sera exibida JLabel label = new JLabel("Digite a senha:"); //criar o componente grafico que recebera o que for digitado JTextField event = new JTextField(); //Exibe a janela JOptionPane.showConfirmDialog(null, new Object[]{label, event}, "Senha:", JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);

Adicione o KeyListener nesse JTextField event e trate a tecla.

OBS: O correto mesmo seria você criar uma classe que estenda a JDialog e fazer todas as alterações para atender suas necessidades…

Tchauzin!

Cheguei nisso e disso não saí!.. :oops:
Me ajude só mais um pouquinho?

[code]JLabel label = new JLabel(“Digite a senha:”);
//criar o componente grafico que recebera o que for digitado
JTextField event = new JTextField();
event.setFocusable(true);

	event.addKeyListener(new KeyListener() {
		
		@Override
		public void keyTyped(KeyEvent e) {
			// TODO Auto-generated method stub
			if (e.getKeyCode() == KeyEvent.VK_I){
				//nesse ponto aqui queria que ele entendesse o I com se fosse ENTER, ou seja, pegar a valor inserido no textField e dar sequência
			}
		}
		
		@Override
		public void keyReleased(KeyEvent e) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void keyPressed(KeyEvent e) {
			// TODO Auto-generated method stub
			
		}
	});
    
    
    //Exibe a janela  
    JOptionPane.showConfirmDialog(null,  
    new Object[]{label, event}, "Senha:",  
    JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);[/code]

Oi,

Implemente o keyPressed e não o keyTyped.

Tchauzin!

Certo, mas como eu pegaria o valor digitado no text do JOption além de fechar o JOption ?

Quando a pessoa clicar a letra “I”, ele deve fechar o JOption pegando o valor digitado no JText e seguir adiante.

Obrigadooooo

[quote=DinhoPereira]Certo, mas como eu pegaria o valor digitado no text do JOption além de fechar o JOption ?

Quando a pessoa clicar a letra “I”, ele deve fechar o JOption pegando o valor digitado no JText e seguir adiante.

Obrigadooooo[/quote]

Oi,

Olha.:

[code]JLabel label = new JLabel(“Digite a senha:”);
//criar o componente grafico que recebera o que for digitado
JTextField event = new JTextField();
event.setFocusable(true);

	event.addKeyListener(new KeyListener() {
		
		@Override
		public void keyTyped(KeyEvent e) {
			
		}
		
		@Override
		public void keyReleased(KeyEvent e) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void keyPressed(KeyEvent e) {
			// TODO Auto-generated method stub
			if (e.getKeyCode() == KeyEvent.VK_I){
				JOptionPane.getRootFrame().dispose();
			}
			
		}
	});
    
    
    //Exibe a janela  
    JOptionPane.showConfirmDialog(null,  
    new Object[]{label, event}, "Senha:",  
    JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);[/code]

API:

[b]Frame javax.swing.JOptionPane.getRootFrame() throws HeadlessException
Returns the Frame to use for the class methods in which a frame is not provided.

Returns:
the default Frame to use
Throws:
HeadlessException - if GraphicsEnvironment.isHeadless returns true
See Also:
setRootFrame
java.awt.GraphicsEnvironment.isHeadless[/b]

======================================================

[b]void java.awt.Window.dispose()
Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable.

The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions). [/b]

Tchauzin!

Tive que aplicar uma outra solução encontrada na net

Agradeço muito muito mesmo a ajuda hein.

abs

[code]
public static String showPasswordDialog(Frame owner,String message,String initialValue,String title) {
final JPasswordField pField = new JPasswordField(20);
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
final JPanel pPanel;

    pField.addKeyListener(new KeyListener() {  
        
        @Override  
        public void keyTyped(KeyEvent e) {  
              
        }  
          
        @Override  
        public void keyReleased(KeyEvent e) {  
            // TODO Auto-generated method stub  
              
        }  
          
        @Override  
        public void keyPressed(KeyEvent e) {  
            // TODO Auto-generated method stub  
            if (e.getKeyCode() == KeyEvent.VK_I){  
                JOptionPane.getRootFrame().dispose();  
            }  
              
        }  
    });          
    
    
     
    c.insets.top = 4;
    c.insets.bottom = 4;
pField.setText(initialValue);
    pPanel = new JPanel(gridbag);
    pPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 5, 20));
    c.anchor = GridBagConstraints.WEST;
    pPanel.add(new JLabel(message),c);
    pField.addFocusListener(new FocusListener() {
        public void focusLost(FocusEvent fe) {
            pField.setBackground(Color.white);
        }
        public void focusGained(FocusEvent fe) {
            pField.setBackground(Color.yellow);
        }
    });
     
    c.gridy=1;
    pPanel.add(pField,c);
    pPanel.requestFocusInWindow(); //DOES NOT WORKS
    JButton okButton = new JButton("OK") {
        boolean firstTimeFocuss=true;
        @Override
        public void requestFocus() {
            if(firstTimeFocuss) {
                pPanel.requestFocusInWindow();
                firstTimeFocuss=false;
            }                  
            super.requestFocus();
        }
    };
   Object[] possibleValues = {okButton, "Cancel"};
    JOptionPane pane=new JOptionPane(pPanel, JOptionPane.QUESTION_MESSAGE);
    pane.setOptions(possibleValues);
     
    final JDialog jd=pane.createDialog(owner,title);
    pField.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae)  {
            jd.setVisible(false)    ;
        }
    });
    okButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            jd.setVisible(false);
        }      
    });
    jd.setVisible(true);
   Object selectedValue = pane.getValue();
   /*if(selectedValue!=null)
        System.out.println (selectedValue+"="+selectedValue.getClass());*/
    jd.dispose();
    //int result = JOptionPane.showConfirmDialog(owner, pPanel,title,JOptionPane.OK_CANCEL_OPTION);       
    if (selectedValue!=null && selectedValue.equals("uninitializedValue"))
        return String.valueOf(pField.getPassword());
    return null;
}    
[/code]

e faço a chamada assim