• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Actionlistener in seperate class question

 
Ranch Hand
Posts: 53
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This donesnt work unfort.


 
Ross Gerard
Ranch Hand
Posts: 53
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



Here is the solution all
 
Marshal
Posts: 79177
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 λ).
 
reply
    Bookmark Topic Watch Topic
  • New Topic