如何使用动作监听器和动作事件让JButton在JTextField中打印整数? [英] How to get JButtons to print integers in a JTextField by using Action Listener and Action Event?

查看:91
本文介绍了如何使用动作监听器和动作事件让JButton在JTextField中打印整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个虚拟的ATM GUI界面,以通过键盘输入几个数字.我在用户单击任何按钮后让程序显示数字时遇到麻烦.为了节省时间,我只创建了一个按钮:

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]);

因此,如果用户单击"jbtOne",则说4次. JTextField应该显示1111.我的问题是该按钮对代码行无响应:

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)

如何让JButton在JTextField中打印整数?我以前已经使它工作了,但是此行代码添加了更加用户友好的外观之后,却使它无法再次工作:

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

推荐答案

在下面的代码中,我使按钮侦听器响应并输出单击的按钮的文本以显示在文本字段中. 所有更改都以/****开始记录,以解释我的所作所为.

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

我需要更好地了解您希望通过密码字段和操作侦听器实现的功能,因此,如果需要,我可以尝试为您提供进一步的帮助. (0:

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:

这篇关于如何使用动作监听器和动作事件让JButton在JTextField中打印整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