JTextField从左到右的数字顺序

时间:2017-09-15 19:08:28

标签: java swing jframe jtextfield

我正在尝试制作计算器,但我遇到了JTextField的问题。当我点击1,2,3,4,5之类的数字(JButtons)时,它们会出现在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 个答案:

答案 0 :(得分:1)

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

您可以控制代码,因此您应该了解代码的作用:

parent.setDisplayValue(clickedBtnValue + displayValue); 

代码完全按照您的要求执行操作 - 按钮文本将附加到现有文本之前。

如果您不喜欢以这种方式显示,那么您可以尝试:

parent.setDisplayValue(displayValue + clickedBtnValue); 

如果您想要更好的解决方案,可以使用How to add a shortcut key for a jbutton in java?

中演示的replaceSelection(...)方法