Java 如何使用按钮键入文本字段?

Java 如何使用按钮键入文本字段?,java,swing,user-interface,keyboard,awt,Java,Swing,User Interface,Keyboard,Awt,在我试图制作的一个程序中,有三个文本字段和几个按钮(每个按钮代表一个数字)。我正在尝试获取它,以便您可以通过单击按钮(而不是键盘)进行键入。到目前为止,我得到了: import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.text.*; public class GUI extends JFrame { private JButton[] numPad = new JBut

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

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(); }

            }


    }

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

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

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();
                    }
                }
            }
        }
    }
}

导入java.awt.BorderLayout;
导入java.awt.Component;
导入java.awt.Dimension;
导入java.awt.EventQueue;
导入java.awt.GridBagConstraints;
导入java.awt.GridBagLayout;
导入java.awt.GridLayout;
导入java.awt.KeyboardFocusManager;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入javax.swing.JTextField;
导入javax.swing.UIManager;
导入javax.swing.UnsupportedLookAndFeelException;
导入javax.swing.text.JTextComponent;
公共类TestNumPad{
公共静态void main(字符串[]args){
新TestNumPad();
}
公共TestNumPad(){
invokeLater(新的Runnable(){
@凌驾
公开募捐{
试一试{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(ClassNotFoundException |实例化Exception | IllegalacessException |不支持ookandfeelException ex){
}
JFrame=新JFrame(“测试”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(新的BorderLayout());
frame.add(newtestpane());
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}
});
}
公共类TestPane扩展了JPanel{
公共测试窗格(){
setLayout(新的GridBagLayout());
GridBagConstraints gbc=新的GridBagConstraints();
gbc.gridwidth=GridBagConstraints.rements;
JTextField=新的JTextField(10);
添加(字段,gbc);
添加(新的NumPad(),gbc);
field.requestFocusInWindow();
}
@凌驾
公共维度getPreferredSize(){
返回新维度(200200);
}
}
公共类NumPad扩展了JPanel{
私有ActionHandler ActionHandler;
公共货币(){
setLayout(新的GridLayout(4,3));
actionHandler=新的actionHandler();
对于(int-index=1;index<10;index++){
添加(创建按钮(索引));
}
添加(新JPanel());
添加(createButton(0));
添加(新JPanel());
}
受保护的JButton createButton(int索引){
JButton btn=新的JButton(String.valueOf(index));
btn.setFocusable(假);
btn.addActionListener(actionHandler);
返回btn;
}
公共类ActionHandler实现ActionListener{
@凌驾
已执行的公共无效操作(操作事件e){
对象源=e.getSource();
if(JButton的源实例){
JButton btn=(JButton)源;
试一试{
int value=Integer.parseInt(btn.getText().trim());
Component comp=KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if(JTextComponent的组件实例){
JTextComponent tc=(JTextComponent)comp;
tc.setText(tc.getText()+值);
}
}捕获(异常扩展){
exp.printStackTrace();
}
}
}
}
}
}

您需要做的本质是:
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);                     
   }
}
我不知道如何使用我找到的代码

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

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

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

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

当用户在文本字段中按Enter键时,程序将文本字段的内容复制到文本区域,然后选择文本字段中的所有文本

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按钮和文本字段的更多信息:

因此,用户可以“单击”数字键盘,而不是手动在字段中输入值?或者你想让数字键盘像键盘上的数字键盘一样,当他们输入一个数字时,它会触发相应的按钮?@Reimeus第一块代码就是我的代码。我只是想知道如何让第二个块与第一个块一起工作,这样他们就可以单击numpad(键盘仍然可以正常工作)。如果他们使用的是永远不会与这个虚拟键盘交互的键盘,我只需将按钮设为un-focusable@MadProgrammer那么,用户应该与之交互(如果他们选择这样做的话). 例如,如果他们的键盘坏了,这是一种“伪造”键盘的好方法;)
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();
            }
        });
    }