Example usage for java.awt GraphicsEnvironment getLocalGraphicsEnvironment

List of usage examples for java.awt GraphicsEnvironment getLocalGraphicsEnvironment

Introduction

In this page you can find the example usage for java.awt GraphicsEnvironment getLocalGraphicsEnvironment.

Prototype

public static GraphicsEnvironment getLocalGraphicsEnvironment() 

Source Link

Document

Returns the local GraphicsEnvironment .

Usage

From source file:pcgen.gui2.tools.Utility.java

/**
 * Centers a {@code JFrame} to the screen.
 *
 * @param frame   JFrame frame to center
 * @param isPopup boolean is the frame a popup dialog?
 *//*from  w  w  w. java 2  s .  co m*/
public static void centerComponent(Component frame, boolean isPopup) {
    // since the Toolkit.getScreenSize() method is broken in the Linux implementation
    // of Java 5  (it returns double the screen size under xinerama), this method is
    // encapsulated to accomodate this with a hack.
    // TODO: remove the hack, once Java fixed this.
    // final Dimension screenSize = getScreenSize(Toolkit.getDefaultToolkit());
    final Rectangle screenSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
            .getDefaultConfiguration().getBounds();

    if (isPopup) {
        frame.setSize(screenSize.width / 2, screenSize.height / 2);
    }

    final Dimension frameSize = frame.getSize();

    if (frameSize.height > screenSize.height) {
        frameSize.height = screenSize.height;
    }

    if (frameSize.width > screenSize.width) {
        frameSize.width = screenSize.width;
    }

    frame.setLocation(screenSize.x + ((screenSize.width - frameSize.width) / 2),
            screenSize.y + ((screenSize.height - frameSize.height) / 2));
}

From source file:org.openscience.jchempaint.application.JChemPaint.java

public static JChemPaintPanel showInstance(IChemModel chemModel, String title, boolean debug) {
    JFrame f = new JFrame(title + " - JChemPaint");
    chemModel.setID(title);//w ww  . j  a v a2 s . c om
    f.addWindowListener(new JChemPaintPanel.AppCloser());
    f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    JChemPaintPanel p = new JChemPaintPanel(chemModel, GUI_APPLICATION, debug, null);
    p.updateStatusBar();
    f.setPreferredSize(new Dimension(800, 494)); //1.618
    f.add(p);
    f.pack();
    Point point = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
    int w2 = (f.getWidth() / 2);
    int h2 = (f.getHeight() / 2);
    f.setLocation(point.x - w2, point.y - h2);
    f.setVisible(true);
    frameList.add(f);
    return p;
}

From source file:org.squidy.nodes.MouseIO.java

@Override
public void onStart() {

    // Search minimum/maximum of x/y.
    GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
    screenBounds = new Rectangle[devices.length];
    for (int i = 0; i < devices.length; i++) {
        GraphicsDevice device = devices[i];
        GraphicsConfiguration gc = device.getDefaultConfiguration();
        Rectangle bounds = gc.getBounds();
        screenBounds[i] = bounds;/*from w w  w. j  av  a  2s .c  om*/

        double x, y;
        x = bounds.getX();
        minX = Math.min(minX, x);
        x += bounds.getWidth();
        maxX = Math.max(maxX, x);
        y = bounds.getY();
        minY = Math.min(minY, y);
        y += bounds.getHeight();
        maxY = Math.max(maxY, y);
    }

    width = Math.abs(minX) + Math.abs(maxX);
    height = Math.abs(minY) + Math.abs(maxY);

    try {
        robot = new Robot();
        robot.setAutoDelay(0);
    } catch (AWTException e) {
        if (LOG.isErrorEnabled())
            LOG.error("Could not initialize Robot.");
        publishFailure(e);
    }

    if (openInputWindow) {
        inputWindow = InputWindow.getInstance();
        inputWindow.registerMouseListener(this);
    }

    if (directInput && isWindows) {
        if (cdim == null) {
            createDirectInputMouse();
            if (cdim != null) {
                if (cdim.Init(0) != 0) {
                    cdim = null;
                    publishFailure(new SquidyException("Could not initialize DirectInput mouse."));
                }
            }
        }
        if (cdim != null) {
            if (cdim.StartCapture() != 0)
                publishFailure(new SquidyException("Could not start DirectInput mouse."));
            else
                new Thread(new Runnable() {
                    public void run() {
                        while (processing) {
                            cdim.WaitForBufferedData();
                            if (processing)
                                processDirectInputMouseBufferedData();
                        }
                    }
                }, getId() + "_DIM").start();
        }
    }
}

From source file:com.alkacon.opencms.formgenerator.CmsCaptchaEngine.java

/**
 * Filters the fonts available on the system. <p>
 * /*from   w  w w.  j a  v a2  s .  c om*/
 * Only fonts, which start with one of the provided prefix are returned. 
 * These prefix list ensures, that font do not contain unreadable characters.
 * 
 * @param prefixList the list of prefix to filter the system fonts
 * 
 * @return an array of standard fonts
 */
