Example usage for java.lang Math max

List of usage examples for java.lang Math max

Introduction

In this page you can find the example usage for java.lang Math max.

Prototype

@HotSpotIntrinsicCandidate
public static double max(double a, double b) 

Source Link

Document

Returns the greater of two double values.

Usage

From source file:TreeTableBarChart.java

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    shell.setText("Show results as a bar chart in Tree");
    final Tree tree = new Tree(shell, SWT.BORDER);
    tree.setHeaderVisible(true);/*www  .j  a  v  a 2s  .c o m*/
    tree.setLinesVisible(true);
    TreeColumn column1 = new TreeColumn(tree, SWT.NONE);
    column1.setText("Bug Status");
    column1.setWidth(100);
    final TreeColumn column2 = new TreeColumn(tree, SWT.NONE);
    column2.setText("Percent");
    column2.setWidth(200);
    String[] states = new String[] { "Resolved", "New", "Won't Fix", "Invalid" };
    String[] teams = new String[] { "UI", "SWT", "OSGI" };
    for (int i = 0; i < teams.length; i++) {
        TreeItem item = new TreeItem(tree, SWT.NONE);
        item.setText(teams[i]);
        for (int j = 0; j < states.length; j++) {
            TreeItem subItem = new TreeItem(item, SWT.NONE);
            subItem.setText(states[j]);
        }
    }

    /*
     * NOTE: MeasureItem, PaintItem and EraseItem are called repeatedly.
     * Therefore, it is critical for performance that these methods be as
     * efficient as possible.
     */
    tree.addListener(SWT.PaintItem, new Listener() {
        int[] percents = new int[] { 50, 30, 5, 15 };

        public void handleEvent(Event event) {
            if (event.index == 1) {
                TreeItem item = (TreeItem) event.item;
                TreeItem parent = item.getParentItem();
                if (parent != null) {
                    GC gc = event.gc;
                    int index = parent.indexOf(item);
                    int percent = percents[index];
                    Color foreground = gc.getForeground();
                    Color background = gc.getBackground();
                    gc.setForeground(display.getSystemColor(SWT.COLOR_RED));
                    gc.setBackground(display.getSystemColor(SWT.COLOR_YELLOW));
                    int width = (column2.getWidth() - 1) * percent / 100;
                    gc.fillGradientRectangle(event.x, event.y, width, event.height, true);
                    Rectangle rect2 = new Rectangle(event.x, event.y, width - 1, event.height - 1);
                    gc.drawRectangle(rect2);
                    gc.setForeground(display.getSystemColor(SWT.COLOR_LIST_FOREGROUND));
                    String text = percent + "%";
                    Point size = event.gc.textExtent(text);
                    int offset = Math.max(0, (event.height - size.y) / 2);
                    gc.drawText(text, event.x + 2, event.y + offset, true);
                    gc.setForeground(background);
                    gc.setBackground(foreground);
                }
            }
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:org.eclipse.swt.snippets.Snippet283.java

public static void main(String[] args) {
    Display display = new Display();
    Image image = new Image(display, Snippet283.class.getResourceAsStream("eclipse.png"));
    Shell shell = new Shell(display);
    shell.setText("Snippet 283");
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.FULL_SELECTION);
    for (int i = 0; i < 8; i++) {
        TableItem item = new TableItem(table, SWT.NONE);
        item.setText("Item " + i + " with long text that scrolls.");
        if (i % 2 == 1)
            item.setImage(image);//from   w w  w  .  ja  va2 s. co m
    }
    table.addListener(SWT.MouseDown, event -> {
        Rectangle rect = table.getClientArea();
        Point point = new Point(event.x, event.y);
        if (table.getItem(point) != null)
            return;
        for (int i = table.getTopIndex(); i < table.getItemCount(); i++) {
            TableItem item = table.getItem(i);
            Rectangle itemRect = item.getBounds();
            if (!itemRect.intersects(rect))
                return;
            itemRect.x = rect.x;
            itemRect.width = rect.width;
            if (itemRect.contains(point)) {
                table.setSelection(item);
                Event selectionEvent = new Event();
                selectionEvent.item = item;
                table.notifyListeners(SWT.Selection, selectionEvent);
                return;
            }
        }
    });
    /*
     * NOTE: MeasureItem, PaintItem and EraseItem are called repeatedly.
     * Therefore, it is critical for performance that these methods be
     * as efficient as possible.
     */
    table.addListener(SWT.EraseItem, event -> {
        event.detail &= ~SWT.FOREGROUND;
        String osName = System.getProperty("os.name");
        if (osName != null && osName.contains("Windows")) {
            if (osName.contains("Vista") || osName.contains("unknown")) {
                return;
            }
        }
        event.detail &= ~(SWT.FOREGROUND | SWT.SELECTED | SWT.HOT | SWT.FOCUSED);
        GC gc = event.gc;
        TableItem item = (TableItem) event.item;
        Rectangle rect = table.getClientArea();
        Rectangle itemRect = item.getBounds();
        itemRect.x = rect.x;
        itemRect.width = rect.width;
        gc.setClipping((Rectangle) null);
        gc.fillRectangle(itemRect);
    });
    table.addListener(SWT.PaintItem, event -> {
        TableItem item = (TableItem) event.item;
        GC gc = event.gc;
        Image image1 = item.getImage(0);
        String text = item.getText(0);
        Point textExtent = gc.stringExtent(text);
        Rectangle imageRect = item.getImageBounds(0);
        Rectangle textRect = item.getTextBounds(0);
        int textY = textRect.y + Math.max(0, (textRect.height - textExtent.y) / 2);
        if (image1 == null) {
            gc.drawString(text, imageRect.x, textY, true);
        } else {
            Rectangle imageExtent = image1.getBounds();
            int imageY = imageRect.y + Math.max(0, (imageRect.height - imageExtent.height) / 2);
            gc.drawImage(image1, imageRect.x, imageY);
            gc.drawString(text, textRect.x, textY, true);
        }
    });
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:com.mgmtp.jfunk.core.ui.JFunkFrame.java

public static void main(final String[] args) {
    List<File> roots = new ArrayList<File>(Math.max(1, args.length));
    if (args.length > 0) {
        for (String arg : args) {
            File file = new File(arg);
            if (file.exists()) {
                roots.add(new File(arg));
            }// ww w.ja v  a  2  s. c  o  m
        }
    } else {
        roots.add(new File("scripts"));
    }
    JFunkFrame.createAndShow(roots);
}

From source file:TreeCellEditor.java

public static void main(String[] args) {
    final Display display = new Display();
    final Color black = display.getSystemColor(SWT.COLOR_BLACK);
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    final Tree tree = new Tree(shell, SWT.BORDER);
    for (int i = 0; i < 16; i++) {
        TreeItem itemI = new TreeItem(tree, SWT.NONE);
        itemI.setText("Item " + i);
        for (int j = 0; j < 16; j++) {
            TreeItem itemJ = new TreeItem(itemI, SWT.NONE);
            itemJ.setText("Item " + j);
        }/*from w w  w. j  av  a 2 s .c  o  m*/
    }
    final TreeItem[] lastItem = new TreeItem[1];
    final TreeEditor editor = new TreeEditor(tree);
    tree.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event event) {
            final TreeItem item = (TreeItem) event.item;
            if (item != null && item == lastItem[0]) {
                boolean isCarbon = SWT.getPlatform().equals("carbon");
                final Composite composite = new Composite(tree, SWT.NONE);
                if (!isCarbon)
                    composite.setBackground(black);
                final Text text = new Text(composite, SWT.NONE);
                final int inset = isCarbon ? 0 : 1;
                composite.addListener(SWT.Resize, new Listener() {
                    public void handleEvent(Event e) {
                        Rectangle rect = composite.getClientArea();
                        text.setBounds(rect.x + inset, rect.y + inset, rect.width - inset * 2,
                                rect.height - inset * 2);
                    }
                });
                Listener textListener = new Listener() {
                    public void handleEvent(final Event e) {
                        switch (e.type) {
                        case SWT.FocusOut:
                            item.setText(text.getText());
                            composite.dispose();
                            break;
                        case SWT.Verify:
                            String newText = text.getText();
                            String leftText = newText.substring(0, e.start);
                            String rightText = newText.substring(e.end, newText.length());
                            GC gc = new GC(text);
                            Point size = gc.textExtent(leftText + e.text + rightText);
                            gc.dispose();
                            size = text.computeSize(size.x, SWT.DEFAULT);
                            editor.horizontalAlignment = SWT.LEFT;
                            Rectangle itemRect = item.getBounds(), rect = tree.getClientArea();
                            editor.minimumWidth = Math.max(size.x, itemRect.width) + inset * 2;
                            int left = itemRect.x, right = rect.x + rect.width;
                            editor.minimumWidth = Math.min(editor.minimumWidth, right - left);
                            editor.minimumHeight = size.y + inset * 2;
                            editor.layout();
                            break;
                        case SWT.Traverse:
                            switch (e.detail) {
                            case SWT.TRAVERSE_RETURN:
                                item.setText(text.getText());
                                // FALL THROUGH
                            case SWT.TRAVERSE_ESCAPE:
                                composite.dispose();
                                e.doit = false;
                            }
                            break;
                        }
                    }
                };
                text.addListener(SWT.FocusOut, textListener);
                text.addListener(SWT.Traverse, textListener);
                text.addListener(SWT.Verify, textListener);
                editor.setEditor(composite, item);
                text.setText(item.getText());
                text.selectAll();
                text.setFocus();
            }
            lastItem[0] = item;
        }
    });
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:org.eclipse.swt.snippets.Snippet48.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 48");
    shell.setLayout(new FillLayout());
    Image originalImage = null;//from   w w w .j a v  a  2 s. co m
    FileDialog dialog = new FileDialog(shell, SWT.OPEN);
    dialog.setText("Open an image file or cancel");
    String string = dialog.open();
    if (string != null) {
        originalImage = new Image(display, string);
    }
    if (originalImage == null) {
        int width = 150, height = 200;
        originalImage = new Image(display, width, height);
        GC gc = new GC(originalImage);
        gc.fillRectangle(0, 0, width, height);
        gc.drawLine(0, 0, width, height);
        gc.drawLine(0, height, width, 0);
        gc.drawText("Default Image", 10, 10);
        gc.dispose();
    }
    final Image image = originalImage;
    final Point origin = new Point(0, 0);
    final Canvas canvas = new Canvas(shell,
            SWT.NO_BACKGROUND | SWT.NO_REDRAW_RESIZE | SWT.V_SCROLL | SWT.H_SCROLL);
    final ScrollBar hBar = canvas.getHorizontalBar();
    hBar.addListener(SWT.Selection, e -> {
        int hSelection = hBar.getSelection();
        int destX = -hSelection - origin.x;
        Rectangle rect = image.getBounds();
        canvas.scroll(destX, 0, 0, 0, rect.width, rect.height, false);
        origin.x = -hSelection;
    });
    final ScrollBar vBar = canvas.getVerticalBar();
    vBar.addListener(SWT.Selection, e -> {
        int vSelection = vBar.getSelection();
        int destY = -vSelection - origin.y;
        Rectangle rect = image.getBounds();
        canvas.scroll(0, destY, 0, 0, rect.width, rect.height, false);
        origin.y = -vSelection;
    });
    canvas.addListener(SWT.Resize, e -> {
        Rectangle rect = image.getBounds();
        Rectangle client = canvas.getClientArea();
        hBar.setMaximum(rect.width);
        vBar.setMaximum(rect.height);
        hBar.setThumb(Math.min(rect.width, client.width));
        vBar.setThumb(Math.min(rect.height, client.height));
        int hPage = rect.width - client.width;
        int vPage = rect.height - client.height;
        int hSelection = hBar.getSelection();
        int vSelection = vBar.getSelection();
        if (hSelection >= hPage) {
            if (hPage <= 0)
                hSelection = 0;
            origin.x = -hSelection;
        }
        if (vSelection >= vPage) {
            if (vPage <= 0)
                vSelection = 0;
            origin.y = -vSelection;
        }
        canvas.redraw();
    });
    canvas.addListener(SWT.Paint, e -> {
        GC gc = e.gc;
        gc.drawImage(image, origin.x, origin.y);
        Rectangle rect = image.getBounds();
        Rectangle client = canvas.getClientArea();
        int marginWidth = client.width - rect.width;
        if (marginWidth > 0) {
            gc.fillRectangle(rect.width, 0, marginWidth, client.height);
        }
        int marginHeight = client.height - rect.height;
        if (marginHeight > 0) {
            gc.fillRectangle(0, rect.height, client.width, marginHeight);
        }
    });
    Rectangle rect = image.getBounds();
    shell.setSize(Math.max(200, rect.width - 100), Math.max(150, rect.height - 100));
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    originalImage.dispose();
    display.dispose();
}

