MasterWhipper
MasterWhipper

Reputation: 23

How does the implementation of this bitwise operator make sense?

In an earlier question regarding how to maximize the JFrame I saw this bit of code and it worked. I took out the

name.getExtendedState()

and it still worked? What does the use of the "getter" and the OR symbol accomplish?

name.setExtendedState(name.getExtendedState()|JFrame.MAXIMIZED_BOTH);

Upvotes: 0

Views: 103

Answers (3)

Matt Coubrough
Matt Coubrough

Reputation: 3829

Quoted from Wikipedia: http://en.wikipedia.org/wiki/Bitwise_operation#OR

A bitwise OR takes two bit patterns of equal length and performs the logical inclusive OR operation on each pair of corresponding bits. The result in each position is 1 if the first bit is 1 or the second bit is 1 or both bits are 1; otherwise, the result is 0. For example:

   0101 (decimal 5)
OR 0011 (decimal 3)
 = 0111 (decimal 7)

So if getExtendedState() is returning a number made up of binary flags (ie. a bit field)... ORing it (using the pipe operator | ), is simply keeping ALL the existing flags in the object's state and also setting the bit/s that correspond to the state JFrame.MAXIMIZED_BOTH.

This is because ORing sets a bit to 1 if it is 1 in either the first operand OR the second operand.

Hope that helps explain it.

Upvotes: 0

TyeH
TyeH

Reputation: 1

From the API getExtendedState() :

Gets the state of this frame. The state is represented as a bitwise mask.
NORMAL 
Indicates that no state bits are set.
ICONIFIED
MAXIMIZED_HORIZ
MAXIMIZED_VERT
MAXIMIZED_BOTH 
Concatenates MAXIMIZED_HORIZ and MAXIMIZED_VERT.

The logical OR will combine the returned value with the value of JFrame.MAXIMIZED_BOTH

for example if NORMAL was 10110 and MAXIMIZED_BOTH was 01100, ORing the two would yeild 1110

Normal  10110
MaxBoth 01100
Result  11110

Upvotes: 0

C. K. Young
C. K. Young

Reputation: 223123

Using name.getExtendedState()|JFrame.MAXIMIZED_BOTH means that you're adding MAXIMIZED_BOTH to the existing extended state. If you say only JFrame.MAXIMIZED_BOTH, that means you're replacing the extended state with only that bit, and throwing away anything in the current extended state.

Upvotes: 5

Related Questions