How to get JButtons to print integers in a JTextField by using Action Listener and Action Event?

99封情书 提交于 2019-12-11 16:25:55

问题


I am trying to create and hypothetical ATM GUI interface to enter in a couple of numbers through a keypad. I am having trouble having the program display the numbers after the user clicks any of the buttons. I have only created one button for time sake:

public JButton jbtOne = new JButton(STANDARD_BTN_TEXTS[0][0]);

So if the user clicks 'jbtOne' say 4 times. The JTextField should display 1111. My problem is that the button is unresponsive to the line of code:

addActionListener(listener)

How do you get JButtons to print integers in a JTextField? I have gotten this to work before, but have since failed to get it to work again after adding in a more user friendly look with this line of code:

 private static final String[][] STANDARD_BTN_TEXTS = 
{
    {"1", "2", "3"},
    {"4", "5", "6"},
    {"7", "8", "9"},
    { "0" }

Can someone point me in the right direction? Any help would be much appreciated!

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JPasswordField;

public class TerminalATM extends JFrame
{
private JPanel panel;
public final JPasswordField passwordField = new JPasswordField(2);
private static final String[][] STANDARD_BTN_TEXTS = 
{
    {"1", "2", "3"},
    {"4", "5", "6"},
    {"7", "8", "9"},
    { "0" }
};
private static final int GAP = 5;
private static final Font BTN_FONT = new Font(Font.DIALOG, Font.BOLD, 20);
public JButton jbtOne = new JButton(STANDARD_BTN_TEXTS[0][0]);
 private JTextField jtfNumber1 = new JTextField(8);//Define Number Field

public TerminalATM()
{       
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null); 

    JPanel standardPanel = createBtnPanel(STANDARD_BTN_TEXTS, "KeyPad");
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(0, 1));
    buttonPanel.add(jtfNumber1, BorderLayout.NORTH);
    buttonPanel.add(standardPanel, BorderLayout.SOUTH);



    BtnListener listener = new BtnListener();
    jbtOne.addActionListener(listener);

    TextFieldHandler handler = new TextFieldHandler();
    passwordField.addActionListener(handler);

    add(buttonPanel, BorderLayout.LINE_START);
    setSize(450, 500);
    setVisible(true);
}

//Create Unique Rows of Buttons
private JPanel createBtnPanel(String[][] texts, String title) {
    JPanel btnPanel = new JPanel();
    int rows = texts.length;
    int cols = texts[0].length;
    btnPanel.setLayout(new GridLayout(rows, cols, GAP, GAP));
    for (int row = 0; row < texts.length; row++) {
        for (int col = 0; col < texts[row].length; col++) {
            JButton btn = new JButton(texts[row][col]);
            btn.setFont(BTN_FONT);
            btnPanel.add(btn);
        }
    }
    btnPanel.setBorder(BorderFactory.createTitledBorder(title));
    return btnPanel;
  }


  private class TextFieldHandler implements ActionListener
 {

  @Override
  public void actionPerformed(ActionEvent event)
  {
  String string = "";

 if(event.getSource()==passwordField)
 string = String.format("textField1: %s", event.getActionCommand());
 }
 } 

/**** Create Button Listener and Action Listener ****/
 class BtnListener implements ActionListener 
{
    @Override
 public void actionPerformed(ActionEvent e)
{
      /* This is where we would set each button to the action event */
      /* Only Button one for brevity */
   int int1=0;
 if(e.getSource().equals(jbtOne))
{
     int1 = 1;
  passwordField.setText(String.valueOf(int1));

  }
 }
 }


public static void main(String[] args)
{
    SwingUtilities.invokeLater(new Runnable()
    {
    public void run()
    {
    new TerminalATM();
    }
    });
   }
 }//EndTerminalATM

回答1:


In the following code I got the button listener to respond and output the text of the clicked button to show in the text field. All changes are documented starting with /****, to explain what I did.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package logging;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class TerminalATM extends JFrame
{
    private JPanel panel;
    public final JPasswordField passwordField = new JPasswordField(2);
    private static final String[][] STANDARD_BTN_TEXTS =
        {
        {"1", "2", "3"},
        {"4", "5", "6"},
        {"7", "8", "9"},
        { "0" }
        };
    private static final int GAP = 5;
    private static final Font BTN_FONT = new Font(Font.DIALOG, Font.BOLD, 20);
    /**** what is the purpose of this JButton ? */
    public JButton jbtOne = new JButton(STANDARD_BTN_TEXTS[0][0]);
    private JTextField jtfNumber1 = new JTextField(8);//Define Number Field

    public TerminalATM()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel standardPanel = createBtnPanel(STANDARD_BTN_TEXTS, "KeyPad");
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(0, 1));
        buttonPanel.add(jtfNumber1, BorderLayout.NORTH);
        buttonPanel.add(standardPanel, BorderLayout.SOUTH);

        /**** The action listener should go on the button which is pressed
         see createBtnPanel  */
//      BtnListener listener = new BtnListener();
//      jbtOne.addActionListener(listener);

        /**** what is the purpose of this JPasswordField ?
         it is not being added to any JPanel */
        TextFieldHandler handler = new TextFieldHandler();
        passwordField.addActionListener(handler);

        add(buttonPanel, BorderLayout.LINE_START);
        setSize(450, 500);
        setVisible(true);
    }

    //Create Unique Rows of Buttons
    private JPanel createBtnPanel(String[][] texts, String title) {
        JPanel btnPanel = new JPanel();
        int rows = texts.length;
        int cols = texts[0].length;
        btnPanel.setLayout(new GridLayout(rows, cols, GAP, GAP));

        /**** create the listener */
        BtnListener listener = new BtnListener();
        for (String[] text : texts) {
            for (String element : text) {
                JButton btn = new JButton(element);
                btn.setFont(BTN_FONT);

                /**** add the listener to each button*/
                btn.addActionListener(listener);
                btnPanel.add(btn);
            }
        }
        btnPanel.setBorder(BorderFactory.createTitledBorder(title));
        return btnPanel;
    }


    private class TextFieldHandler implements ActionListener
    {

        @Override
        public void actionPerformed(ActionEvent event)
        {
            String string = "";

            if(event.getSource()==passwordField) {
                string = String.format("textField1: %s", event.getActionCommand());
            }
        }
    }

    /**** Create Button Listener and Action Listener ****/
    class BtnListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {

            /* This is where we would set each button to the action event */
            /* Only Button one for brevity */

            /**** what is the purpose of it ?   int int1=0; */

            /****  the event is generated by the button created in
             createBtnPanel so e.getSource()  can not be equal to
             jbtOne. It should be an instance of JButton  */

            if(e.getSource() instanceof JButton)
            {
                /**** get the JButton clicked */
                JButton button = (JButton) e.getSource() ;
                /**** display its text on the text field */
                jtfNumber1.setText(button.getText());
            }
        }
    }


    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                /**** new MultiplePanels(); is un defined */
                new TerminalATM();
            }
        });
    }

}//EndTerminalATM

I need to better understand what is the functionality you want to achieve with the password field and action listener, so I can try to help you further, if needed. (0:




回答2:


It looks to me that you are not adding jbtOne to the visible panel. Your createBtnPanel method creates its own buttons and adds them to the panel without any action listeners.

Try changing the following lines of the inner loop of createBtnPanel:

for (int row = 0; row < texts.length; row++) {
    for (int col = 0; col < texts[row].length; col++) {
        final String text = texts[row][col];
        final JButton btn = new JButton(text);
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ev) {
                passwordField.setText(text);
            }
        });
        btn.setFont(BTN_FONT);
        btnPanel.add(btn);
    }
}

Let me know if you don't understand what this does or have any problems with it.

This code can also be significantly simplified if you are using Java 8 but I'll assume you aren't to keep my answer straightforward.




回答3:


Your listeners are using passwordField however it seems you have added a text field to your panel, either use the passwordField or jtfNumber1.



来源:https://stackoverflow.com/questions/31420512/how-to-get-jbuttons-to-print-integers-in-a-jtextfield-by-using-action-listener-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!