From source file:de.tudarmstadt.lt.lm.app.GenerateNgrams.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options opts = new Options();
    opts.addOption(OptionBuilder.withLongOpt("help").withDescription("Display help message.").create("?"));
    opts.addOption(OptionBuilder.withLongOpt("ptype").withArgName("class").hasArg().withDescription(
            "specify the instance of the language model provider that you want to use: {LtSegProvider, BreakIteratorStringProvider, UimaStringProvider, PreTokenizedStringProvider} (default: LtSegProvider)")
            .create("p"));
    opts.addOption(OptionBuilder.withLongOpt("cardinality").withArgName("ngram-order").hasArg().withDescription(
            "Specify the cardinality of the ngrams (min. 1). Specify a range using 'from-to'. (Examples: 5 = extract 5grams; 1-5 = extract 1grams, 2grams, ..., 5grams; default: 1-5).")
            .create("n"));
    opts.addOption(OptionBuilder.withLongOpt("dir").withArgName("directory").isRequired().hasArg()
            .withDescription(/*ww  w.  j a  v  a2 s .c  o m*/
                    "specify the directory that contains '.txt' files that are used as source for generating ngrams.")
            .create("d"));
    opts.addOption(OptionBuilder.withLongOpt("overwrite").withDescription("Overwrite existing ngram file.")
            .create("w"));

    CommandLine cli = null;
    try {
        cli = new GnuParser().parse(opts, args);
    } catch (Exception e) {
        print_usage(opts, e.getMessage());
    }
    if (cli.hasOption("?"))
        print_usage(opts, null);

    AbstractStringProvider prvdr = null;
    try {
        prvdr = StartLM
                .getStringProviderInstance(cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName()));
    } catch (Exception e) {
        print_usage(opts, String.format("Could not instantiate LmProvider '%s': %s",
                cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName()), e.getMessage()));
    }

    String n_ = cli.getOptionValue("cardinality", "1-5");
    int dash_index = n_.indexOf('-');
    int n_e = Integer.parseInt(n_.substring(dash_index + 1, n_.length()).trim());
    int n_b = n_e;
    if (dash_index == 0)
        n_b = 1;
    if (dash_index > 0)
        n_b = Math.max(1, Integer.parseInt(n_.substring(0, dash_index).trim()));

    final File src_dir = new File(cli.getOptionValue("dir"));
    boolean overwrite = Boolean.parseBoolean(cli.getOptionValue("overwrite", "false"));

    generateNgrams(src_dir, prvdr, n_b, n_e, overwrite);

}