private Font[] getFilteredFonts(List<String> prefixList) {

    LOG.debug(Messages.get().getBundle().key(Messages.DEBUG_CAPTCHA_FONT_FILTERING_START_0));
    List<Font> filteredFontsList = new LinkedList<Font>();

    // Get all system fonts
    GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
    Font[] systemFonts = e.getAllFonts();

    for (Font f : systemFonts) {
        for (String prefix : prefixList) {
            if (f.getFontName().toLowerCase().startsWith(prefix.toLowerCase())) {
                filteredFontsList.add(f);
                LOG.debug(Messages.get().getBundle().key(Messages.DEBUG_CAPTCHA_ADD_FONT_1, f.getFontName()));
            }
        }
    }
    Font[] filteredFonts = new Font[filteredFontsList.size()];
    int i = 0;
    for (Font f : filteredFontsList) {
        filteredFonts[i] = f;
        i++;
    }
    LOG.debug(Messages.get().getBundle().key(Messages.DEBUG_CAPTCHA_FONT_FILTERING_FINISH_1,
            Integer.valueOf(filteredFonts.length)));
    return filteredFonts;
}

From source file:edu.ku.brc.specify.prefs.FormattingPrefsPanel.java

/**
 * Create the UI for the panel/*from  w  w w  .java 2 s . c  om*/
 */
