We may sometimes need to have that when we press the enter key it automatically performs some tasks.
And when we press the escape key it automatically exits the application or like else.
So here is a simple example to do so.
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;
public class DefaultEscapeButton extends JFrame
{
JButton btn1,btn2;
//Preparing ActionListener for escape key pressed
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
};
DefaultEscapeButton()
{
setLayout(null);
btn1 = new JButton("Default");
btn1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
System.out.println(btn1.getText());
}
});
btn1.setBounds(10,10,150,30);
btn2 = new JButton("Cancel");
btn2.setBounds(10,50,150,30);
//This is the code for when Escape key is pressed
getRootPane().registerKeyboardAction(al,KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0),JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
add(btn1);
add(btn2);
getRootPane().setDefaultButton(btn1);
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new DefaultEscapeButton();
}
}
And when we press the escape key it automatically exits the application or like else.
So here is a simple example to do so.
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;
public class DefaultEscapeButton extends JFrame
{
JButton btn1,btn2;
//Preparing ActionListener for escape key pressed
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
};
DefaultEscapeButton()
{
setLayout(null);
btn1 = new JButton("Default");
btn1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
System.out.println(btn1.getText());
}
});
btn1.setBounds(10,10,150,30);
btn2 = new JButton("Cancel");
btn2.setBounds(10,50,150,30);
//This is the code for when Escape key is pressed
getRootPane().registerKeyboardAction(al,KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0),JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
add(btn1);
add(btn2);
getRootPane().setDefaultButton(btn1);
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new DefaultEscapeButton();
}
}
No comments:
Post a Comment