From source file:jsdp.app.control.clqg.univariate.CLQG.java

public static void main(String args[]) {

    /*******************************************************************
     * Problem parameters//from   www. j  a  v  a2s  .  c o m
     */

    int T = 20; // Horizon length
    double G = 1; // Input transition
    double Phi = 1; // State transition
    double R = 1; // Input cost
    double Q = 1; // State cost
    double Ulb = -1; // Action constraint
    double Uub = 20; // Action constraint
    double noiseStd = 5; // Standard deviation of the noise

    double[] noiseStdArray = new double[T];
    Arrays.fill(noiseStdArray, noiseStd);
    double truncationQuantile = 0.975;

    // Random variables

    Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(noiseStdArray.length)
            .mapToObj(i -> new NormalDist(0, noiseStdArray[i]))

            .toArray(Distribution[]::new);
    double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(T)
            .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], 1 - truncationQuantile)).toArray();

    double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(T)
            .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], truncationQuantile)).toArray();

    double initialX = 0; // Initial state

    /*******************************************************************
     * Model definition
     */

    // State space

    double stepSize = 0.5; //Stepsize must be 1 for discrete distributions
    double minState = -25;
    double maxState = 100;
    StateImpl.setStateBoundaries(stepSize, minState, maxState);

    // Actions

    Function<State, ArrayList<Action>> buildActionList = (Function<State, ArrayList<Action>> & Serializable) s -> {
        StateImpl state = (StateImpl) s;
        ArrayList<Action> feasibleActions = new ArrayList<Action>();
        double maxAction = Math.min(Uub, (StateImpl.getMaxState() - Phi * state.getInitialState()) / G);
        double minAction = Math.max(Ulb, (StateImpl.getMinState() - Phi * state.getInitialState()) / G);
        for (double actionPointer = minAction; actionPointer <= maxAction; actionPointer += StateImpl
                .getStepSize()) {
            feasibleActions.add(new ActionImpl(state, actionPointer));
        }
        return feasibleActions;
    };

    Function<State, Action> idempotentAction = (Function<State, Action> & Serializable) s -> new ActionImpl(s,
            0.0);

    ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action,
            finalState) -> {
        ActionImpl a = (ActionImpl) action;
        StateImpl fs = (StateImpl) finalState;
        double inputCost = Math.pow(a.getAction(), 2) * R;
        double stateCost = Math.pow(fs.getInitialState(), 2) * Q;
        return inputCost + stateCost;
    };

    // Random Outcome Function

    RandomOutcomeFunction<State, Action, Double> randomOutcomeFunction = (initialState, action, finalState) -> {
        double realizedNoise = ((StateImpl) finalState).getInitialState()
                - ((StateImpl) initialState).getInitialState() * Phi - ((ActionImpl) action).getAction() * G;
        return realizedNoise;
    };

    /*******************************************************************
     * Solve
     */

    // Sampling scheme

    SamplingScheme samplingScheme = SamplingScheme.NONE;
    int maxSampleSize = 50;
    double reductionFactorPerStage = 1;

    // Value Function Processing Method: backward recursion
    double discountFactor = 1.0;
    int stateSpaceLowerBound = 10000000;
    float loadFactor = 0.8F;
    BackwardRecursionImpl recursion = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage,
            stateSpaceLowerBound, loadFactor, HashType.THASHMAP);

    System.out.println("--------------Backward recursion--------------");
    StopWatch timer = new StopWatch();
    OperatingSystemMXBean osMBean;
    try {
        osMBean = ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(),
                ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
        long nanoBefore = System.nanoTime();
        long cpuBefore = osMBean.getProcessCpuTime();

        timer.start();
        recursion.runBackwardRecursionMonitoring();
        timer.stop();

        long cpuAfter = osMBean.getProcessCpuTime();
        long nanoAfter = System.nanoTime();

        long percent;
        if (nanoAfter > nanoBefore)
            percent = ((cpuAfter - cpuBefore) * 100L) / (nanoAfter - nanoBefore);
        else
            percent = 0;

        System.out.println(
                "Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println();
    double ETC = recursion.getExpectedCost(initialX);
    StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialX);
    double action = recursion.getOptimalAction(initialState).getAction();
    System.out.println("Expected total cost (assuming an initial state " + initialX + "): " + ETC);
    System.out.println("Optimal initial action: " + action);
    System.out.println("Time elapsed: " + timer);
    System.out.println();
}