protected void createUI() {
    createForm("Preferences", "Formatting"); //$NON-NLS-1$ //$NON-NLS-2$

    UIValidator.setIgnoreAllValidation(this, true);

    JLabel fontNamesLabel = form.getLabelFor("fontNames"); //$NON-NLS-1$
    ValComboBox fontNamesVCB = form.getCompById("fontNames"); //$NON-NLS-1$

    JLabel fontSizesLabel = form.getLabelFor("fontSizes"); //$NON-NLS-1$
    ValComboBox fontSizesVCB = form.getCompById("fontSizes"); //$NON-NLS-1$

    JLabel controlSizesLabel = form.getLabelFor("controlSizes"); //$NON-NLS-1$
    ValComboBox controlSizesVCB = form.getCompById("controlSizes"); //$NON-NLS-1$

    formTypesCBX = form.getCompById("formtype"); //$NON-NLS-1$

    fontNames = fontNamesVCB.getComboBox();
    fontSizes = fontSizesVCB.getComboBox();
    controlSizes = controlSizesVCB.getComboBox();

    testField = form.getCompById("fontTest"); //$NON-NLS-1$
    if (testField != null) {
        testField.setText(UIRegistry.getResourceString("FormattingPrefsPanel.THIS_TEST")); //$NON-NLS-1$
    }
    if (UIHelper.isMacOS_10_5_X()) {
        fontNamesLabel.setVisible(false);
        fontNamesVCB.setVisible(false);
        fontSizesLabel.setVisible(false);
        fontSizesVCB.setVisible(false);
        testField.setVisible(false);

        int inx = -1;
        int i = 0;
        Vector<String> controlSizeTitles = new Vector<String>();
        for (UIHelper.CONTROLSIZE cs : UIHelper.CONTROLSIZE.values()) {
            String titleStr = getResourceString(cs.toString());
            controlSizeTitles.add(titleStr);
            controlSizesHash.put(titleStr, cs);
            controlSizes.addItem(titleStr);
            if (cs == UIHelper.getControlSize()) {
                inx = i;
            }
            i++;
        }
        controlSizes.setSelectedIndex(inx);

        Font baseFont = UIRegistry.getBaseFont();
        if (baseFont != null) {
            fontNames.addItem(baseFont.getFamily());
            fontSizes.addItem(Integer.toString(baseFont.getSize()));
            fontNames.setSelectedIndex(0);
            fontSizes.setSelectedIndex(0);
        }

    } else {
        controlSizesLabel.setVisible(false);
        controlSizesVCB.setVisible(false);

        Hashtable<String, Boolean> namesUsed = new Hashtable<String, Boolean>();
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        for (Font font : ge.getAllFonts()) {
            if (namesUsed.get(font.getFamily()) == null) {
                fontNames.addItem(font.getFamily());
                namesUsed.put(font.getFamily(), true); //$NON-NLS-1$
            }
        }
        for (int i = BASE_FONT_SIZE; i < 22; i++) {
            fontSizes.addItem(Integer.toString(i));
        }

        Font baseFont = UIRegistry.getBaseFont();
        if (baseFont != null) {
            fontNames.setSelectedItem(baseFont.getFamily());
            fontSizes.setSelectedItem(Integer.toString(baseFont.getSize()));

            if (testField != null) {
                ActionListener al = new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        testField.setFont(new Font((String) fontNames.getSelectedItem(), Font.PLAIN,
                                fontSizes.getSelectedIndex() + BASE_FONT_SIZE));
                        form.getUIComponent().validate();
                        clearFontSettings = false;
                    }
                };
                fontNames.addActionListener(al);
                fontSizes.addActionListener(al);
            }
        }
    }

    //-----------------------------------
    // Do DisciplineType Icons
    //-----------------------------------

    String iconName = AppPreferences.getRemote().get(getDisciplineImageName(), "CollectionObject"); //$NON-NLS-1$ //$NON-NLS-2$

    List<Pair<String, ImageIcon>> list = IconManager.getListByType("disciplines", IconManager.IconSize.Std16); //$NON-NLS-1$
    Collections.sort(list, new Comparator<Pair<String, ImageIcon>>() {
        public int compare(Pair<String, ImageIcon> o1, Pair<String, ImageIcon> o2) {
            String s1 = UIRegistry.getResourceString(o1.first);
            String s2 = UIRegistry.getResourceString(o2.first);
            return s1.compareTo(s2);
        }
    });

    disciplineCBX = (ValComboBox) form.getCompById("disciplineIconCBX"); //$NON-NLS-1$

    final JLabel dispLabel = form.getCompById("disciplineIcon"); //$NON-NLS-1$
    JComboBox comboBox = disciplineCBX.getComboBox();
    comboBox.setRenderer(new DefaultListCellRenderer() {
        @SuppressWarnings("unchecked") //$NON-NLS-1$
        public Component getListCellRendererComponent(JList listArg, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
            Pair<String, ImageIcon> item = (Pair<String, ImageIcon>) value;
            JLabel label = (JLabel) super.getListCellRendererComponent(listArg, value, index, isSelected,
                    cellHasFocus);
            if (item != null) {
                label.setIcon(item.second);
                label.setText(UIRegistry.getResourceString(item.first));
            }
            return label;
        }
    });

    int inx = 0;
    Pair<String, ImageIcon> colObj = new Pair<String, ImageIcon>("colobj_backstop", //$NON-NLS-1$
            IconManager.getIcon("colobj_backstop", IconManager.IconSize.Std16)); //$NON-NLS-1$
    comboBox.addItem(colObj);

    int cnt = 1;
    for (Pair<String, ImageIcon> item : list) {
        if (item.first.equals(iconName)) {
            inx = cnt;
        }
        comboBox.addItem(item);
        cnt++;
    }

    comboBox.addActionListener(new ActionListener() {
        @SuppressWarnings("unchecked") //$NON-NLS-1$
        public void actionPerformed(ActionEvent e) {
            JComboBox cbx = (JComboBox) e.getSource();
            Pair<String, ImageIcon> item = (Pair<String, ImageIcon>) cbx.getSelectedItem();
            if (item != null) {
                dispLabel.setIcon(IconManager.getIcon(item.first));
                form.getUIComponent().validate();
            }
        }
    });

    comboBox.setSelectedIndex(inx);

    //-----------------------------------
    // Date Field
    //-----------------------------------
    dateFieldCBX = form.getCompById("scrdateformat"); //$NON-NLS-1$
    fillDateFormat();

    //-----------------------------------
    // FormType
    //-----------------------------------
    fillFormTypes();

    //-----------------------------------
    // Do App Icon
    //-----------------------------------

    final JButton getIconBtn = form.getCompById("GetIconImage"); //$NON-NLS-1$
    final JButton clearIconBtn = form.getCompById("ClearIconImage"); //$NON-NLS-1$
    final JLabel appLabel = form.getCompById("appIcon"); //$NON-NLS-1$
    final JButton resetDefFontBtn = form.getCompById("ResetDefFontBtn"); //$NON-NLS-1$

    String imgEncoded = AppPreferences.getRemote().get(iconImagePrefName, ""); //$NON-NLS-1$
    ImageIcon innerAppImgIcon = null;
    if (StringUtils.isNotEmpty(imgEncoded)) {
        innerAppImgIcon = GraphicsUtils.uudecodeImage("", imgEncoded); //$NON-NLS-1$
        if (innerAppImgIcon != null && innerAppImgIcon.getIconWidth() != 32
                || innerAppImgIcon.getIconHeight() != 32) {
            innerAppImgIcon = null;
            clearIconBtn.setEnabled(false);
        } else {
            clearIconBtn.setEnabled(true);
        }
    }

    if (innerAppImgIcon == null) {
        innerAppImgIcon = IconManager.getIcon("AppIcon"); //$NON-NLS-1$
        clearIconBtn.setEnabled(false);
    } else {
        clearIconBtn.setEnabled(true);
    }
    appLabel.setIcon(innerAppImgIcon);

    getIconBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            chooseToolbarIcon(appLabel, clearIconBtn);
        }
    });

    clearIconBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ImageIcon appIcon = IconManager.getIcon("AppIcon");
            IconEntry entry = IconManager.getIconEntryByName(INNER_APPICON_NAME);
            entry.setIcon(appIcon);
            if (entry.getIcons().get(IconManager.IconSize.Std32) != null) {
                entry.getIcons().get(IconManager.IconSize.Std32).setImageIcon(appIcon);
            }

            appLabel.setIcon(IconManager.getIcon("AppIcon")); //$NON-NLS-1$
            clearIconBtn.setEnabled(false);
            AppPreferences.getRemote().remove(iconImagePrefName);
            form.getValidator().dataChanged(null, null, null);
        }
    });

    resetDefFontBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Font sysDefFont = UIRegistry.getDefaultFont();
            ComboBoxModel model = fontNames.getModel();
            for (int i = 0; i < model.getSize(); i++) {
                //System.out.println("["+model.getElementAt(i).toString()+"]["+sysDefFont.getFamily()+"]");
                if (model.getElementAt(i).toString().equals(sysDefFont.getFamily())) {
                    fontNames.setSelectedIndex(i);
                    clearFontSettings = true;
                    break;
                }
            }

            if (clearFontSettings) {
                fontSizes.setSelectedIndex(sysDefFont.getSize() - BASE_FONT_SIZE);
                clearFontSettings = true; // needs to be redone 
            }

            form.getValidator().dataChanged(null, null, null);
        }
    });

    //-----------------------------------
    // Do Banner Icon Size
    //-----------------------------------

    String fmtStr = "%d x %d pixels";//getResourceString("BNR_ICON_SIZE");
    bnrIconSizeCBX = form.getCompById("bnrIconSizeCBX"); //$NON-NLS-1$

    int size = AppPreferences.getLocalPrefs().getInt(BNR_ICON_SIZE, 20);
    inx = 0;
    cnt = 0;
    for (int pixelSize : pixelSizes) {
        ((DefaultComboBoxModel) bnrIconSizeCBX.getModel())
                .addElement(String.format(fmtStr, pixelSize, pixelSize));
        if (pixelSize == size) {
            inx = cnt;
        }
        cnt++;
    }

    bnrIconSizeCBX.getComboBox().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            form.getUIComponent().validate();
        }
    });

    bnrIconSizeCBX.getComboBox().setSelectedIndex(inx);

    UIValidator.setIgnoreAllValidation(this, false);
    fontNamesVCB.setChanged(false);
    fontSizesVCB.setChanged(false);

    form.getValidator().validateForm();
}

