Search code examples
javaswingmethodsjframecall

Java Methods when working with Swing - It is possible to call event method in another event method in same class?


so I am new to java and using right now swing. I have an method (first method) that does some code when I type in specific jField and release key. I also have jCheckBox, so when I tick or untick checkbox it does some action, this is second method.

So I want when I tick or untick checkbox make it call my first method and first method must do it's code. But it seems I have problem and I can't call this method fro some reason.

Part of first method:

   private void bruttoTextFieldKeyReleased(java.awt.event.KeyEvent evt) {  
       //code
}

Second method trying to call first method:

private void pensionCheckBoxStateChanged(javax.swing.event.ChangeEventevt) {                                             
       bruttoTextFieldKeyReleased();
}    

Those methods were created with this menu

And this is hint, but I am not sure what I need to do, it required some KeyEvent? I just want launch one method from another, not putting any value and not returning.

Error Hint


Solution

  • To expand a bit on Luvy's comment, and convert it into an answer using your code.

    Right now, the first method takes a KeyEvent, and looks like this:

    private void bruttoTextFieldKeyReleased(java.awt.event.KeyEvent evt) {
      double salaryBrutto = Double.parseDouble(bruttoTextField.getText());
    
      double taxPensRound;
      if (pensionCheckBox.isSelected()) {
        double taxPens = salaryBrutto * TAX_PENS;
        //more code
    

    Going by the screenshots, it looks like you most likely auto-created it from a GUI builder, and are not using the KeyEvent evt parameter. You aren't able to call this method without passing in a KeyEvent, which is why pensionCheckBoxStateChanged cannot call it.

    Luvy's suggestion would be to create a new method out of the bruttoTextFieldKeyReleased button, so afterwords you would have two methods:

    private void bruttoTextFieldKeyReleased(java.awt.event.KeyEvent evt) {
      calculatePensionInformation();
      //maybe do something with evt later on
    }
    

    and

    private void calculatePensionInformation() {
      double salaryBrutto = Double.parseDouble(bruttoTextField.getText());
    
      double taxPensRound;
      if (pensionCheckBox.isSelected()) {
        double taxPens = salaryBrutto * TAX_PENS;
        //more code
    

    }

    At this point, you could change your existing second method to be:

    private void pensionCheckBoxStateChanged(javax.swing.event.ChangeEventevt) {                                             
       calculatePensionInformation();
    }    
    

    And it would work as expected, since calculatePensionInformation requires no parameters, and you are passing in no parameters.