From source file:edu.msu.cme.rdp.probematch.cli.PrimerMatch.java

public static void main(String[] args) throws Exception {

    PrintStream out = new PrintStream(System.out);
    int maxDist = Integer.MAX_VALUE;

    try {/*  w ww . ja v  a  2 s.c o m*/
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption("outFile")) {
            out = new PrintStream(new File(line.getOptionValue("outFile")));
        }
        if (line.hasOption("maxDist")) {
            maxDist = Integer.valueOf(line.getOptionValue("maxDist"));
        }
        args = line.getArgs();

        if (args.length != 2) {
            throw new Exception("Unexpected number of command line arguments");
        }
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        new HelpFormatter().printHelp("PrimerMatch <primer_list | primer_file> <seq_file>", options);
        return;
    }

    List<PatternBitMask64> primers = new ArrayList();
    if (new File(args[0]).exists()) {
        File primerFile = new File(args[0]);
        SequenceFormat seqformat = SeqUtils.guessFileFormat(primerFile);

        if (seqformat.equals(SequenceFormat.FASTA)) {
            SequenceReader reader = new SequenceReader(primerFile);
            Sequence seq;

            while ((seq = reader.readNextSequence()) != null) {
                primers.add(new PatternBitMask64(seq.getSeqString(), true, seq.getSeqName()));
            }
            reader.close();
        } else {
            BufferedReader reader = new BufferedReader(new FileReader(args[0]));
            String line;

            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (!line.equals("")) {
                    primers.add(new PatternBitMask64(line, true));
                }
            }
            reader.close();
        }
    } else {
        for (String primer : args[0].split(",")) {
            primers.add(new PatternBitMask64(primer, true));
        }
    }

    SeqReader seqReader = new SequenceReader(new File(args[1]));
    Sequence seq;
    String primerRegion;

    out.println("#seqname\tdesc\tprimer_index\tprimer_name\tposition\tmismatches\tseq_primer_region");
    while ((seq = seqReader.readNextSequence()) != null) {
        for (int index = 0; index < primers.size(); index++) {
            PatternBitMask64 primer = primers.get(index);
            BitVector64Result results = BitVector64.process(seq.getSeqString().toCharArray(), primer, maxDist);

            for (BitVector64Match result : results.getResults()) {
                primerRegion = seq.getSeqString().substring(
                        Math.max(0, result.getPosition() - primer.getPatternLength()), result.getPosition());

                if (result.getPosition() < primer.getPatternLength()) {
                    for (int pad = result.getPosition(); pad < primer.getPatternLength(); pad++) {
                        primerRegion = "x" + primerRegion;
                    }
                }

                out.println(seq.getSeqName() + "\t" + seq.getDesc() + "\t" + (index + 1) + "\t"
                        + primer.getPrimerName() + "\t" + result.getPosition() + "\t" + result.getScore() + "\t"
                        + primerRegion);
            }
        }
    }
    out.close();
    seqReader.close();
}