From source file:com.lfv.lanzius.server.LanziusServer.java

public void init() {

    log.info(Config.VERSION + "\n");

    docVersion = 0;/* w  w  w .  ja  va2  s  . c o  m*/

    frame = new JFrame(Config.TITLE + " - Server Control Panel");

    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            actionPerformed(new ActionEvent(itemExit, 0, null));
        }
    });

    // Create graphical terminal view
    panel = new WorkspacePanel(this);
    frame.getContentPane().add(panel);

    // Create a menu bar
    JMenuBar menuBar = new JMenuBar();

    // FILE
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);
    // Load configuration
    itemLoadConfig = new JMenuItem("Load configuration...");
    itemLoadConfig.addActionListener(this);
    fileMenu.add(itemLoadConfig);
    // Load terminal setup
    itemLoadExercise = new JMenuItem("Load exercise...");
    itemLoadExercise.addActionListener(this);
    fileMenu.add(itemLoadExercise);
    fileMenu.addSeparator();
    // Exit
    itemExit = new JMenuItem("Exit");
    itemExit.addActionListener(this);
    fileMenu.add(itemExit);
    menuBar.add(fileMenu);

    // SERVER
    JMenu serverMenu = new JMenu("Server");
    serverMenu.setMnemonic(KeyEvent.VK_S);
    // Start
    itemServerStart = new JMenuItem("Start");
    itemServerStart.addActionListener(this);
    serverMenu.add(itemServerStart);
    // Stop
    itemServerStop = new JMenuItem("Stop");
    itemServerStop.addActionListener(this);
    serverMenu.add(itemServerStop);
    // Restart
    itemServerRestart = new JMenuItem("Restart");
    itemServerRestart.addActionListener(this);
    itemServerRestart.setEnabled(false);
    serverMenu.add(itemServerRestart);
    // Monitor network connection
    itemServerMonitor = new JCheckBoxMenuItem("Monitor network");
    itemServerMonitor.addActionListener(this);
    itemServerMonitor.setState(false);
    serverMenu.add(itemServerMonitor);
    menuBar.add(serverMenu);

    // TERMINAL
    JMenu terminalMenu = new JMenu("Terminal");
    terminalMenu.setMnemonic(KeyEvent.VK_T);
    itemTerminalLink = new JMenuItem("Link...");
    itemTerminalLink.addActionListener(this);
    terminalMenu.add(itemTerminalLink);
    itemTerminalUnlink = new JMenuItem("Unlink...");
    itemTerminalUnlink.addActionListener(this);
    terminalMenu.add(itemTerminalUnlink);
    itemTerminalUnlinkAll = new JMenuItem("Unlink All");
    itemTerminalUnlinkAll.addActionListener(this);
    terminalMenu.add(itemTerminalUnlinkAll);
    itemTerminalSwap = new JMenuItem("Swap...");
    itemTerminalSwap.addActionListener(this);
    terminalMenu.add(itemTerminalSwap);
    menuBar.add(terminalMenu);

    // GROUP
    JMenu groupMenu = new JMenu("Group");
    groupMenu.setMnemonic(KeyEvent.VK_G);
    itemGroupStart = new JMenuItem("Start...");
    itemGroupStart.addActionListener(this);
    groupMenu.add(itemGroupStart);
    itemGroupPause = new JMenuItem("Pause...");
    itemGroupPause.addActionListener(this);
    groupMenu.add(itemGroupPause);
    itemGroupStop = new JMenuItem("Stop...");
    itemGroupStop.addActionListener(this);
    groupMenu.add(itemGroupStop);
    menuBar.add(groupMenu);

    frame.setJMenuBar(menuBar);

    GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    Rectangle maximumWindowBounds = graphicsEnvironment.getMaximumWindowBounds();

    if (Config.SERVER_SIZE_FULLSCREEN) {
        maximumWindowBounds.setLocation(0, 0);
        maximumWindowBounds.setSize(Toolkit.getDefaultToolkit().getScreenSize());
        frame.setResizable(false);
        frame.setUndecorated(true);
    } else if (Config.SERVER_SIZE_100P_WINDOW) {
        // Fixes a bug in linux using gnome. With the line below the upper and
        // lower bars are respected
        maximumWindowBounds.height -= 1;
    } else if (Config.SERVER_SIZE_75P_WINDOW) {
        maximumWindowBounds.width *= 0.75;
        maximumWindowBounds.height *= 0.75;
    } else if (Config.SERVER_SIZE_50P_WINDOW) {
        maximumWindowBounds.width /= 2;
        maximumWindowBounds.height /= 2;
    }

    frame.setBounds(maximumWindowBounds);
    frame.setVisible(true);

    log.info("Starting control panel");

    // Autostart for debugging
    if (Config.SERVER_AUTOLOAD_CONFIGURATION != null)
        actionPerformed(new ActionEvent(itemLoadConfig, 0, null));

    if (Config.SERVER_AUTOSTART_SERVER)
        actionPerformed(new ActionEvent(itemServerStart, 0, null));

    if (Config.SERVER_AUTOLOAD_EXERCISE != null)
        actionPerformed(new ActionEvent(itemLoadExercise, 0, null));

    if (Config.SERVER_AUTOSTART_GROUP > 0)
        actionPerformed(new ActionEvent(itemGroupStart, 0, null));

    try {
        // Read the property files
        serverProperties = new Properties();
        serverProperties.loadFromXML(new FileInputStream("data/properties/serverproperties.xml"));
        int rcPort = Integer.parseInt(serverProperties.getProperty("RemoteControlPort", "0"));
        if (rcPort > 0) {
            groupRemoteControlListener(rcPort);
        }
        isaPeriod = Integer.parseInt(serverProperties.getProperty("ISAPeriod", "60"));
        isaNumChoices = Integer.parseInt(serverProperties.getProperty("ISANumChoices", "6"));
        for (int i = 0; i < 9; i++) {
            String tag = "ISAKeyText" + Integer.toString(i);
            String def_val = Integer.toString(i + 1);
            isakeytext[i] = serverProperties.getProperty(tag, def_val);
        }
        isaExtendedMode = serverProperties.getProperty("ISAExtendedMode", "false").equalsIgnoreCase("true");
    } catch (Exception e) {
        log.error("Unable to start remote control listener");
        log.error(e.getMessage());
    }
    isaClients = new HashSet<Integer>();
}

