java 如何使用按钮在文本字段中输入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15754374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use buttons to type in a text field?
提问by DTHCND
In a program I'm attempting to make, there are three text field accompanied by several buttons (each representing a number). I'm trying to get it so you can type by clicking on the buttons (as opposed to the keyboard). So far, I got this:
在我尝试制作的程序中,有三个文本字段,并带有几个按钮(每个按钮代表一个数字)。我正在尝试获取它,以便您可以通过单击按钮(而不是键盘)来输入。到目前为止,我得到了这个:
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(); }
}
}
}
After searching the Internet, I came across the following code:
在网上搜索后,我遇到了以下代码:
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 );
}
}
The only problem is, I have no clue how to use the code I found (the code I found being the second block).
唯一的问题是,我不知道如何使用我找到的代码(我发现的代码是第二个块)。
回答by MadProgrammer
If you don't "expect" the user to use the keyboard to navigate the buttons, then I would simply make them unfocusable. This way, the user can click the button, but the currently active field will not lose focus. The user can either type directly into the field or click the 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();
}
}
}
}
}
}
回答by Gander7
The essence of what you need to do is to:
1. create a method that appends a number onto the end of the textbox
2. add a Event Listener to each button that calls that method passing the value of the current button to the method.
您需要做的本质是:
1. 创建一个方法,将一个数字附加到文本框的末尾
2. 向每个调用该方法的按钮添加一个事件侦听器,将当前按钮的值传递给该方法。
For Example:
例如:
// 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);
}
}
回答by camickr
I have no clue how to use the code I found
我不知道如何使用我找到的代码
You create a button from the Action and then add the button to your GUI. For example:
您从操作创建一个按钮,然后将该按钮添加到您的 GUI。例如:
JButton one = new JButton( new AddDigit("1") );
The code will add the text to the last text field that had focus.
该代码会将文本添加到具有焦点的最后一个文本字段。
回答by Johnny
Check out this demo code. It will display a basic text field and a text area where the text field is editableand the text area is not editable.
查看此演示代码。它将显示一个基本文本字段和一个文本区域,其中文本字段可编辑而文本区域不可编辑。
When the user presses Enter in the text field, the program copies the text field's contents to the text area, and then selects all the text in the text field.
当用户在文本字段中按 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();
}
});
}
Check out to learn more about JFrame Buttons and Text Fields: https://javatutorial.net/jframe-buttons-listeners-text-fields
查看以了解有关 JFrame 按钮和文本字段的更多信息:https: //javatutorial.net/jframe-buttons-listeners-text-fields