From source file:Snippet119.java

public static void main(String[] args) {
    Display display = new Display();
    Color white = display.getSystemColor(SWT.COLOR_WHITE);
    Color black = display.getSystemColor(SWT.COLOR_BLACK);
    Color yellow = display.getSystemColor(SWT.COLOR_YELLOW);
    Color red = display.getSystemColor(SWT.COLOR_RED);
    Color green = display.getSystemColor(SWT.COLOR_GREEN);
    Color blue = display.getSystemColor(SWT.COLOR_BLUE);

    // Create a source ImageData of depth 4
    PaletteData palette = new PaletteData(new RGB[] { black.getRGB(), white.getRGB(), yellow.getRGB(),
            red.getRGB(), blue.getRGB(), green.getRGB() });
    ImageData sourceData = new ImageData(16, 16, 4, palette, 1, srcData);

    // Create a mask ImageData of depth 1 (monochrome)
    palette = new PaletteData(new RGB[] { black.getRGB(), white.getRGB(), });
    ImageData maskData = new ImageData(16, 16, 1, palette, 1, mskData);

    // Set mask/*from   w w w  . j  av a 2 s  .c o  m*/
    sourceData.maskData = maskData.data;
    sourceData.maskPad = maskData.scanlinePad;

    // Create cursor
    Cursor cursor = new Cursor(display, sourceData, 10, 10);

    // Remove mask to draw them separately just to show what they look like
    sourceData.maskData = null;
    sourceData.maskPad = -1;

    Shell shell = new Shell(display);
    final Image source = new Image(display, sourceData);
    final Image mask = new Image(display, maskData);
    shell.addPaintListener(new PaintListener() {
        public void paintControl(PaintEvent e) {
            GC gc = e.gc;
            int x = 10, y = 10;
            String stringSource = "source: ";
            String stringMask = "mask: ";
            gc.drawString(stringSource, x, y);
            gc.drawString(stringMask, x, y + 30);
            x += Math.max(gc.stringExtent(stringSource).x, gc.stringExtent(stringMask).x);
            gc.drawImage(source, x, y);
            gc.drawImage(mask, x, y + 30);
        }
    });
    shell.setSize(150, 150);
    shell.open();
    shell.setCursor(cursor);

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    cursor.dispose();
    source.dispose();
    mask.dispose();
    display.dispose();
}