From source file:com.freedomotic.jfrontend.MainWindow.java

private void setFullscreenMode() {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();

    if (gd.isFullScreenSupported()) {
        frameMap.setVisible(false);//from  w  ww  .ja  v a2 s.  com
        menuBar.setVisible(false);
        frameMap.dispose();
        frameClient.setVisible(false);
        frameClient.dispose();
        desktopPane.removeAll();
        desktopPane.moveToBack(this);
        setVisible(false);
        dispose();

        setUndecorated(true);
        setResizable(false);
        setLayout(new BorderLayout());

        drawer = master.createRenderer(drawer.getCurrEnv());
        if (drawer != null) {
            setDrawer(drawer);
        } else {
            LOG.error(
                    "Unable to create a drawer to render the environment on the desktop frontend in fullscreen mode");
        }
        add(drawer);

        Rectangle maximumWindowBounds = ge.getMaximumWindowBounds();
        setBounds(maximumWindowBounds);

        drawer.setVisible(true);
        this.setVisible(true);
        gd.setFullScreenWindow(this);
        isFullscreen = true;
        Callout callout = new Callout(this.getClass().getCanonicalName(), "info",
                i18n.msg("esc_to_exit_fullscreen"), 100, 100, 0, 5000);
        drawer.createCallout(callout);

    }

}

From source file:ca.sqlpower.wabit.report.ResultSetRendererTest.java

/**
 * This is a test to confirm that subtotalling columns for breaks works.
 *///from  w  ww.  jav  a 2s . com
