JButton + Default Key

3 respostas
AlencarCanton

e ae galera,
seguinte,
tenho um botão de pesquisa em um jFrame,o usuário preenche um jTextField e clica no botão para fazer a pesquisa…preciso fazer com que qnd o enter for pressionado o evento do botao seja chamado…como faço?alguma idéia?
vlw!

3 Respostas

yhhik

é só add o handler o Jtextfield…o jeito mais fácil não precisa implementar interface nenhuma. :smiley:

yhhik
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class guj extends JFrame {

	public guj() {
		this.setLayout(new FlowLayout());
		JButton botao = new JButton("botao");
		JTextField txt = new JTextField(15);
		util handler = new util();
		botao.addActionListener(handler);
		txt.addActionListener(handler);
		this.add(botao);
		this.add(txt);
		this.setSize(200, 200);

	}

	private class util implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			JOptionPane.showMessageDialog(null, "vc apoertou o botao");
		}

	}

	public static void main(String[] args) {
		new guj().setVisible(true);
	}

}
ViniGodoy
No construtor do seu JFrame faça:
getRootPane().setDefaultButton(btnPesquisa);

(Estou assumindo aqui que seu botão de pesquisa está criado e chama-se btnPesquisa).

Alterando o exemplo do yhhik para demonstrar:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class GujFrame extends JFrame {

	public GujFrame() {		
		this.setLayout(new FlowLayout());
		
		JButton botao = new JButton("botao");
		botao.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, "vc apoertou o botao");
			}
		});
		this.add(botao);
		getRootPane().setDefaultButton(botao);
		
		JTextField txt = new JTextField(15);		
		this.add(txt);
		this.setSize(200, 200);
		this.setLocationRelativeTo(null);
	}

	public static void main(String[] args) {
		new GujFrame().setVisible(true);
	}
}

Além de muito simples, elimina a necessidade de ter que registrar o ActionListener em cada componente da tela.
Além disso, o Swing irá destacar o botão padrão com uma borda mais forte, indicando que ele é o padrão.

Para outros tipos de tecla de atalho, o ideal também é não usar listeners. Use o ActionMap e o KeyMap, como explicado aqui:
http://www.guj.com.br/java/140986-como-acionar-os-bots-de-uma-calculadora-atrav-do-teclado

Criado 5 de janeiro de 2012
Ultima resposta 5 de jan. de 2012
Respostas 3
Participantes 3