Issues with ActionListener (Java)

前端 未结 1 566
后悔当初
后悔当初 2021-01-29 05:33

I am trying to implement action listener on two buttons in JFrame, but the issue is one of the two button is performing both the functions; but i\'ve not configured it to do so.

相关标签:
1条回答
  • 2021-01-29 06:22

    You think the button triggers both the if and else statement but that is not the case. If you would adjust your code in the following way:

    • add a setColor, changeColor or something similar to your MyDrawPanel class
    • adjust the MyDrawPanel#paintComponent method to use a fixed color instead of a random color, and only adjust the color through the method created in the first step
    • your color change button should use the method created in the first step to adjust the color of the MyDrawPanel

    The thing is that paintComponent can be called by Swing itself. It is not only called when you call repaint (which is a good thing, or all code you write for Swing components would be filled with repaint calls).

    Side note: when overriding the paintComponent method I would recommended to call super.paintComponent as well

    0 讨论(0)
提交回复
热议问题