Coloquei no Jframe o uma KeyPressed queria pegar e sair quando precionado esc porem coloquei um simples print e nem imprimiu parece que é porque não esta no foco, fiz o teste num campo funcionou tudo certo.
Estou usando o NetBeans
Alguma dica
Coloquei no Jframe o uma KeyPressed queria pegar e sair quando precionado esc porem coloquei um simples print e nem imprimiu parece que é porque não esta no foco, fiz o teste num campo funcionou tudo certo.
Estou usando o NetBeans
Alguma dica
Para ESC não funciona direito essa história do KeyPressed. Como eu havia comentado em um outro post, se você usou KeyPressed, provavemente usou errado.
http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
Este é um exemplo bem boboca, simplesmente cria um JFrame que fecha com ESC. Note que o botão “Fechar” também fecha o JFrame, e aqui vai um exemplo de reuso de Action.
package guj;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class JFrameFechaComEsc extends JFrame {
class FecharAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
// Isto serve para fechar este frame JFrameFechaComEsc
JFrameFechaComEsc.this.dispose();
}
}
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
private JPanel pnlBotoes = null;
private JButton btnFechar = null;
private JPanel getPnlBotoes() {
if (pnlBotoes == null) {
pnlBotoes = new JPanel();
pnlBotoes.setLayout(new FlowLayout());
pnlBotoes.add(getBtnFechar(), null);
}
return pnlBotoes;
}
private JButton getBtnFechar() {
if (btnFechar == null) {
btnFechar = new JButton();
btnFechar.setText("Fechar");
btnFechar.addActionListener(new FecharAction());
}
return btnFechar;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrameFechaComEsc thisClass = new JFrameFechaComEsc();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
});
}
public JFrameFechaComEsc() {
super();
initialize();
}
private void initialize() {
this.setSize(300, 200);
this.setContentPane(getJContentPane());
this.setTitle("Tecle ESC para fechar este JFrame");
this.getJContentPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "esc");
this.getJContentPane().getActionMap().put("esc", new FecharAction());
}
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(new BorderLayout());
jContentPane.add(getPnlBotoes(), BorderLayout.SOUTH);
}
return jContentPane;
}
}