开发者

Java Beginner: the mechanism behind "|" operator in Shell s = new Shell(d, SWT.CLOSE | SWT.RESIZE);

hi I was won开发者_开发问答dering about the mechanism behind the "|" operator in the next code.

Display d = new Display( );
Shell s = new Shell(d, SWT.CLOSE | SWT.RESIZE);

p.s: I already checked the source code, but didn't understand


SWT.CLOSE and SWT.RESIZE are int flags. the | means Binary OR between them which meant for passing both of them.

For example. if RESIZE = 1 (00000001 binary) and CLOSE = 2 (00000010 binary), SWT.CLOSE | SWT.RESIZE = 3 (00000011 binary) and later on the method called will know to respcet them both.

Edit - what's next

If the constructor behaves according to the flags, it might look like this:

public Shell(Display d, int flags)
{
      if ((flags & SWT.CLOSE) > 0)//the close flag is on
      { /*do some stuff*/ };
      if ((flags & SWT.RESIZE) > 0)
      { /*do some stuff to enable resize..*/ };
}

Now, instead of passing many unnecessary arguments to the constructor, we tell it with one argument (flags) many things to do. The first if for example, checks if the CLOSE flag is set in flags: flags = 3 (00000011 binary) (as we set it before) SWT.CLOSE = 2 (00000010 binary) and flags & SWT.CLOSE = 3 & 2 = 00000010 binary which is bigger than zero and is set.


It's the bitwise OR operator.

Using correct integers it can be used to define options. If your integers are - but not necesseraly - set unique bits in an integer it can be used on the accepting method to select options.

Example:

  • Highlight foreground: 001 => 1 (HIGHLIGHT_FG)
  • Highlight background: 010 => 2 (HIGHLIGHT_BG)
  • Bold: 100 => 4 (BOLD)

So oring the constants BOLD | HIGHLIGHT_FG will be 5.

But it can be defined also a HIGHLIGHT_ALL with 011 => 3.


It's the bitwise or operator. In this case it is used for a bitfield, i.e. SWT.CLOSE | SWT.RESIZE sets two bits in an integer variable.


What is your question, exactly?

The pipe operator is a bit-wise inclusive OR operation.

In general when programming, it lets you OR two values bits together. For example,

0001b | 0010b yields 0011.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