Skip to main content

KeyListener does not respond if there is any input in JTextField



I develop a simple MVC Calculator app. I decided to add some functionality by implementing KeyListener in CalculatorView. But this KeyListener only responds when there is no input in JTextField (before any input was made by pushing GUI buttons) or it responds when I press "ESC". I know some people here advice to use KeyBindings instead of KeyListener, but then I need to have 12 KeyBindings in my code (10 for numbers, 1 for ESC and 1 for "." character). Is there any way to make KeyListener to work properly in my app?





And here is the code:







/**

*

* @author Kate Nezdoly

*/

public class CalculatorView implements ActionListener, KeyListener {



private JButton[] operButtons = new JButton[13];

private JButton[] numberButtons = new JButton[12];

private String[] operators = {"C", "(", ")", "+", "-", "*", "/", "^", "cos", "sin",

"tan", "sqrt"};

private String[] numbers = {"1", "2", "3", "4", "5", "6", "7", "8",

"9", "0", ".", "="};



public CalculatorView() {

try {

UIManager.setLookAndFeel(

UIManager.getSystemLookAndFeelClassName());

} catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {

System.err.println(e.getMessage());

}



createAndShowGUI();

}

private JTextField input;

private boolean decimal = true;



private JPanel createContentPane() {

JPanel totalGUI = new JPanel(new BorderLayout(12, 8));

input = new JTextField("0.0", 18);

input.addKeyListener(this);

input.setEditable(false);

input.setBackground(Color.white);

input.setHorizontalAlignment(JTextField.RIGHT);



JPanel action_buttons = new JPanel(new GridLayout(5, 2));



operButtons[0] = new JButton(operators[0]);

action_buttons.add(operButtons[0]);



for (int i = 1; i < operators.length; i++) {

operButtons[i] = new JButton(operators[i]);

operButtons[i].addActionListener(this);

operButtons[i].setActionCommand(operators[i]);

action_buttons.add(operButtons[i]);

}



JPanel number_buttons = new JPanel(new GridLayout(5, 2));



for (int i = 0; i < numbers.length - 1; i++) {

numberButtons[i] = new JButton(numbers[i]);

numberButtons[i].addActionListener(this);

numberButtons[i].setBackground(Color.lightGray);

numberButtons[i].setActionCommand(numbers[i]);

number_buttons.add(numberButtons[i]);

}



numberButtons[11] = new JButton(numbers[11]);

number_buttons.add(numberButtons[11]);



totalGUI.add(input, BorderLayout.PAGE_START);

totalGUI.add(number_buttons, BorderLayout.CENTER);

totalGUI.add(action_buttons, BorderLayout.LINE_END);



totalGUI.setOpaque(true);

return totalGUI;

}



private void createAndShowGUI() {

JFrame frame = new JFrame("Calculator");



frame.setContentPane(createContentPane());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();

frame.setVisible(true);

frame.setSize(300, 190);

frame.setResizable(false);

}



public void actionPerformed(ActionEvent ae) {

String temp = ae.getActionCommand();



if (input.getText().equals("0.0")) {

input.setText("");

}



if (temp.equals(".")) {

if (decimal) {

decimal = false;

input.setText(input.getText() + "" + temp);

}

}

else {

input.setText(input.getText() + "" + temp);

}

}



public void buttonActionListeners(ActionListener al) {

//add "=" action listener

numberButtons[11].setActionCommand(numbers[11]);

numberButtons[11].addActionListener(al);



//add "C" action listener

operButtons[0].setActionCommand(operators[0]);

operButtons[0].addActionListener(al);



}



// Gets the text from the Text Box and converts it into a Double.

public String getFieldText() {

return input.getText();

}



// Sets the text displayed on the Text Box.

public void setFieldText(String message) {

input.setText("" + message);

decimal = true;

}



@Override

public void keyTyped(KeyEvent e) {



}



@Override

public void keyPressed(KeyEvent e) {

if (e.getKeyCode() == 27) {

System.exit(0);

} else if (e.getKeyCode() >= 48 && e.getKeyCode() <= 57) {

if (input.getText().equals("0.0")) {

setFieldText(String.valueOf(e.getKeyChar()));

} else {

setFieldText(input.getText() + e.getKeyChar());



}

}

}



@Override

public void keyReleased(KeyEvent e) {



}





}







Controller class:







public class CalculatorController implements ActionListener {



private CalculatorView view;



public CalculatorController( CalculatorView view) {

this.view = view;

view.buttonActionListeners(this);

}



@Override

public void actionPerformed(ActionEvent e) {

String action = e.getActionCommand();

switch (action) {

case "=":

view.setFieldText(Parser.parse(view.getFieldText()));

break;

case "C":

view.setFieldText("0.0");

break;

}

}



public static void main(String args[]){

CalculatorView calc = new CalculatorView();

CalculatorController contr = new CalculatorController(calc);

}



}




Comments

  1. I think that there isn't any reason for implement KeyListener/KeyBinding,

    1) add as ActionCommand to the JButtons example here

    private String[] numbers = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", "="};


    2) change JTextField to the JFormattedTextField with NumberInstance/Formatter, then there are alowed only Numbers and decimal separator, and no longer there reason for listening from KeyBoard by implement KeyListener/KeyBindings nor parsing/testing for NumberInstance

    3) if is there more than one that one JFormattedTextField (value could be imputed or pasted from ClipBoard) or for example JFormattedTextField and JTextArea (for showing previous calculations) then chaining these fiedls by using DocumentListener

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.