在我试图制作的程序中,有三个文本字段,附有几个按钮(每个按钮代表一个数字)。我试图通过点击按钮(而不是键盘)来输入它。到目前为止,我得到了这个:
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 );
}
}
唯一的问题是,我不知道如何使用我找到的代码(我找到的代码是第二个块)。
答案 0 :(得分:3)
如果您没有“期望”用户使用键盘导航按钮,那么我只会让它们无法对焦。这样,用户可以单击按钮,但当前活动的字段不会失去焦点。用户可以直接在字段中输入或单击小键盘...
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();
}
}
}
}
}
}
答案 1 :(得分: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);
}
}
答案 2 :(得分:1)
我不知道如何使用我找到的代码
您可以从Action创建一个按钮,然后将该按钮添加到GUI。例如:
JButton one = new JButton( new AddDigit("1") );
代码会将文本添加到有焦点的最后一个文本字段中。
答案 3 :(得分: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