Java – jbutton changes text of text field

javajbuttonjtextfieldnetbeansswing

I am simply trying to make an employee clock. I have a keypad of numbers 0-9 and a text field. I want to be able to click the numbers and the numbers will appear on the text field. This seems so easy but I can't find any answers for it.

I'm using netbeans and I created the design of the Jframe in the Design.

I added action events to all of the buttons.

I'm calling each button like Btn0 (the button with 0 on it, Btn1, etc etc.

Best Solution

You need to retrieve the JButton on which ActionEvent is fired and then append the text retrieved from the JButton to the JTextField. Here is the short Demo:
enter image description here

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class EClock extends JFrame
{
    JTextField tf;
    public void createAndShowGUI()
    {
        setTitle("Eclock");
        Container c = getContentPane();
        tf = new JTextField(10);
        JPanel cPanel = new JPanel();
        JPanel nPanel = new JPanel();
        nPanel.setLayout(new BorderLayout());
        nPanel.add(tf);
        cPanel.setLayout(new GridLayout(4,4));
        for (int i =0 ; i < 10 ; i++)
        {
            JButton button = new JButton(String.valueOf(i));
            cPanel.add(button);
            button.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    String val = ((JButton)evt.getSource()).getText();
                    tf.setText(tf.getText()+val);
                }
            });
        }
        c.add(cPanel);
        c.add(nPanel,BorderLayout.NORTH);
        setSize(200,250);
        setLocationRelativeTo(null);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    public static void main(String[] args) 
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                EClock ec = new EClock();
                ec.createAndShowGUI();
            }
        });
    }
}
Related Question