代码之家  ›  专栏  ›  技术社区  ›  user8616404

JTextField从左到右的数字顺序

  •  1
  • user8616404  · 技术社区  · 7 年前

    我正在尝试制作计算器,我对JTextField有一个问题。当我单击数字(JButtons)如1,2,3,4,5时,它们会出现在JTextField上,如54321。那么,我如何将其更改为显示12345而不是54321?

    public void actionPerformed(ActionEvent e) {
    
        JButton clickedButton = (JButton) e.getSource();
    
    
        String displayValue = parent.getDisplayValue();
    
        String clickedBtnValue = clickedButton.getText();
    
        parent.setDisplayValue(clickedBtnValue + displayValue); 
    

    contentPane = new JPanel();
        textField = new JTextField(30);
        textField.setAlignmentX(Component.LEFT_ALIGNMENT);
        contentPane.add(textField);
        textField.setHorizontalAlignment(JTextField.RIGHT);
        textField.setBounds(10, 11, 152, 32);
        textField.setColumns(1);
        textField.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        textField.addActionListener(eng);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 184, 312);
    
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   camickr    7 年前

    你问这个问题之前真的想过这个吗?

    您可以控制您的代码,因此您应该了解您的代码在做什么:

    parent.setDisplayValue(clickedBtnValue + displayValue); 
    

    parent.setDisplayValue(displayValue + clickedBtnValue); 
    

    如果您想要更好的解决方案,可以使用 replaceSelection(...) 方法如所示: How to add a shortcut key for a jbutton in java?