This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Actionlistener in seperate class question  RSS feed

 
Ross Gerard
Ranch Hand
Posts: 53
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I simply want to select b1 with a mouse click and change b2 to random in actionPerformed but having problems with strange error message when I try to: //p1.b1.addActionListener(this); on MyJPanel2 I am not allowed to change anything in MyJPanel1. Exception in Main error





 
Ross Gerard
Ranch Hand
Posts: 53
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This donesnt work unfort.


 
Ross Gerard
Ranch Hand
Posts: 53
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Here is the solution all
 
Campbell Ritchie
Marshal
Posts: 55717
163
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't do arithmetic with Math#random. Use a Random object. There is a long discussion here. Don't use floats for arithmetic. Don't use floats for anything if you can help it.
Don't use if-elses to pick text; it is far neater to use an array, or a List<String>. That also means you can add another activity to the array, e.g. "drinking" without needing to change any other code.
Don't mix tabs and spaces. Don't use so many empty lines (which I have deleted).
Using addActionListener(this) might seem to work when you have one action but when you have several the code expands into a mess of repeated if‑elses which are difficult to maintain. Create one class for each type of action required (or in Java8, a λ).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!