【问题标题】:How to use buttons to type in a text field?如何使用按钮在文本字段中输入内容?
【发布时间】:2013-03-23 04:08:35
【问题描述】:

在我正在尝试制作的程序中,有三个文本字段伴随着几个按钮(每个代表一个数字)。我正在尝试获取它,以便您可以通过单击按钮(而不是键盘)来输入。到目前为止,我得到了这个:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.text.*;

public class GUI extends JFrame {

    private JButton[] numPad = new JButton[10];
    private JTextField totalBill = new JTextField();
    private JTextField totalPeople = new JTextField();
    private JTextField tipPercentage = new JTextField();
    private JTextField tipAmount = new JTextField();
    private JTextField grandTotal = new JTextField();
    private JTextField totalPerPerson = new JTextField();
    private JButton doneButton = new JButton("Done");
    private JButton clearButton = new JButton("Clear");
    ////////////////////////////////////////////////////////////////////////
    private JPanel superContainer;
    private JPanel container;
    private JPanel panel1 = new JPanel();
    private JPanel panel2 = new JPanel();

    public GUI() {

            //Set JFrame title.
            super("Tip Calculator");

            superContainer = new JPanel();
            superContainer.setLayout(new BoxLayout(superContainer, BoxLayout.Y_AXIS));

    //Create a container to hold two GridLayouts beside one another.
            container = new JPanel();
            container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));

    //Create panels to be placed in container panel.
            panel1.setPreferredSize(new Dimension(500, 250));
            panel1.setLayout(new GridLayout(4,3,10,10));
            panel2.setPreferredSize(new Dimension(500, 250));
            panel2.setLayout(new GridLayout(7,2,10,10));

            //Populate all the JButtons for the numPad.
            for (int i=0; i<=9; i++) {
                numPad[i] = new JButton(Integer.toString(i));
            }

            //Place each numPad button on the first JPanel.
            for (int i=1; i<=9; i++) {
                panel1.add(numPad[i]);
            }
            panel1.add(numPad[0]);

            //Populate second GridLayout.
            panel2.add(new JLabel("Total Bill: "));
            panel2.add(totalBill);
            panel2.add(new JLabel("Total People: "));
            panel2.add(totalPeople);
            panel2.add(new JLabel("Total Percentage: "));
            panel2.add(tipPercentage);
            panel2.add(doneButton);
            panel2.add(clearButton);
            panel2.add(new JLabel("Tip Amount: "));
            panel2.add(tipAmount);
            panel2.add(new JLabel("Grand Total: "));
            panel2.add(grandTotal);
            panel2.add(new JLabel("Total/Person: "));
            panel2.add(totalPerPerson);
            grandTotal.setEditable(false);
            tipAmount.setEditable(false);
            totalPerPerson.setEditable(false);


            //Add the first GridLayout panel to the container.
            container.add(panel1);
            //Create a space between the GridLayout panels.
            container.add(Box.createRigidArea(new Dimension(30,0)));
            //Add the second GridLayout panel to the container.
            container.add(panel2);

            //Same as above but with title ontop and container panel below.
            superContainer.add(new JLabel("Title"));
            superContainer.add(Box.createRigidArea(new Dimension(0,30)));
            superContainer.add(container);

            //The panel the JFrame uses.
            this.setContentPane(superContainer);

            TheHandler handler = new TheHandler();
            doneButton.addActionListener(handler);
            clearButton.addActionListener(handler);

    }

    private class TheHandler implements ActionListener {

            public void actionPerformed(ActionEvent e) {

                   if (e.getSource()==doneButton) {
                            tipAmount.setText(Double.toString(Double.parseDouble(totalBill.getText()) * (Double.parseDouble(tipPercentage.getText()) / 100)));
                            grandTotal.setText(Double.toString(Double.parseDouble(tipAmount.getText()) + Double.parseDouble(totalBill.getText())));
                            totalPerPerson.setText(Double.toString(Double.parseDouble(grandTotal.getText()) / Double.parseDouble(totalPeople.getText()))); }
                    else if (e.getSource()==clearButton) {
                            grandTotal.setText("");
                            tipAmount.setText("");
                            totalPerPerson.setText("");
                            totalBill.setText("0");
                            tipPercentage.setText("0");
                            totalPeople.setText("1");
                            totalBill.requestFocus();
                            totalBill.selectAll(); }

            }


    }

}

在网上搜索后,发现如下代码:

    private class AddDigit extends TextAction {
        private String digit;

        public AddDigit(String digit) {

            super( digit );
            this.digit = digit;

        }

        public void actionPerformed(ActionEvent e) {

            JTextComponent component = getFocusedComponent();
            component.replaceSelection( digit );

        }

    }

唯一的问题是,我不知道如何使用我找到的代码(我找到的代码是第二个块)。

Where I got the code from.

【问题讨论】:

  • 因此,用户可以“单击”数字键盘,而不是手动在字段中输入值?或者你想让数字键盘像键盘数字键盘一样,当他们输入一个数字时,它会触发相应的按钮?
  • @Reimeus 第一个代码块是我的代码。我只是好奇如何让第二个块与第一个块一起工作。
  • @MadProgrammer 所以他们可以点击小键盘(键盘仍然可以使用)。
  • 如果他们使用的永远不会与这个虚拟键盘交互,我只会让按钮无法聚焦
  • @MadProgrammer 好吧,用户应该与它进行交互(如果他们愿意的话)。这种用法的一个例子是他们的键盘坏了。

标签: java swing user-interface keyboard awt


【解决方案1】:

如果您不“期望”用户使用键盘来导航按钮,那么我只会让它们无法聚焦。这样,用户可以点击按钮,但当前活动的字段不会失去焦点。用户可以直接在字段中键入或单击小键盘...

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.JTextComponent;

public class TestNumPad {

    public static void main(String[] args) {
        new TestNumPad();
    }

    public TestNumPad() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            JTextField field = new JTextField(10);
            add(field, gbc);
            add(new NumPad(), gbc);
            field.requestFocusInWindow();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }
    }

    public class NumPad extends JPanel {

        private ActionHandler actionHandler;

        public NumPad() {
            setLayout(new GridLayout(4, 3));
            actionHandler = new ActionHandler();
            for (int index = 1; index < 10; index++) {
                add(createButton(index));
            }
            add(new JPanel());
            add(createButton(0));
            add(new JPanel());
        }

        protected JButton createButton(int index) {
            JButton btn = new JButton(String.valueOf(index));
            btn.setFocusable(false);
            btn.addActionListener(actionHandler);
            return btn;
        }

        public class ActionHandler implements ActionListener {

            @Override
            public void actionPerformed(ActionEvent e) {
                Object source = e.getSource();
                if (source instanceof JButton) {
                    JButton btn = (JButton) source;
                    try {
                        int value = Integer.parseInt(btn.getText().trim());
                        Component comp = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
                        if (comp instanceof JTextComponent) {
                            JTextComponent tc = (JTextComponent) comp;
                            tc.setText(tc.getText() + value);
                        }
                    } catch (Exception exp) {
                        exp.printStackTrace();
                    }
                }
            }
        }
    }
}

【讨论】:

  • 这是“伪造”它的好方法;)
【解决方案2】:

您需要做的事情的本质是:
1. 创建一个将数字附加到文本框末尾的方法
2. 为调用该方法的每个按钮添加一个事件监听器,将当前按钮的值传递给该方法。

例如:

// Method to Append Number to Textbox
public void addNumberToTextBox(int currentVal) {
     txtOutputBox.Value = txtOutputBox.Value + currentVal
} 

// Initialize Some Buttons 
JButton btnOne = new JButton("1");
JButton btnTwo = new JButton("2");
JButton btnThree = new JButton("3");

// Add an ActionListener to the buttons
ButtonHandler handler = new ButtonHandler();
btnOne.addActionListener(handler);
btnTwo.addActionListener(handler);
btnThree.addActionListener(handler);

// Class to deal with when a button is pressed
private class ButtonHandler implements ActionListener {
   public void actionPerformed(ActionEvent e) {
      // Converst the number to int
      int num = Integer.parseInt(e.getSource().Value);
      // Call the method
      addNumberToTextBox(num);                     
   }
}

【讨论】:

    【解决方案3】:

    我不知道如何使用我找到的代码

    您从操作创建一个按钮,然后将该按钮添加到您的 GUI。例如:

    JButton one = new JButton( new AddDigit("1") );
    

    代码会将文本添加到最后一个具有焦点的文本字段。

    【讨论】:

      【解决方案4】:

      查看此演示代码。它将显示一个基本文本字段和一个文本区域,其中 文本字段可编辑文本区域不可编辑

      当用户在文本域中按下回车时,程序将文本域的内容复制到文本区域,然后选择文本域中的所有文本。

      import java.awt.*;
      import java.awt.event.*;
      import javax.swing.*;
      
      public class TextDemo extends JPanel implements ActionListener {
          protected JTextField textField;
          protected JTextArea textArea;
          private final static String newline = "\n";
      
          public TextDemo() {
              super(new GridBagLayout());
      
              textField = new JTextField(20);
              textField.addActionListener(this);
      
              textArea = new JTextArea(5, 20);
              textArea.setEditable(false);
              JScrollPane scrollPane = new JScrollPane(textArea);
      
              //Add Components to this panel.
              GridBagConstraints c = new GridBagConstraints();
              c.gridwidth = GridBagConstraints.REMAINDER;
      
              c.fill = GridBagConstraints.HORIZONTAL;
              add(textField, c);
      
              c.fill = GridBagConstraints.BOTH;
              c.weightx = 1.0;
              c.weighty = 1.0;
              add(scrollPane, c);
          }
      
          public void actionPerformed(ActionEvent evt) {
              String text = textField.getText();
              textArea.append(text + newline);
              textField.selectAll();
      
              //Make sure the new text is visible, even if there
              //was a selection in the text area.
              textArea.setCaretPosition(textArea.getDocument().getLength());
          }
      
          /**
           * Create the GUI and show it.  For thread safety,
           * this method should be invoked from the
           * event dispatch thread.
           */
          private static void createAndShowGUI() {
              //Create and set up the window.
              JFrame frame = new JFrame("TextDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      
              //Add contents to the window.
              frame.add(new TextDemo());
      
              //Display the window.
              frame.pack();
              frame.setVisible(true);
          }
      
          public static void main(String[] args) {
              //Schedule a job for the event dispatch thread:
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                  public void run() {
                      createAndShowGUI();
                  }
              });
          }
      

      查看以了解有关 JFrame 按钮和文本字段的更多信息:https://javatutorial.net/jframe-buttons-listeners-text-fields

      【讨论】:

        猜你喜欢
        • 2021-02-16
        • 2015-07-08
        • 1970-01-01
        • 2011-01-25
        • 1970-01-01
        • 1970-01-01
        • 2011-04-30
        • 2022-01-23
        • 2011-05-04
        相关资源
        最近更新 更多