JTextField的“附加”文本

我正在尝试创建一个小的应用程序,其中U输入ID(在JButton的帮助下 – 从0到9 – )然后将已经按下的数字传递给putText-Method然后将其显示在JTextField中 – 问题在于每一个时间我按下我之前按下的那个新数字:s。 有人可以帮助我吗?

public class IdPanel extends JPanel { private JTextField idField; private JLabel idLabel; public IdPanel() { setLayout(new GridBagLayout()); setPreferredSize(new Dimension(500, 70)); idField = new JTextField(20); idField.setFont(new Font("Serif", Font.PLAIN, 20)); idLabel = new JLabel("Enter ID:"); idLabel.setFont(new Font("Serif", Font.PLAIN, 20)); GridBagConstraints gc = new GridBagConstraints(); gc.gridx = 0; gc.gridy = 0; gc.insets = new Insets(9, 9, 9, 9); gc.anchor = GridBagConstraints.CENTER; add(idLabel, gc); gc.gridx = 1; gc.anchor = GridBagConstraints.CENTER; add(idField, gc); } public void putText(String number) { idField.setText(number); } } 

尝试:

 idField.setText(idField.getText()+number); 

在JButton的帮助下 – 从0到9 –

以下是9个按钮的示例:

 import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class CalculatorPanel extends JPanel { private JTextField display; public CalculatorPanel() { Action numberAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { // display.setCaretPosition( display.getDocument().getLength() ); display.replaceSelection(e.getActionCommand()); } }; setLayout( new BorderLayout() ); display = new JTextField(); display.setEditable( false ); display.setHorizontalAlignment(JTextField.RIGHT); add(display, BorderLayout.NORTH); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout( new GridLayout(0, 5) ); add(buttonPanel, BorderLayout.CENTER); for (int i = 0; i < 10; i++) { String text = String.valueOf(i); JButton button = new JButton( text ); button.addActionListener( numberAction ); button.setBorder( new LineBorder(Color.BLACK) ); button.setPreferredSize( new Dimension(50, 50) ); buttonPanel.add( button ); InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStroke.getKeyStroke(text), text); inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text); button.getActionMap().put(text, numberAction); } } private static void createAndShowUI() { // UIManager.put("Button.margin", new Insets(10, 10, 10, 10) ); JFrame frame = new JFrame("Calculator Panel"); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.add( new CalculatorPanel() ); frame.pack(); frame.setLocationRelativeTo( null ); frame.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); } }