Search code examples
javaswingjbuttonactionlistenerjtextfield

jbuttons and a jtextfield that has an action listener


I have a keypad made up of jbuttons and a jtextfield that has an action listener. When I press the button the number shows in the textfield but the next number overwrites it. Could anyone tell me how to append the text to the length 13 numbers and when it get's there to carriage return.

If I use the keyboard to enter numbers I can enter a String of numbers but not from the buttons.

I am using:

    JButton buttonNo2 = new JButton("2");
    buttonNo2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            textfield.setText("2");
        }

buttonNo1.setBounds(11, 18, 50, 50);
    keyboardPanel.add(buttonNo2);
    buttonNo1.setForeground(Color.BLUE);
    buttonNo1.setFont(new Font("Perpetua", Font.BOLD, 20));

Solution

  • Try using something like

    textfield.setText(textfield.getText() + "2");
    

    instead of textfield.setText("2");

    setText does just that, sets the text of the text field to the value you specified.

    Also buttonNo1.setBounds(11, 18, 50, 50); looks like you're trying to do without a layout manager. Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

    You could also make it much simpler for yourself, and use the Action API instead, which would save you a not lot of repeated typing...

    public class NumberAction extends AbstractAction {
    
        private JTextField field;
        private int number;
    
        public NumberAction(JTextField field, int number) {
            this.field = field;
            this.number = number;
            putValue(NAME, Integer.toString(number));
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            Document doc = field.getDocument();
            try {
                doc.insertString(doc.getLength(), Integer.toString(number), null);
            } catch (BadLocationException ex) {
                ex.printStackTrace();
            }
        }
    
    }
    

    Then you would just need to add each button as required...

    add(new JButton(new NumberAction(textfield, 1)));
    add(new JButton(new NumberAction(textfield, 2)));
    add(new JButton(new NumberAction(textfield, 3)));
    

    See How to Use Actions for more details