• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to initialize a field, after it has been initialized on the constructor?  RSS feed

 
rick pine
Ranch Hand
Posts: 90
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Im doing something wrong here, i think my problem its at the step " Initialize the field clickImage with a new ImageIcon that is based on Image3". My understanding is that the constructor does the initialization,  so after i create
the constructor, i cant go outside of it and say  field = new object... , i tried to initialize inside of the constructor but i got errors. The instructions do not say anything about initializing the fields on the ctor, it only says to change the tittle. So i also tried not initializing the fields on the ctor, and initializing at the same time as the fields are declared but it doesn't like this approach either. Can i get a hint about how to resolve this.


1- Create two final fields: imgButton of type JButton clickImage of type Icon
2- In the constructor do the following:
3- Set the title to Lab Button
4- Create two local variables of type Icon: image1 and image2.
5- Initialize them with a new ImageIcon base on Image1 and Image2 - like this:
   Icon image1 = new ImageIcon(getClass().getResource("Image1.png"));
6- Initialize the field clickImage with a new ImageIcon that is based on Image3
7- Initialize the field imgButton with a new JButton that accepts image1 as the only argument
8- Call the method setRolloverIcon on imgButton and pass image2 as roll-over icon
9- Add the imgButton to this (ImageButton, which is a JFrame)




 
rick pine
Ranch Hand
Posts: 90
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
never mind guys i wasnt reading the instructions properly, dumb me. I have marked the question as resolved.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done sorting it out, but what was the error? Your original code does look incorrect because you are initialising the same field twice. Also please work out which order the two initialisations are executed. Do you know the rules about initialising final fields? Note the link to §4.12.4 in that Java® Language Specification (=JLS) link. Remember the JLS can be difficult to read.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!