2

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

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

        }

    }

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

我从哪里得到代码的。

4

4 回答 4

4

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

在此处输入图像描述

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();
                    }
                }
            }
        }
    }
}
于 2013-04-02T01:13:10.903 回答
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);                     
   }
}
于 2013-04-02T01:14:30.870 回答
1

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

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

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

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

于 2013-04-02T01:57:31.740 回答
0

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

当用户在文本字段中按 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 按钮和文本字段的更多信息:https ://javatutorial.net/jframe-buttons-listeners-text-fields

于 2019-05-05T18:48:56.077 回答