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 ?
Related
I need help with my homework. I can't seem to make this program work. I just need to put shortcut keys for the compute, reset, and exit buttons.
Compute - Ctrl C
Reset - Ctrl R
Exit - Ctrl E
If you guys need my professor's instructions, I can provide that as well.
here
Here's my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener{
JLabel fval,sval;
JTextField tf1,tf2;
JButton add,subtract,multiply,divide,compute,reset;
String s="";
JPanel jp = new JPanel();
Calculator(){
jp.setLayout(new GridLayout(5,2));
fval=new JLabel("First Value: ");
sval=new JLabel("Second Value: ");
tf1=new JTextField();
tf2=new JTextField();
add=new JButton("ADD");
subtract=new JButton("SUBTRACT");
multiply=new JButton("MULTIPLY");
divide=new JButton("DIVIDE");
compute=new JButton("COMPUTE");
reset=new JButton("RESET");
jp.add(fval);
jp.add(tf1);
jp.add(sval);
jp.add(tf2);
jp.add(add);
jp.add(subtract);
jp.add(multiply);
jp.add(divide);
jp.add(compute);
jp.add(reset);
add.addActionListener(this);
subtract.addActionListener(this);
multiply.addActionListener(this);
divide.addActionListener(this);
compute.addActionListener(this);
reset.addActionListener(this);
this.setTitle("Calculator");
this.setBounds(10,10,300,300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
add(jp);
//ADD
Action addAction = new AbstractAction("ADD") {
#Override
public void actionPerformed(ActionEvent evt) {
s="ADD";
}
};
String key1 = "ADD";
add.setAction(addAction);
addAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_A);
add.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_DOWN_MASK), key1);
add.getActionMap().put(key1, addAction);
//SUBTRACT
Action subAction = new AbstractAction("SUBTRACT") {
#Override
public void actionPerformed(ActionEvent evt) {
s="SUBTRACT";
}
};
String key2 = "SUBTRACT";
subtract.setAction(subAction);
subAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_S);
subtract.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK), key2);
subtract.getActionMap().put(key2, subAction);
//MULTIPLY
Action mulAction = new AbstractAction("MULTIPLY") {
#Override
public void actionPerformed(ActionEvent evt) {
s="MULTIPLY";
}
};
String key3 = "MULTIPLY";
multiply.setAction(mulAction);
mulAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_M);
multiply.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_M, KeyEvent.CTRL_DOWN_MASK), key3);
multiply.getActionMap().put(key3, mulAction);
//DIVIDE
Action divAction = new AbstractAction("DIVIDE") {
#Override
public void actionPerformed(ActionEvent evt) {
s="DIVIDE";
}
};
String key4 = "DIVIDE";
divide.setAction(divAction);
divAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_D);
divide.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_D, KeyEvent.CTRL_DOWN_MASK), key4);
divide.getActionMap().put(key4, divAction);
}
public void Add(double n1,double n2){
JOptionPane.showMessageDialog(this, +(n1+n2), "Answer", JOptionPane.INFORMATION_MESSAGE);
}
public void Subtract(double n1,double n2){
JOptionPane.showMessageDialog(this, +(n1-n2), "Answer", JOptionPane.INFORMATION_MESSAGE);
}
public void Multiply(double n1,double n2){
JOptionPane.showMessageDialog(this, +(n1*n2), "Answer", JOptionPane.INFORMATION_MESSAGE);
}
public void Divide(double n1,double n2){
JOptionPane.showMessageDialog(this, +(n1/n2), "Answer", JOptionPane.INFORMATION_MESSAGE);
}
#Override
public void actionPerformed(ActionEvent e) {
String in=e.getActionCommand();
if(in.equals("COMPUTE")){
try {
double n1=Double.parseDouble(tf1.getText());
double n2=Double.parseDouble(tf2.getText());
if(s.equals("ADD"))
Add(n1,n2);
else if(s.equals("SUBTRACT"))
Subtract(n1,n2);
else if(s.equals("MULTIPLY"))
Multiply(n1,n2);
else if(s.equals("DIVIDE"))
Divide(n1,n2);
else if(in.equals("RESET")){
tf1.setText("");
tf2.setText("");
s="";
}else
{
s=in;
}
}
catch (NumberFormatException e1) {
compute.setSelected(true);
JOptionPane.showMessageDialog(this, "Math Error.", "Warning", JOptionPane.INFORMATION_MESSAGE);
}
}
};
public static void main(String[] args) {
new Calculator();
}
}
Thank you in advance!
I just need to put shortcut keys for the compute, reset, and exit buttons.
I think you are confusing a "mnemonic" with an "accelerator".
The "mnemonic" is invoked when the component is focused. You invoke the Action by using the "Alt" key plus the underlined character of the text on the button.
The "accelerator" can be invoked even when the component doesn't have focus by using the specified KeyStroke.
So instead of attempting use Key Bindings directly, you can set the "accelerator" of the Action. When you add the Action to the button the key bindings will be set automatically for you.
Read the section from the Swing tutorial on How to Use Actions for more information
This question already has an answer here:
Add key bindings to JButtons that get their actions from action commands?
(1 answer)
Closed 2 years ago.
I would like to have 2 buttons:
1) BindBTN - When clicked a keyListener/action will listen for key press and find the KeyCode of that key.
2) RunBTN - When clicked an action will wait until the user presses the same key and then preforms runProgram()
RunBTN.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
#SuppressWarnings("serial")
AbstractAction run = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
runProgram();
}
};
RunBTN.getInputMap().put(KeyStroke.getKeyStroke("**bound key**"),
"run");
RunBTN.getActionMap().put("run",
run);
}
});
What should i do for BindBTN?
Okey so i figured it out:
for BindBTN:
BindingBTN.addKeyListener(new KeyAdapter()
{
#Override
public void keyPressed(KeyEvent evtBind)
{
BindCmd = evtBind.getKeyCode();
BindCmdString = KeyEvent.getKeyText(BindCmd);
}
});
and for RunBTN:
RunBTN.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
#SuppressWarnings("serial")
AbstractAction run = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
runProgram();
}
};
RunBTN.getInputMap().put(KeyStroke.getKeyStroke(BindCmdString),
"run");
RunBTN.getActionMap().put("run",
run);
}
});
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());
}
I want to show a popupmenu, while using Metal L&F it will do these behavior.
single click: it printed "pressed" and show menu
double pressed: it printed "pressed" and show menu too.
Yes it is I needed. But when using WindowsLookAndFeel, it not same as those.
when twice pressed it just hide menu and not printed "pressed". why it have difference behavior between two L&F?
import javax.swing.*;
import java.awt.event.*;
public class Popup {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(300, 300);
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception ex) {
ex.printStackTrace();
}
JPopupMenu menu = new JPopupMenu();
menu.add("item");
f.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
System.out.println("pressed");
}
});
f.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
menu.show(f, e.getX(), e.getY());
}
});
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
boolean consumeEvent = UIManager.getBoolean("PopupMenu.consumeEventOnClose");
// Consume the event so that normal processing stops.
if(consumeEvent && !(src instanceof MenuElement)) {
me.consume();
}
I have found the problems, because of this property is different
so end it
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.