Add text to two textfields with JButtons

前端 未结 1 628
無奈伤痛
無奈伤痛 2021-01-21 02:05

If my question wasn\'t very specific, here is what I am trying to do. I have a calculator that has two JTextFields, a JLabel (\"Answer = \"), and a JTextField for the answer.

相关标签:
1条回答
  • 2021-01-21 02:32

    Instead of using an ActionListener you can add an Action to the button. In this case you will want to extend TextAction because it has a method that allows you to get the last focused text component so you can insert the digit into that component. The code would be something like:

    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 讨论(0)
提交回复
热议问题