public void testSubtotals() throws Exception {
    Connection con = null;
    Statement stmt = null;
    try {
        con = getContext().createConnection(
                (JDBCDataSource) getSession().getDataSources().getDataSource("regression_test"));
        stmt = con.createStatement();
        stmt.execute("Create table subtotal_table (break_col varchar(50), subtotal_values integer)");
        stmt.execute("insert into subtotal_table (break_col, subtotal_values) values ('a', 10)");
        stmt.execute("insert into subtotal_table (break_col, subtotal_values) values ('a', 20)");
        stmt.execute("insert into subtotal_table (break_col, subtotal_values) values ('a', 30)");
        stmt.execute("insert into subtotal_table (break_col, subtotal_values) values ('b', 12)");
        stmt.execute("insert into subtotal_table (break_col, subtotal_values) values ('b', 24)");
        stmt.execute("insert into subtotal_table (break_col, subtotal_values) values ('fib', 1)");
        stmt.execute("insert into subtotal_table (break_col, subtotal_values) values ('fib', 1)");
        stmt.execute("insert into subtotal_table (break_col, subtotal_values) values ('fib', 2)");
        stmt.execute("insert into subtotal_table (break_col, subtotal_values) values ('fib', 3)");
        stmt.execute("insert into subtotal_table (break_col, subtotal_values) values ('fib', 5)");
        stmt.execute("insert into subtotal_table (break_col, subtotal_values) values ('fib', 8)");
        stmt.execute("insert into subtotal_table (break_col, subtotal_values) values ('fib', 13)");
    } finally {
        if (stmt != null)
            stmt.close();
        if (con != null)
            con.close();
    }

    query.setUserModifiedQuery("select * from subtotal_table");

    Report report = new Report("report");
    getWorkspace().addReport(report);

    ContentBox cb = new ContentBox();
    report.getPage().addContentBox(cb);
    cb.setWidth(100);
    cb.setHeight(200);
    ResultSetRenderer renderer = new ResultSetRenderer(query);
    renderer.setParent(cb);
    renderer.refresh();

    Graphics2D contentGraphics = (Graphics2D) graphics.create((int) cb.getX(), (int) cb.getY(),
            (int) cb.getWidth(), (int) cb.getHeight());

    renderer.renderReportContent(contentGraphics, (int) cb.getWidth(), (int) cb.getHeight(), 1, 0, true,
            new SPVariableHelper(renderer));

    assertEquals(2, renderer.getColumnInfoList().size());
    renderer.getColumnInfoList().get(0).setWillGroupOrBreak(GroupAndBreak.GROUP);
    renderer.getColumnInfoList().get(1).setWillSubtotal(true);

    Font font = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts()[0];
    renderer.setHeaderFont(font);
    renderer.setBodyFont(font);

    renderer.renderReportContent(contentGraphics, (int) cb.getWidth(), (int) cb.getHeight(), 1, 0, false,
            new SPVariableHelper(renderer));

    List<List<ResultSetCell>> layoutCells = renderer.findCells();

    boolean foundATotal = false;
    boolean foundBTotal = false;
    boolean foundFibTotal = false;
    for (List<ResultSetCell> cells : layoutCells) {
        for (ResultSetCell cell : cells) {
            if (cell.getText().equals("60")) {
                foundATotal = true;
            } else if (cell.getText().equals("36")) {
                foundBTotal = true;
            } else if (cell.getText().equals("33")) {
                foundFibTotal = true;
            }
        }
    }
    if (!foundATotal) {
        fail("Could not find the correct subtotal cell for the A column. The cell should contain the value 60");
    }
    if (!foundBTotal) {
        fail("Could not find the correct subtotal cell for the B column. The cell should contain the value 36");
    }
    if (!foundFibTotal) {
        fail("Could not find the correct subtotal cell for the Fib column. The cell should contain the value 33");
    }

    con = null;
    stmt = null;
    try {
        con = getContext().createConnection(
                (JDBCDataSource) getSession().getDataSources().getDataSource("regression_test"));
        stmt = con.createStatement();
        stmt.execute("drop table subtotal_table");
    } finally {
        if (stmt != null)
            stmt.close();
        if (con != null)
            con.close();
    }

}

From source file:imageviewer.system.ImageViewerClient.java

private void initialize(CommandLine args) {

    // First, process all the different command line arguments that we
    // need to override and/or send onwards for initialization.

    boolean fullScreen = (args.hasOption("fullscreen")) ? true : false;
    String dir = (args.hasOption("dir")) ? args.getOptionValue("dir") : null;
    String type = (args.hasOption("type")) ? args.getOptionValue("type") : "DICOM";
    String prefix = (args.hasOption("client")) ? args.getOptionValue("client") : null;

    LOG.info("Java home environment: " + System.getProperty("java.home"));

    // Logging system taken care of through properties file.  Check
    // for JAI.  Set up JAI accordingly with the size of the cache
    // tile and to recycle cached tiles as needed.

    verifyJAI();/*from   w w  w.ja v a2 s  .  com*/
    TileCache tc = JAI.getDefaultInstance().getTileCache();
    tc.setMemoryCapacity(32 * 1024 * 1024);
    TileScheduler ts = JAI.createTileScheduler();
    ts.setPriority(Thread.MAX_PRIORITY);
    JAI.getDefaultInstance().setTileScheduler(ts);
    JAI.getDefaultInstance().setRenderingHint(JAI.KEY_CACHED_TILE_RECYCLING_ENABLED, Boolean.TRUE);

    // Set up the frame and everything else.  First, try and set the
    // UI manager to use our look and feel because it's groovy and
    // lets us control the GUI components much better.

    try {
        UIManager.setLookAndFeel(new ImageViewerLookAndFeel());
        LookAndFeelAddons.setAddon(ImageViewerLookAndFeelAddons.class);
    } catch (Exception exc) {
        LOG.error("Could not set imageViewer L&F.");
    }

    // Load up the ApplicationContext information...

    ApplicationContext ac = ApplicationContext.getContext();
    if (ac == null) {
        LOG.error("Could not load configuration, exiting.");
        System.exit(1);
    }

    // Override the client node information based on command line
    // arguments...Make sure that the files are there, otherwise just
    // default to a local configuration.

    String hostname = new String("localhost");
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (Exception exc) {
    }

    String[] gatewayConfigs = (prefix != null)
            ? (new String[] { "resources/server/" + prefix + "GatewayConfig.xml",
                    (String) ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                    "resources/server/" + hostname + "GatewayConfig.xml",
                    "resources/server/localGatewayConfig.xml" })
            : (new String[] { (String) ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                    "resources/server/" + hostname + "GatewayConfig.xml",
                    "resources/server/localGatewayConfig.xml" });
    String[] nodeConfigs = (prefix != null)
            ? (new String[] { "resources/server/" + prefix + "NodeConfig.xml",
                    (String) ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                    "resources/server/" + hostname + "NodeConfig.xml", "resources/server/localNodeConfig.xml" })
            : (new String[] { (String) ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                    "resources/server/" + hostname + "NodeConfig.xml",
                    "resources/server/localNodeConfig.xml" });

    for (int loop = 0; loop < gatewayConfigs.length; loop++) {
        String s = gatewayConfigs[loop];
        if ((s != null) && (s.length() != 0) && (!"null".equals(s))) {
            File f = new File(s);
            if (f.exists()) {
                ac.setProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG, s);
                break;
            }
        }
    }

    LOG.info("Using gateway config: " + ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG));

    for (int loop = 0; loop < nodeConfigs.length; loop++) {
        String s = nodeConfigs[loop];
        if ((s != null) && (s.length() != 0) && (!"null".equals(s))) {
            File f = new File(s);
            if (f.exists()) {
                ac.setProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE, s);
                break;
            }
        }
    }
    LOG.info("Using client config: " + ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE));

    // Load the layouts and set the default window/level manager...

    LayoutFactory.initialize();
    DefaultWindowLevelManager dwlm = new DefaultWindowLevelManager();

    // Create the main JFrame, set its behavior, and let the
    // ApplicationPanel know the glassPane and layeredPane.  Set the
    // menubar based on reading in the configuration menus.

    mainFrame = new JFrame("imageviewer");
    try {
        ArrayList<Image> iconList = new ArrayList<Image>();
        iconList.add(ImageIO.read(new File("resources/icons/mii.png")));
        iconList.add(ImageIO.read(new File("resources/icons/mii32.png")));
        mainFrame.setIconImages(iconList);
    } catch (Exception exc) {
    }

    mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    mainFrame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            int confirm = ApplicationPanel.getInstance().showDialog(
                    "Are you sure you want to quit imageViewer?", null, JOptionPane.QUESTION_MESSAGE,
                    JOptionPane.OK_CANCEL_OPTION, UIManager.getIcon("Dialog.shutdownIcon"));
            if (confirm == JOptionPane.OK_OPTION) {
                boolean hasUnsaved = SaveStack.getInstance().hasUnsavedItems();
                if (hasUnsaved) {
                    int saveResult = ApplicationPanel.getInstance().showDialog(
                            "There is still unsaved data.  Do you want to save this data in the local archive?",
                            null, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
                    if (saveResult == JOptionPane.CANCEL_OPTION)
                        return;
                    if (saveResult == JOptionPane.YES_OPTION)
                        SaveStack.getInstance().saveAll();
                }
                LOG.info("Shutting down imageServer local archive...");
                try {
                    ImageViewerClientNode.getInstance().shutdown();
                } catch (Exception exc) {
                    LOG.error("Problem shutting down imageServer local archive...");
                } finally {
                    System.exit(0);
                }
            }
        }
    });

    String menuFile = (String) ApplicationContext.getContext().getProperty(ac.CONFIG_MENUS);
    String ribbonFile = (String) ApplicationContext.getContext().getProperty(ac.CONFIG_RIBBON);
    if (menuFile != null) {
        JMenuBar mb = new JMenuBar();
        mb.setBackground(Color.black);
        MenuReader.parseFile(menuFile, mb);
        mainFrame.setJMenuBar(mb);
        ApplicationContext.getContext().setApplicationMenuBar(mb);
    } else if (ribbonFile != null) {
        RibbonReader rr = new RibbonReader();
        JRibbon jr = rr.parseFile(ribbonFile);
        mainFrame.getContentPane().add(jr, BorderLayout.NORTH);
        ApplicationContext.getContext().setApplicationRibbon(jr);
    }
    mainFrame.getContentPane().add(ApplicationPanel.getInstance(), BorderLayout.CENTER);
    ApplicationPanel.getInstance().setGlassPane((JPanel) (mainFrame.getGlassPane()));
    ApplicationPanel.getInstance().setLayeredPane(mainFrame.getLayeredPane());

    // Load specified plugins...has to occur after the menus are
    // created, btw.

    PluginLoader.initialize("config/plugins.xml");

    // Detect operating system...

    String osName = System.getProperty("os.name");
    ApplicationContext.getContext().setProperty(ApplicationContext.OS_NAME, osName);
    LOG.info("Detected operating system: " + osName);

    // Try and hack the searched library paths if it's windows so we
    // can add a local dll path...

    try {
        if (osName.contains("Windows")) {
            Field f = ClassLoader.class.getDeclaredField("usr_paths");
            f.setAccessible(true);
            String[] paths = (String[]) f.get(null);
            String[] tmp = new String[paths.length + 1];
            System.arraycopy(paths, 0, tmp, 0, paths.length);
            File currentPath = new File(".");
            tmp[paths.length] = currentPath.getCanonicalPath() + "/lib/dll/";
            f.set(null, tmp);
            f.setAccessible(false);
        }
    } catch (Exception exc) {
        LOG.error("Error attempting to dynamically set library paths.");
    }

    // Get screen resolution...

    GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
            .getDefaultConfiguration();
    Rectangle r = gc.getBounds();
    LOG.info("Detected screen resolution: " + (int) r.getWidth() + "x" + (int) r.getHeight());

    // Try and see if Java3D is installed, and if so, what version...

    try {
        VirtualUniverse vu = new VirtualUniverse();
        Map m = vu.getProperties();
        String s = (String) m.get("j3d.version");
        LOG.info("Detected Java3D version: " + s);
    } catch (Throwable t) {
        LOG.info("Unable to detect Java3D installation");
    }

    // Try and see if native JOGL is installed...

    try {
        System.loadLibrary("jogl");
        ac.setProperty(ApplicationContext.JOGL_DETECTED, Boolean.TRUE);
        LOG.info("Detected native libraries for JOGL");
    } catch (Throwable t) {
        LOG.info("Unable to detect native JOGL installation");
        ac.setProperty(ApplicationContext.JOGL_DETECTED, Boolean.FALSE);
    }

    // Start the local client node to connect to the network and the
    // local archive running on this machine...Thread the connection
    // process so it doesn't block the imageViewerClient creating this
    // instance.  We may not be connected to the given gateway, so the
    // socketServer may go blah...

    final boolean useNetwork = (args.hasOption("nonet")) ? false : true;
    ApplicationPanel.getInstance().addStatusMessage("ImageViewer is starting up, please wait...");
    if (useNetwork)
        LOG.info("Starting imageServer client to join network - please wait...");
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                ImageViewerClientNode.getInstance(
                        (String) ApplicationContext.getContext()
                                .getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                        (String) ApplicationContext.getContext()
                                .getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                        useNetwork);
                ApplicationPanel.getInstance().addStatusMessage("Ready");
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    });
    t.setPriority(9);
    t.start();

    this.fullScreen = fullScreen;
    mainFrame.setUndecorated(fullScreen);

    // Set the view to encompass the default screen.

    if (fullScreen) {
        Insets i = Toolkit.getDefaultToolkit().getScreenInsets(gc);
        mainFrame.setLocation(r.x + i.left, r.y + i.top);
        mainFrame.setSize(r.width - i.left - i.right, r.height - i.top - i.bottom);
    } else {
        mainFrame.setSize(1100, 800);
        mainFrame.setLocation(r.x + 200, r.y + 100);
    }

    if (dir != null)
        ApplicationPanel.getInstance().load(dir, type);

    timer = new Timer();
    timer.schedule(new GarbageCollectionTimer(), 5000, 2500);
    mainFrame.setVisible(true);
}

From source file:ded.ui.DiagramController.java

@Override
public void paint(Graphics g) {
    // Swing JPanel is double buffered already, but that is not
    // sufficient to avoid rendering bugs on Apple computers
    // with HiDPI/Retina displays.  This is an attempt at a
    // hack that might circumvent it, effectively triple-buffering
    // the rendering step.
    if (this.tripleBufferMode != 0) {
        // The idea here is if I create an in-memory image with no
        // initial association with the display, whatever hacks Apple
        // has added should not kick in, and I get unscaled pixel
        // rendering.
        BufferedImage bi;//from  www .  j  a va  2  s  .com

        if (this.tripleBufferMode == -1) {
            // This is not right because we might be drawing on a
            // different screen than the "default" screen.  Also, I
            // am worried that a "compatible" image might be one
            // subject to the scaling effects I'm trying to avoid.
            GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
            GraphicsConfiguration gc = gd.getDefaultConfiguration();
            bi = gc.createCompatibleImage(this.getWidth(), this.getHeight());
        } else {
            // This is not ideal because the color representation
            // for this hidden image may not match that of the display,
            // necessitating a conversion during 'drawImage'.
            try {
                bi = new BufferedImage(this.getWidth(), this.getHeight(), this.tripleBufferMode);
            } catch (IllegalArgumentException e) {
                // This would happen if 'tripleBufferMode' were invalid.
                if (this.tripleBufferMode == BufferedImage.TYPE_INT_ARGB) {
                    // I don't know how this could happen.  Re-throw.
                    this.log("creating a BufferedImage with TYPE_INT_ARGB failed: "
                            + Util.getExceptionMessage(e));
                    this.log("re-throwing exception...");
                    throw e;
                } else {
                    // Change it to something known to be valid and try again.
                    this.log("creating a BufferedImage with imageType " + this.tripleBufferMode + " failed: "
                            + Util.getExceptionMessage(e));
                    this.log("switching type to TYPE_INT_ARGB and re-trying...");
                    this.tripleBufferMode = BufferedImage.TYPE_INT_ARGB;
                    this.paint(g);
                    return;
                }
            }
        }
        Graphics g2 = bi.createGraphics();
        this.innerPaint(g2);
        g2.dispose();

        g.drawImage(bi, 0, 0, null /*imageObserver*/);
    } else {
        this.innerPaint(g);
    }

    if (this.fpsMeasurementMode) {
        // Immediately trigger another paint cycle.
        this.repaint();
    }
}