From source file:org.eclipse.swt.snippets.Snippet119.java

public static void main(String[] args) {
    Display display = new Display();
    Color white = display.getSystemColor(SWT.COLOR_WHITE);
    Color black = display.getSystemColor(SWT.COLOR_BLACK);
    Color yellow = display.getSystemColor(SWT.COLOR_YELLOW);
    Color red = display.getSystemColor(SWT.COLOR_RED);
    Color green = display.getSystemColor(SWT.COLOR_GREEN);
    Color blue = display.getSystemColor(SWT.COLOR_BLUE);

    //Create a source ImageData of depth 4
    PaletteData palette = new PaletteData(black.getRGB(), white.getRGB(), yellow.getRGB(), red.getRGB(),
            blue.getRGB(), green.getRGB());
    ImageData sourceData = new ImageData(16, 16, 4, palette, 1, srcData);

    //Create a mask ImageData of depth 1 (monochrome)
    palette = new PaletteData(black.getRGB(), white.getRGB());
    ImageData maskData = new ImageData(16, 16, 1, palette, 1, mskData);

    //Set mask//w w w  .  j  a va  2  s .  c  o  m
    sourceData.maskData = maskData.data;
    sourceData.maskPad = maskData.scanlinePad;

    //Create cursor
    Cursor cursor = new Cursor(display, sourceData, 10, 10);

    //Remove mask to draw them separately just to show what they look like
    sourceData.maskData = null;
    sourceData.maskPad = -1;

    Shell shell = new Shell(display);
    shell.setText("Snippet 119");
    final Image source = new Image(display, sourceData);
    final Image mask = new Image(display, maskData);
    shell.addPaintListener(e -> {
        GC gc = e.gc;
        int x = 10, y = 10;
        String stringSource = "source: ";
        String stringMask = "mask: ";
        gc.drawString(stringSource, x, y);
        gc.drawString(stringMask, x, y + 30);
        x += Math.max(gc.stringExtent(stringSource).x, gc.stringExtent(stringMask).x);
        gc.drawImage(source, x, y);
        gc.drawImage(mask, x, y + 30);
    });
    shell.setSize(150, 150);
    shell.open();
    shell.setCursor(cursor);

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    cursor.dispose();
    source.dispose();
    mask.dispose();
    display.dispose();
}