Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Swing in multiple classes?

 
Michael Duff
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wondered if this question belongs to the Swing/Gui part of the forum, but the question itself probably belongs here. If not I'm sorry for posting it here .

I have two classes, and I want to set a specific value in my JTextField and my JLabel in my GUI. Is there any way I could use the setText functions in my other class too, or do I have to rely on returning Strings to the GUI class (which I'm not very fond of, because my other class will be quite complex)?

GUI class:


And in my other class I have

 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It doesn't look right to add a Listener to a Car class. You should add said ActionListener to a button or similar.
It looks very peculiar and non-object-oriented, what you have about "BMW". It appears that BMWs are special cars; if you have a BMW anywhere the text fields will say BMW even if the present car is a VW.

Let's get the Car class sorted out, then move it to the GUIs forum to sort out the Listeners.
 
Michael Duff
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just made it like that as an example (not very good, I admit).

What I'm interested in is if I can change , for example , a JLable text from both of my classes (Is that even possible?).

Cheers,

Michael
 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. You would have to pass a reference to that JLabel.

You can also set those JLabels as fields of the "View" class, then provide setLeftLabelText(String text) methods.

I think I probably prefer the second option; it is better encapsulation which makes each class "take care of itself."
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic