如何通过使用动作监听器和动作事件让JButtons在JTextField中打印整数



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

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

如果用户点击'jbtOne' 4次。JTextField应该显示1111。我的问题是,按钮是没有响应的代码行:

addActionListener(listener)

如何让JButtons在JTextField中打印整数?我已经得到了这个工作之前,但已经未能让它再次工作后,在一个更用户友好的外观与这一行代码:

 private static final String[][] STANDARD_BTN_TEXTS = 
{
    {"1", "2", "3"},
    {"4", "5", "6"},
    {"7", "8", "9"},
    { "0" }
谁能给我指个正确的方向?任何帮助将非常感激!
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

在我看来,您没有将jbtOne添加到可见面板。您的createBtnPanel方法创建自己的按钮并将它们添加到面板中,而不需要任何操作侦听器。

尝试更改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);
    }
}

如果你不明白它的作用或有任何问题,请告诉我。

如果您使用的是Java 8,那么这段代码也可以大大简化,但我假定您不想让我的答案直截了当。

在下面的代码中,我让按钮侦听器响应并输出单击按钮的文本以显示在文本字段中。所有的更改都以/****开头,以解释我所做的一切。

/*
 * 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:

您的监听器正在使用passwordField,但似乎您已经添加了一个文本字段到您的面板,要么使用passwordField或jtfNumber1。

相关内容

  • 没有找到相关文章

最新更新