Example usage for javax.swing JPanel setBackground

List of usage examples for javax.swing JPanel setBackground

Introduction

In this page you can find the example usage for javax.swing JPanel setBackground.

Prototype

@BeanProperty(preferred = true, visualUpdate = true, description = "The background color of the component.")
public void setBackground(Color bg) 

Source Link

Document

Sets the background color of this component.

Usage

From source file:com.mirth.connect.client.ui.SettingsPanelResources.java

private void initComponents() {
    setLayout(new MigLayout("insets 12, novisualpadding, hidemode 3, fill"));
    setBackground(UIConstants.BACKGROUND_COLOR);

    JPanel resourceListPanel = new JPanel(new MigLayout("insets 0, novisualpadding, hidemode 3, fill"));
    resourceListPanel.setBackground(getBackground());
    resourceListPanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(204, 204, 204)), "Resources",
            TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Tahoma", 1, 11)));

    resourceTable = new MirthTable();
    resourceTable.setModel(//ww  w .  j a v a  2s  . com
            new RefreshTableModel(new Object[] { "Properties", "Name", "Type", "Global Scripts" }, 0) {
                @Override
                public boolean isCellEditable(int row, int column) {
                    if (row == 0) {
                        return column == GLOBAL_SCRIPTS_COLUMN;
                    } else {
                        return column == NAME_COLUMN || column == TYPE_COLUMN
                                || column == GLOBAL_SCRIPTS_COLUMN;
                    }
                }
            });
    resourceTable.setDragEnabled(false);
    resourceTable.setRowSelectionAllowed(true);
    resourceTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    resourceTable.setRowHeight(UIConstants.ROW_HEIGHT);
    resourceTable.setFocusable(true);
    resourceTable.setOpaque(true);
    resourceTable.getTableHeader().setReorderingAllowed(false);
    resourceTable.setEditable(true);
    resourceTable.setSortable(false);

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        resourceTable.setHighlighters(HighlighterFactory.createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR,
                UIConstants.BACKGROUND_COLOR));
    }

    for (ResourceClientPlugin plugin : LoadedExtensions.getInstance().getResourceClientPlugins().values()) {
        propertiesPanelMap.put(plugin.getType(), plugin.getPropertiesPanel());
    }

    resourceTable.getColumnModel().getColumn(NAME_COLUMN).setCellEditor(new NameEditor());
    resourceTable.getColumnExt(NAME_COLUMN).setToolTipText("The unique name of the resource.");

    resourceTable.getColumnModel().getColumn(TYPE_COLUMN).setMinWidth(100);
    resourceTable.getColumnModel().getColumn(TYPE_COLUMN).setMaxWidth(200);
    resourceTable.getColumnModel().getColumn(TYPE_COLUMN)
            .setCellRenderer(new ComboBoxRenderer(propertiesPanelMap.keySet().toArray()));
    resourceTable.getColumnModel().getColumn(TYPE_COLUMN).setCellEditor(new ComboBoxEditor(resourceTable,
            propertiesPanelMap.keySet().toArray(), 1, true, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent evt) {
                    typeComboBoxActionPerformed(evt);
                }
            }));
    resourceTable.getColumnExt(TYPE_COLUMN).setToolTipText("The type of resource.");

    resourceTable.getColumnModel().getColumn(GLOBAL_SCRIPTS_COLUMN).setMinWidth(80);
    resourceTable.getColumnModel().getColumn(GLOBAL_SCRIPTS_COLUMN).setMaxWidth(80);
    resourceTable.getColumnModel().getColumn(GLOBAL_SCRIPTS_COLUMN).setCellRenderer(new CheckBoxRenderer());
    resourceTable.getColumnModel().getColumn(GLOBAL_SCRIPTS_COLUMN).setCellEditor(new CheckBoxEditor());
    resourceTable.getColumnExt(GLOBAL_SCRIPTS_COLUMN).setToolTipText(
            "<html>If checked, libraries associated with the corresponding<br/>resource will be included in global script contexts.</html>");

    resourceTable.removeColumn(resourceTable.getColumnModel().getColumn(PROPERTIES_COLUMN));

    resourceTable.getSelectionModel().addListSelectionListener(this);

    resourceTable
            .setToolTipText("<html>Add or remove resources to use<br/>in specific channels/connectors.</html>");

    resourceTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
            .put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "selectNextColumnCell");

    resourceListPanel.add(new JScrollPane(resourceTable), "grow, push");

    add(resourceListPanel, "grow, h 20%");

    for (ResourcePropertiesPanel panel : propertiesPanelMap.values()) {
        add(panel, "newline, grow, h 80%");
    }

    fillerPanel = new JPanel(new MigLayout("insets 5, novisualpadding, hidemode 3, fill", "", "[][grow]"));
    fillerPanel.setBackground(getBackground());
    fillerPanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(204, 204, 204)), "Resource Settings",
            TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Tahoma", 1, 11)));
    fillerLabel = new JLabel("Select a resource from the table above.");
    fillerPanel.add(fillerLabel);

    exceptionTextPane = new JTextPane();
    exceptionTextPane.setBackground(new Color(224, 223, 227));
    exceptionTextPane.setEditable(false);
    exceptionScrollPane = new JScrollPane(exceptionTextPane);
    fillerPanel.add(exceptionScrollPane, "newline, grow");

    add(fillerPanel, "newline, grow, h 80%");
}

From source file:com.mirth.connect.client.ui.panels.connectors.PollingSettingsPanel.java

private void initLayout() {
    setBackground(UIConstants.BACKGROUND_COLOR);

    if (channelContext) {
        setLayout(new MigLayout("novisualpadding, hidemode 3, insets 0, gap 6 4", "[]12[]"));
        setBorder(javax.swing.BorderFactory.createTitledBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(204, 204, 204)), "Polling Settings",
                TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Tahoma", 1, 11)));

        add(scheduleTypeLabel, "right");
        add(scheduleTypeComboBox, "split");
        add(nextPollLabel, "gapbefore 6");

        add(new JLabel("Poll Once on Start:"), "newline, right");
        add(yesStartPollRadioButton, "split");
        add(noStartPollRadioButton, "gapbefore 5");
    } else {/* www. j a  v a2s  .c o m*/
        setLayout(new MigLayout("novisualpadding, hidemode 3, insets 0, gap 6 6", "[]12[]"));
        add(scheduleTypeLabel, "right");
        add(scheduleTypeComboBox);
    }

    add(timeSettingsLabel, "newline, right");
    scheduleSettingsPanel.setLayout(new MigLayout("novisualpadding, hidemode 3, insets 0, gap 6 6"));

    scheduleSettingsPanel.add(pollingTimePicker, "w 70!");

    pollingFrequencySettingsPanel.setLayout(new MigLayout("novisualpadding, insets 0, gap 6 6"));
    pollingFrequencySettingsPanel.add(pollingFrequencyField, "w 75!, left");
    pollingFrequencySettingsPanel.add(pollingFrequencyTypeComboBox, "left");
    scheduleSettingsPanel.add(pollingFrequencySettingsPanel);

    pollingCronSettingsPanel.setLayout(new MigLayout("novisualpadding, insets 0, gap 6 6"));
    pollingCronSettingsPanel.add(cronScrollPane, "h 74!, w 400!");

    JPanel buttonPanel = new JPanel(new MigLayout("novisualpadding, insets 0, gap 6 6"));
    buttonPanel.setBackground(UIConstants.BACKGROUND_COLOR);
    buttonPanel.add(addJobButton, "wrap, w 50!");
    buttonPanel.add(deleteJobButton, "w 50!");
    pollingCronSettingsPanel.add(buttonPanel, "top");
    scheduleSettingsPanel.add(pollingCronSettingsPanel);

    add(scheduleSettingsPanel, "split");
    add(advancedSettingsButton, "gapbefore 6, h 21!, w 22!");
}

From source file:edu.ku.brc.af.tasks.subpane.StatsPane.java

/**
 * Loads all the panels./* ww  w .  j  av a 2 s .  c  o  m*/
 */
protected void init() {
    JComponent parentComp = upperDisplayComp != null ? upperDisplayComp : this;
    for (Component c : comps) {
        parentComp.remove(c);
    }
    comps.clear();

    if (centerPanel != null) {
        remove(centerPanel);
    }

    Element rootElement = null;
    try {
        rootElement = AppContextMgr.getInstance().getResourceAsDOM(resourceName);
        if (rootElement == null) {
            throw new RuntimeException("Couldn't find resource [" + resourceName + "]"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        // count up rows and column
        StringBuilder rowsDef = new StringBuilder(128);

        boolean hasResBundle = false;
        Element panelEl = (Element) rootElement.selectObject("/panel");
        String resBundleName = XMLHelper.getAttr(panelEl, "resource", null);
        if (StringUtils.isNotEmpty(resBundleName)) {
            hasResBundle = true;
            UIRegistry.loadAndPushResourceBundle(resBundleName);
        }

        List<?> rows = rootElement.selectNodes("/panel/row"); //$NON-NLS-1$
        int maxCols = 0;
        for (Object obj : rows) {
            Element rowElement = (Element) obj;
            List<?> boxes = rowElement.selectNodes("box"); //$NON-NLS-1$
            maxCols = Math.max(maxCols, boxes.size());
            if (rowsDef.length() > 0) {
                rowsDef.append(",15dlu,"); //$NON-NLS-1$
            }
            rowsDef.append("top:p"); //$NON-NLS-1$
        }

        int preferredWidth = PREFERREDWIDTH;
        int spacing = SPACING;

        String colDefs = createDuplicateJGoodiesDef("f:min(" + preferredWidth + "px;p)", spacing + "px", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                maxCols);
        FormLayout formLayout = new FormLayout(colDefs, rowsDef.toString());
        PanelBuilder builder = new PanelBuilder(formLayout);
        CellConstraints cc = new CellConstraints();

        int y = 1;
        for (Object obj : rows) {
            Element rowElement = (Element) obj;

            int x = 1;
            List<?> boxes = rowElement.selectNodes("box"); //$NON-NLS-1$
            for (Object bo : boxes) {
                Element boxElement = (Element) bo;

                String type = getAttr(boxElement, "type", "box"); //$NON-NLS-1$ //$NON-NLS-2$
                int colSpan = getAttr(boxElement, "colspan", 1); //$NON-NLS-1$

                Component comp = null;
                if (type.equalsIgnoreCase("bar chart")) //$NON-NLS-1$
                {
                    String statName = getAttr(boxElement, "name", null); //$NON-NLS-1$

                    if (isNotEmpty(statName)) {
                        BarChartPanel bcp = (BarChartPanel) StatsMgr.createStatPane(statName);
                        int width = colSpan > 1 ? ((maxCols * preferredWidth) + ((maxCols - 1) * spacing))
                                : preferredWidth;
                        // We start by assuming the chart will be square which is why we use
                        // preferredWidth as the height, and then we calculate the new width
                        bcp.setPreferredChartSize(width, preferredWidth);
                        comp = bcp;
                        //comp.setSize(new Dimension(preferredWidth, preferredWidth));
                        //comp.setPreferredSize(new Dimension(preferredWidth, preferredWidth));
                        //comp.invalidate();
                        //comp.doLayout();
                        //System.out.println(comp.getSize());
                        validate();
                        doLayout();
                        repaint();
                    }

                } else // The default is "Box"
                {
                    comp = processBox(boxElement, hasResBundle);
                }

                if (comp != null) {
                    comps.add(comp);

                    if (colSpan == 1) {
                        builder.add(comp, cc.xy(x, y));

                    } else {
                        builder.add(comp, cc.xywh(x, y, colSpan, 1));
                    }
                    x += 2;
                }
            } // boxes
            y += 2;
        }

        if (hasResBundle) {
            UIRegistry.popResourceBundle();
        }

        setBackground(bgColor);

        JPanel statPanel = builder.getPanel();
        statPanel.setBackground(Color.WHITE);

        boolean hasUpper = upperDisplayComp != null;

        builder = new PanelBuilder(new FormLayout("C:P:G", hasUpper ? "50px,p,20px,p" : "p")); //$NON-NLS-1$ //$NON-NLS-2$

        if (hasUpper) {
            y = 2;
            builder.add(upperDisplayComp, cc.xy(1, y));
            y += 2;

        } else {
            y = 1;
        }

        builder.add(statPanel, cc.xy(1, y));
        centerPanel = builder.getPanel();

        centerPanel.setBackground(Color.WHITE);

        //For Tiling
        if (isTiled()) {
            centerPanel.setOpaque(false);
            setOpaque(false);
            statPanel.setOpaque(false);
        }

        centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        add(centerPanel, BorderLayout.CENTER);

        if (updateBtn == null) {
            PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g,p,4px", "4px,p,4px"));
            //pb.setOpaque(false);
            updateBtn = new FadeBtn(UIRegistry.getResourceString("STS_UPDATE"));
            pb.add(updateBtn, cc.xy(2, 2));
            pb.getPanel().setBackground(bgColor);
            add(pb.getPanel(), BorderLayout.SOUTH);

            updateBtn.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    init();
                }
            });
        }

        centerPanel.validate();
        validate();
        doLayout();

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(StatsPane.class, ex);
        log.error(ex);
        ex.printStackTrace();
    }

}

From source file:ecg.ecgshow.ECGShowUI.java

private void createGuardData() {
    GuardDataPanel = new JPanel();
    GuardDataPanel.setBackground(new Color(0, 150, 255));
    //        GuardDataPanel.setBounds();
    //        BoxLayout layout=new BoxLayout(GuardDataPanel,BoxLayout.Y_AXIS);
    //        GuardDataPanel.setLayout(layout);
    GroupLayout layout = new GroupLayout(GuardDataPanel);
    GuardDataPanel.setLayout(layout);//from w  ww .j  av  a 2  s.  co  m
    JPanel temperatureData = new JPanel();
    temperatureData.setLayout(new FlowLayout());
    //        temperatureData.setLayout(null);
    //        temperatureData.setBounds(0,0,(int) (WIDTH * 0.14), (int) (HEIGHT * 0.15));
    temperatureData.setSize((int) (WIDTH * 0.16), (int) (HEIGHT * 0.11));
    temperatureData.setBackground(new Color(0, 150, 255));
    temperatureLabel = new JLabel("--.- ");
    temperatureLabel.setFont(loadFont("LED.tff", (float) (HEIGHT * 0.070)));
    temperatureLabel.setBackground(new Color(0, 150, 255));
    temperatureLabel.setForeground(Color.RED);
    //        temperatureLabel.setBounds(0,0,200,100);
    temperatureLabel.setOpaque(true);
    JLabel temperatureLabelName = new JLabel(" ");
    temperatureLabelName.setFont(new Font("SansSerif", 0, (int) (HEIGHT * 0.020)));
    temperatureLabelName.setBackground(new Color(0, 150, 255));
    temperatureLabelName.setForeground(Color.BLACK);
    temperatureLabelName.setBounds(0, 0, 100, 100);
    temperatureLabelName.setOpaque(true); //??
    temperatureData.add(temperatureLabelName);
    temperatureData.add(temperatureLabel);
    //        JPanel emptyPanel=new JPanel();
    //        emptyPanel.setSize((int)(WIDTH*0.14),(int)(HEIGHT*0.2));
    //        emptyPanel.setBackground(new Color(0,150,255));
    //        GuardDataPanel.add(emptyPanel);

    JPanel lightValueData = new JPanel();
    lightValueData.setLayout(new BorderLayout());
    lightValueData.setBackground(new Color(0, 150, 255));
    //        lightValueData.setBounds(0,(int)(HEIGHT*0.28),(int)(WIDTH*0.14),(int)(HEIGHT*0.30));
    lightValueData.setSize((int) (WIDTH * 0.14), (int) (HEIGHT * 0.22));
    lightValueDataSet = new DefaultValueDataset();
    DialPlot lightValueDialPlot = new DialPlot();
    lightValueDialPlot.setDataset(lightValueDataSet);
    StandardDialFrame dialFrame = new StandardDialFrame();
    dialFrame.setVisible(false);
    lightValueDialPlot.setDialFrame(dialFrame);

    GradientPaint gradientpaint = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(),
            new Color(170, 170, 170));
    DialBackground dialBackground = new DialBackground(gradientpaint);
    dialBackground.setGradientPaintTransformer(
            new StandardGradientPaintTransformer(GradientPaintTransformType.VERTICAL));
    lightValueDialPlot.setBackground(dialBackground);
    // ??
    DialTextAnnotation dialtextannotation = new DialTextAnnotation("");
    dialtextannotation.setFont(new Font("Dialog", 0, (int) (0.016 * HEIGHT)));
    dialtextannotation.setRadius(0.1D);
    lightValueDialPlot.addLayer(dialtextannotation);

    DialValueIndicator dialValueIndicator = new DialValueIndicator(0);
    dialValueIndicator.setFont(new Font("Dialog", Font.PLAIN, (int) (0.011 * HEIGHT)));
    dialValueIndicator.setOutlinePaint(Color.darkGray);
    dialValueIndicator.setRadius(0.4D);
    dialValueIndicator.setAngle(-90.0);
    lightValueDialPlot.addLayer(dialValueIndicator);

    StandardDialScale dialScale = new StandardDialScale();
    dialScale.setLowerBound(0D); // 
    dialScale.setUpperBound(1024); // 
    dialScale.setMajorTickIncrement(100);
    dialScale.setStartAngle(-120D); // 120,?
    dialScale.setExtent(-300D); // 300,?
    dialScale.setTickRadius(0.85D); // ,
    dialScale.setTickLabelOffset(0.1D); // ,0

    bloodDialRange = new StandardDialRange(500D, 750D, Color.red);
    bloodDialRange.setInnerRadius(0.52000000000000002D);
    bloodDialRange.setOuterRadius(0.55000000000000004D);
    lightValueDialPlot.addLayer(bloodDialRange);
    //
    bubbleDialRange = new StandardDialRange(0D, 500D, Color.black);
    bubbleDialRange.setInnerRadius(0.52000000000000002D);
    bubbleDialRange.setOuterRadius(0.55000000000000004D);
    lightValueDialPlot.addLayer(bubbleDialRange);
    //
    normalDialRange = new StandardDialRange(750D, 1024D, Color.green);
    normalDialRange.setInnerRadius(0.52000000000000002D);
    normalDialRange.setOuterRadius(0.55000000000000004D);
    lightValueDialPlot.addLayer(normalDialRange);

    dialScale.setTickLabelFont(new Font("Dialog", 0, (int) (0.011 * HEIGHT))); // 
    lightValueDialPlot.addScale(0, dialScale);

    DialPointer.Pointer pointer = new DialPointer.Pointer();
    lightValueDialPlot.addPointer(pointer);
    lightValueDialPlot.mapDatasetToScale(0, 0);
    DialCap dialCap = new DialCap();
    dialCap.setRadius(0.07D);
    JFreeChart lightValueDialChart = new JFreeChart(lightValueDialPlot);
    lightValueDialChart.setBackgroundPaint(new Color(0, 150, 255));
    lightValueDialChart.setTitle("??");
    lightValueDialChart.getTitle().setFont(new Font("SansSerif", 0, (int) (HEIGHT * 0.020)));
    ChartPanel lightValueDialChartPanel = new ChartPanel(lightValueDialChart, (int) (WIDTH * 0.15),
            (int) (HEIGHT * 0.27), 0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, true, true, false, true, false,
            false);
    lightValueData.add(lightValueDialChartPanel, BorderLayout.CENTER);
    layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                            .addComponent(temperatureData, GroupLayout.Alignment.LEADING)
                            .addComponent(lightValueData, GroupLayout.Alignment.LEADING))));
    layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                    .addGap((int) (HEIGHT * 0.05), (int) (HEIGHT * 0.05), (int) (HEIGHT * 0.05))
                    .addComponent(temperatureData)
                    .addGap((int) (HEIGHT * 0.05), (int) (HEIGHT * 0.05), (int) (HEIGHT * 0.05))
                    .addComponent(lightValueData)
                    .addGap((int) (HEIGHT * 0.05), (int) (HEIGHT * 0.05), (int) (HEIGHT * 0.05))));

    //        JPanel alarmMessage=new JPanel();
    //        alarmMessage.setBackground(new Color(0,150,255));
    //        alarmMessLabel=new JLabel("");
    //        alarmMessLabel.setFont(new Font("SansSerif", 0, (int)(HEIGHT *0.020)));
    //        alarmMessLabel.setBackground(new Color(0,150,255));
    //        alarmMessage.add(alarmMessLabel);
    //        GuardDataPanel.add(alarmMessage);
}

From source file:Citas.FrameCita.java

private void cambiarColorPanel(JPanel panel, Color color) {

    panel.setBackground(color);

}

From source file:com.jamfsoftware.jss.healthcheck.ui.HealthReport.java

/**
 * Creates a new Health Report JPanel window from the Health Check JSON string.
 * Will throw errors if the JSON is not formatted correctly.
 *//*w ww .  j a v a2  s  . co  m*/
public HealthReport(final String JSON) throws Exception {
    LOGGER.debug("[DEBUG] - JSON String (Copy entire below line)");
    LOGGER.debug(JSON.replace("\n", ""));
    LOGGER.debug("Attempting to parse Health Report JSON");

    JsonElement report = new JsonParser().parse(JSON);
    JsonObject healthcheck = ((JsonObject) report).get("healthcheck").getAsJsonObject();
    Boolean show_system_info = true;
    JsonObject system = null;
    //Check if the check JSON contains system information and show/hide panels accordingly later.
    system = ((JsonObject) report).get("system").getAsJsonObject();

    final JsonObject data = ((JsonObject) report).get("checkdata").getAsJsonObject();

    this.JSSURL = extractData(healthcheck, "jss_url");

    if (extractData(system, "iscloudjss").contains("true")) {
        show_system_info = false;
        isCloudJSS = true;
    }

    PanelIconGenerator iconGen = new PanelIconGenerator();
    PanelGenerator panelGen = new PanelGenerator();

    //Top Level Frame
    final JFrame frame = new JFrame("JSS Health Check Report");

    //Top Level Content
    JPanel outer = new JPanel(new BorderLayout());

    //Two Blank Panels for the Sides
    JPanel blankLeft = new JPanel();
    blankLeft.add(new JLabel("        "));
    JPanel blankRight = new JPanel();
    blankRight.add(new JLabel("        "));
    blankLeft.setMinimumSize(new Dimension(100, 100));
    blankRight.setMinimumSize(new Dimension(100, 100));
    //Header
    JPanel header = new JPanel();
    header.add(new JLabel("Total Computers: " + extractData(healthcheck, "totalcomputers")));
    header.add(new JLabel("Total Mobile Devices: " + extractData(healthcheck, "totalmobile")));
    header.add(new JLabel("Total Users: " + extractData(healthcheck, "totalusers")));
    int total_devices = Integer.parseInt(extractData(healthcheck, "totalcomputers"))
            + Integer.parseInt(extractData(healthcheck, "totalmobile"));
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
    Date dateobj = new Date();
    header.add(new JLabel("JSS Health Check Report Performed On " + df.format(dateobj)));
    //Foooter
    JPanel footer = new JPanel();
    JButton view_report_json = new JButton("View Report JSON");
    footer.add(view_report_json);
    JButton view_activation_code = new JButton("View Activation Code");
    footer.add(view_activation_code);
    JButton test_again = new JButton("Run Test Again");
    footer.add(test_again);
    JButton view_text_report = new JButton("View Text Report");
    footer.add(view_text_report);
    JButton about_and_terms = new JButton("About and Terms");
    footer.add(about_and_terms);
    //Middle Content, set the background white and give it a border
    JPanel content = new JPanel(new GridLayout(2, 3));
    content.setBackground(Color.WHITE);
    content.setBorder(BorderFactory.createLineBorder(Color.BLACK));

    //Setup Outer Placement
    outer.add(header, BorderLayout.NORTH);
    outer.add(footer, BorderLayout.SOUTH);
    outer.add(blankLeft, BorderLayout.WEST);
    outer.add(blankRight, BorderLayout.EAST);
    outer.add(content, BorderLayout.CENTER);

    //Don't show system info if it is hosted.
    JPanel system_info = null;
    JPanel database_health = null;
    if (show_system_info) {
        //Read all of the System information variables from the JSON and perform number conversions.
        String[][] sys_info = { { "Operating System", extractData(system, "os") },
                { "Java Version", extractData(system, "javaversion") },
                { "Java Vendor", extractData(system, "javavendor") },
                { "Processor Cores", extractData(system, "proc_cores") },
                { "Is Clustered?", extractData(system, "clustering") },
                { "Web App Directory", extractData(system, "webapp_dir") },
                { "Free Memory",
                        Double.toString(
                                round((Double.parseDouble(extractData(system, "free_memory")) / 1000000000), 2))
                                + " GB" },
                { "Max Memory",
                        Double.toString(
                                round((Double.parseDouble(extractData(system, "max_memory")) / 1000000000), 2))
                                + " GB" },
                { "Memory currently in use", Double.toString(round(
                        (Double.parseDouble(extractData(system, "memory_currently_in_use")) / 1000000000), 2))
                        + " GB" },
                { "Total space",
                        Double.toString(
                                round((Double.parseDouble(extractData(system, "total_space")) / 1000000000), 2))
                                + " GB" },
                { "Free Space",
                        Double.toString(round(
                                (Double.parseDouble(extractData(system, "usable_space")) / 1000000000), 2))
                                + " GB" } };
        //Generate the system info panel.
        String systemInfoIcon = iconGen.getSystemInfoIconType(
                Integer.parseInt(extractData(healthcheck, "totalcomputers"))
                        + Integer.parseInt(extractData(healthcheck, "totalmobile")),
                extractData(system, "javaversion"), Double.parseDouble(extractData(system, "max_memory")));
        system_info = panelGen.generateContentPanelSystem("System Info", sys_info, "JSS Minimum Requirements",
                "http://www.jamfsoftware.com/resources/casper-suite-system-requirements/", systemInfoIcon);

        //Get all of the DB information.
        String[][] db_health = { { "Database Size", extractData(system, "database_size") + " MB" } };
        if (extractData(system, "database_size").equals("0")) {
            db_health[0][0] = "Unable to connect to database.";
        }

        String[][] large_sql_tables = extractArrayData(system, "largeSQLtables", "table_name", "table_size");
        String[][] db_health_for_display = ArrayUtils.addAll(db_health, large_sql_tables);
        //Generate the DB Health panel.
        String databaseIconType = iconGen.getDatabaseInfoIconType(total_devices,
                Double.parseDouble(extractData(system, "database_size")),
                extractArrayData(system, "largeSQLtables", "table_name", "table_size").length);
        database_health = panelGen.generateContentPanelSystem("Database Health", db_health_for_display,
                "Too Large SQL Tables", "https://google.com", databaseIconType);
        if (!databaseIconType.equals("green")) {
            this.showLargeDatabase = true;
        }
    }

    int password_strenth = 0;
    if (extractData(data, "password_strength", "uppercase?").contains("true")) {
        password_strenth++;
    }
    if (extractData(data, "password_strength", "lowercase?").contains("true")) {
        password_strenth++;
    }
    if (extractData(data, "password_strength", "number?").contains("true")) {
        password_strenth++;
    }
    if (extractData(data, "password_strength", "spec_chars?").contains("true")) {
        password_strenth++;
    }
    String password_strength_desc = "";
    if (password_strenth == 4) {
        password_strength_desc = "Excellent";
    } else if (password_strenth == 3 || password_strenth == 2) {
        password_strength_desc = "Good";
    } else if (password_strenth == 1) {
        this.strongerPassword = true;
        password_strength_desc = "Poor";
    } else {
        this.strongerPassword = true;
        password_strength_desc = "Needs Updating";
    }

    if (extractData(data, "loginlogouthooks", "is_configured").contains("false")) {
        this.loginInOutHooks = true;
    }

    try {
        if (Integer.parseInt(extractData(data, "device_row_counts", "computers").trim()) != Integer
                .parseInt(extractData(data, "device_row_counts", "computers_denormalized").trim())) {
            this.computerDeviceTableCountMismatch = true;
        }

        if (Integer.parseInt(extractData(data, "device_row_counts", "mobile_devices").trim()) != Integer
                .parseInt(extractData(data, "device_row_counts", "mobile_devices_denormalized").trim())) {
            this.mobileDeviceTableCountMismatch = true;
        }
    } catch (Exception e) {
        System.out.println("Unable to parse device row counts.");
    }

    if ((extractData(system, "mysql_version").contains("5.6.16")
            || extractData(system, "mysql_version").contains("5.6.20"))
            && (extractData(system, "os").contains("OS X") || extractData(system, "os").contains("Mac")
                    || extractData(system, "os").contains("OSX"))) {
        this.mysql_osx_version_bug = true;
    }

    //Get all of the information for the JSS ENV and generate the panel.
    String[][] env_info = {
            { "Checkin Frequency", extractData(data, "computercheckin", "frequency") + " Minutes" },
            { "Log Flushing", extractData(data, "logflushing", "log_flush_time") },
            { "Log In/Out Hooks", extractData(data, "loginlogouthooks", "is_configured") },
            { "Computer EA", extractData(data, "computerextensionattributes", "count") },
            { "Mobile Deivce EA", extractData(data, "mobiledeviceextensionattributes", "count") },
            { "Password Strength", password_strength_desc },
            { "SMTP Server", extractData(data, "smtpserver", "server") },
            { "Sender Email", extractData(data, "smtpserver", "sender_email") },
            { "GSX Connection", extractData(data, "gsxconnection", "status") } };
    String[][] vpp_accounts = extractArrayData(data, "vppaccounts", "name", "days_until_expire");
    String[][] ldap_servers = extractArrayData(data, "ldapservers", "name", "type", "address", "id");
    String envIconType = iconGen.getJSSEnvIconType(Integer.parseInt(extractData(healthcheck, "totalcomputers")),
            Integer.parseInt(extractData(data, "computercheckin", "frequency")),
            Integer.parseInt(extractData(data, "computerextensionattributes", "count")),
            Integer.parseInt(extractData(data, "mobiledeviceextensionattributes", "count")));
    JPanel env = panelGen.generateContentPanelEnv("JSS Environment", env_info, vpp_accounts, ldap_servers, "",
            "", envIconType);

    //Get all of the group information from the JSON, merge the arrays, and then generate the groups JPanel.
    String[][] groups_1 = ArrayUtils.addAll(
            extractArrayData(data, "computergroups", "name", "nested_groups_count", "criteria_count", "id"),
            extractArrayData(data, "mobiledevicegroups", "name", "nested_groups_count", "criteria_count",
                    "id"));
    String[][] groups_2 = ArrayUtils.addAll(groups_1,
            extractArrayData(data, "usergroups", "name", "nested_groups_count", "criteria_count", "id"));
    String groupIconType = iconGen.getGroupIconType("groups", countJSONObjectSize(data, "computergroups")
            + countJSONObjectSize(data, "mobiledevicegroups") + countJSONObjectSize(data, "usergroups"));
    JPanel groups = panelGen.generateContentPanelGroups("Groups", groups_2, "", "", groupIconType);
    if (groupIconType.equals("yellow") || groupIconType.equals("red")) {
        this.showGroupsHelp = true;
    }

    //Get all of the information for the printers, policies and scripts, then generate the panel.
    String[][] printers = extractArrayData(data, "printer_warnings", "model");
    String[][] policies = extractArrayData(data, "policies_with_issues", "name", "ongoing", "checkin_trigger");
    String[][] scripts = extractArrayData(data, "scripts_needing_update", "name");
    String[][] certs = { { "SSL Cert Issuer", extractData(data, "tomcat", "ssl_cert_issuer") },
            { "SLL Cert Expires", extractData(data, "tomcat", "cert_expires") },
            { "MDM Push Cert Expires", extractData(data, "push_cert_expirations", "mdm_push_cert") },
            { "Push Proxy Expires", extractData(data, "push_cert_expirations", "push_proxy") },
            { "Change Management Enabled?", extractData(data, "changemanagment", "isusinglogfile") },
            { "Log File Path:", extractData(data, "changemanagment", "logpath") } };
    String policiesScriptsIconType = iconGen.getPoliciesAndScriptsIconType(
            extractArrayData(data, "policies_with_issues", "name", "ongoing", "checkin_trigger").length,
            extractArrayData(data, "scripts_needing_update", "name").length);
    JPanel policies_scripts = panelGen.generateContentPanelPoliciesScripts(
            "Policies, Scripts, Certs and Change", policies, scripts, printers, certs, "", "",
            policiesScriptsIconType);
    if (extractArrayData(data, "policies_with_issues", "name", "ongoing", "checkin_trigger").length > 0) {
        this.showPolicies = true;
    }
    if (extractArrayData(data, "scripts_needing_update", "name").length > 0) {
        this.showScripts = true;
    }
    if (extractData(data, "changemanagment", "isusinglogfile").contains("false")) {
        this.showChange = true;
    }
    this.showCheckinFreq = iconGen.showCheckinFreq;
    this.showExtensionAttributes = iconGen.showCheckinFreq;
    this.showSystemRequirements = iconGen.showSystemRequirements;
    this.showScalability = iconGen.showScalability;
    //Update Panel Gen Variables
    updatePanelGenVariables(panelGen);

    //Generate the Help Section.
    content.add(panelGen.generateContentPanelHelp("Modifications to Consider", "", "", "blank"));
    //If contains system information, add those panels, otherwise just continue adding the rest of the panels.
    if (show_system_info) {
        content.add(system_info);
        content.add(database_health);
    }
    content.add(env);
    content.add(groups);
    content.add(policies_scripts);

    //View report action listner.
    //Opens a window with the health report JSON listed
    view_report_json.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JPanel middlePanel = new JPanel();
            middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Health Report JSON"));
            // create the middle panel components
            JTextArea display = new JTextArea(16, 58);
            display.setEditable(false);
            //Make a new GSON object so the text can be Pretty Printed.
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String pp_json = gson.toJson(JSON.trim());
            display.append(JSON);
            JScrollPane scroll = new JScrollPane(display);
            scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            //Add Textarea in to middle panel
            middlePanel.add(scroll);

            JFrame frame = new JFrame();
            frame.add(middlePanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
    //Action listener for the Terms, About and Licence button.
    //Opens a new window with the AS IS License, 3rd Party Libs used and a small about section
    about_and_terms.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JPanel middlePanel = new JPanel();
            middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "About, Licence and Terms"));
            // create the middle panel components
            JTextArea display = new JTextArea(16, 58);
            display.setEditable(false);
            display.append(StringConstants.ABOUT);
            display.append("\n\nThird Party Libraries Used:");
            display.append(
                    " Apache Commons Codec, Google JSON (gson), Java X JSON, JDOM, JSON-Simple, MySQL-connector");
            display.append(StringConstants.LICENSE);
            JScrollPane scroll = new JScrollPane(display);
            scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            //Add Textarea in to middle panel
            middlePanel.add(scroll);

            JFrame frame = new JFrame();
            frame.add(middlePanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });

    //Listener for a button click to open a window containing the activation code.
    view_activation_code.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(frame, extractData(data, "activationcode", "code") + "\nExpires: "
                    + extractData(data, "activationcode", "expires"));
        }
    });

    view_text_report.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JPanel middlePanel = new JPanel();
            middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Text Health Report"));
            // create the middle panel components
            JTextArea display = new JTextArea(16, 58);
            display.setEditable(false);
            //Make a new GSON object so the text can be Pretty Printed.
            display.append(new HealthReportHeadless(JSON).getReportString());
            JScrollPane scroll = new JScrollPane(display);
            scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            //Add Textarea in to middle panel
            middlePanel.add(scroll);

            JFrame frame = new JFrame();
            frame.add(middlePanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });

    //Listener for the Test Again button. Opens a new UserPrompt object and keeps the Health Report open in the background.
    test_again.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                new UserPrompt();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    });

    frame.add(outer);
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setVisible(true);

    DetectVM vm_checker = new DetectVM();
    if (EnvironmentUtil.isMac()) {
        if (vm_checker.getIsVM()) {
            JOptionPane.showMessageDialog(new JFrame(),
                    "The tool has detected that it is running in a OSX Virtual Machine.\nThe opening of links is not supported on OSX VMs.\nPlease open the tool on a non-VM computer and run it again OR\nyou can also copy the JSON from the report to a non-VM OR view the text report.\nIf you are not running a VM, ignore this message.",
                    "VM Detected", JOptionPane.ERROR_MESSAGE);
        }
    }

}

From source file:es.emergya.ui.plugins.admin.aux1.RecursoDialog.java

public RecursoDialog(final Recurso rec, final AdminResources adminResources) {
    super();/* ww  w  .  j a  va 2s  .  c  om*/
    setAlwaysOnTop(true);
    setSize(600, 400);

    setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {
            super.windowClosing(e);
            if (cambios) {
                int res = JOptionPane.showConfirmDialog(RecursoDialog.this,
                        "Existen cambios sin guardar. Seguro que desea cerrar la ventana?",
                        "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION);
                if (res != JOptionPane.CANCEL_OPTION) {
                    e.getWindow().dispose();
                }
            } else {
                e.getWindow().dispose();
            }
        }
    });
    final Recurso r = (rec == null) ? null : RecursoConsultas.get(rec.getId());
    if (r != null) {
        setTitle(i18n.getString("Resources.summary.titleWindow") + " " + r.getIdentificador());
    } else {
        setTitle(i18n.getString("Resources.summary.titleWindow.new"));
    }
    setIconImage(getBasicWindow().getFrame().getIconImage());
    JPanel base = new JPanel();
    base.setBackground(Color.WHITE);
    base.setLayout(new BoxLayout(base, BoxLayout.Y_AXIS));

    // Icono del titulo
    JPanel title = new JPanel(new FlowLayout(FlowLayout.LEADING));
    title.setOpaque(false);
    JLabel labelTitulo = null;
    if (r != null) {
        labelTitulo = new JLabel(i18n.getString("Resources.summary"),
                LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT);

    } else {
        labelTitulo = new JLabel(i18n.getString("Resources.cabecera.nuevo"),
                LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT);

    }
    labelTitulo.setFont(LogicConstants.deriveBoldFont(12f));
    title.add(labelTitulo);
    base.add(title);

    // Nombre
    JPanel mid = new JPanel(new SpringLayout());
    mid.setOpaque(false);
    mid.add(new JLabel(i18n.getString("Resources.name"), JLabel.RIGHT));
    final JTextField name = new JTextField(25);
    if (r != null) {
        name.setText(r.getNombre());
    }

    name.getDocument().addDocumentListener(changeListener);
    name.setEditable(r == null);
    mid.add(name);

    // patrullas
    final JLabel labelSquads = new JLabel(i18n.getString("Resources.squad"), JLabel.RIGHT);
    mid.add(labelSquads);
    List<Patrulla> pl = PatrullaConsultas.getAll();
    pl.add(0, null);
    final JComboBox squads = new JComboBox(pl.toArray());
    squads.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXX");
    squads.addActionListener(changeSelectionListener);
    squads.setOpaque(false);
    labelSquads.setLabelFor(squads);
    if (r != null) {
        squads.setSelectedItem(r.getPatrullas());
    } else {
        squads.setSelectedItem(null);
    }
    squads.setEnabled((r != null && r.getHabilitado() != null) ? r.getHabilitado() : true);
    mid.add(squads);

    // // Identificador
    // mid.setOpaque(false);
    // mid.add(new JLabel(i18n.getString("Resources.identificador"),
    // JLabel.RIGHT));
    // final JTextField identificador = new JTextField("");
    // if (r != null) {
    // identificador.setText(r.getIdentificador());
    // }
    // identificador.getDocument().addDocumentListener(changeListener);
    // identificador.setEditable(r == null);
    // mid.add(identificador);
    // Espacio en blanco
    // mid.add(Box.createHorizontalGlue());
    // mid.add(Box.createHorizontalGlue());

    // Tipo
    final JLabel labelTipoRecursos = new JLabel(i18n.getString("Resources.type"), JLabel.RIGHT);
    mid.add(labelTipoRecursos);
    final JComboBox types = new JComboBox(RecursoConsultas.getTipos());
    labelTipoRecursos.setLabelFor(types);
    types.addActionListener(changeSelectionListener);
    if (r != null) {
        types.setSelectedItem(r.getTipo());
    } else {
        types.setSelectedItem(0);
    }
    // types.setEditable(true);
    types.setEnabled(true);
    mid.add(types);

    // Estado Eurocop
    mid.add(new JLabel(i18n.getString("Resources.status"), JLabel.RIGHT));
    final JTextField status = new JTextField();
    if (r != null && r.getEstadoEurocop() != null) {
        status.setText(r.getEstadoEurocop().getIdentificador());
    }
    status.setEditable(false);
    mid.add(status);

    // Subflota y patrulla
    mid.add(new JLabel(i18n.getString("Resources.subfleet"), JLabel.RIGHT));
    final JComboBox subfleets = new JComboBox(FlotaConsultas.getAllHabilitadas());
    subfleets.addActionListener(changeSelectionListener);
    if (r != null) {
        subfleets.setSelectedItem(r.getFlotas());
    } else {
        subfleets.setSelectedIndex(0);
    }
    subfleets.setEnabled(true);
    subfleets.setOpaque(false);
    mid.add(subfleets);

    // Referencia humana
    mid.add(new JLabel(i18n.getString("Resources.incidences"), JLabel.RIGHT));
    final JTextField rhumana = new JTextField();
    // if (r != null && r.getIncidencias() != null) {
    // rhumana.setText(r.getIncidencias().getReferenciaHumana());
    // }
    rhumana.setEditable(false);
    mid.add(rhumana);

    // dispositivo
    mid.add(new JLabel(i18n.getString("Resources.device"), JLabel.RIGHT));
    final PlainDocument plainDocument = new PlainDocument() {

        private static final long serialVersionUID = 4929271093724956016L;

        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            if (this.getLength() + str.length() <= LogicConstants.LONGITUD_ISSI) {
                super.insertString(offs, str, a);
            }
        }
    };
    final JTextField issi = new JTextField(plainDocument, "", LogicConstants.LONGITUD_ISSI);
    plainDocument.addDocumentListener(changeListener);
    issi.setEditable(true);
    mid.add(issi);
    mid.add(new JLabel(i18n.getString("Resources.enabled"), JLabel.RIGHT));
    final JCheckBox enabled = new JCheckBox("", true);
    enabled.addActionListener(changeSelectionListener);
    enabled.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (enabled.isSelected()) {
                squads.setSelectedIndex(0);
            }
            squads.setEnabled(enabled.isSelected());
        }
    });
    enabled.setEnabled(true);
    enabled.setOpaque(false);
    if (r != null) {
        enabled.setSelected(r.getHabilitado());
    } else {
        enabled.setSelected(true);
    }
    if (r != null && r.getDispositivo() != null) {
        issi.setText(
                StringUtils.leftPad(String.valueOf(r.getDispositivo()), LogicConstants.LONGITUD_ISSI, '0'));
    }

    mid.add(enabled);

    // Fecha ultimo gps
    mid.add(new JLabel(i18n.getString("Resources.lastPosition"), JLabel.RIGHT));
    JTextField lastGPS = new JTextField();
    final Date lastGPSDateForRecurso = HistoricoGPSConsultas.lastGPSDateForRecurso(r);
    if (lastGPSDateForRecurso != null) {
        lastGPS.setText(SimpleDateFormat.getDateTimeInstance().format(lastGPSDateForRecurso));
    }
    lastGPS.setEditable(false);
    mid.add(lastGPS);

    // Espacio en blanco
    mid.add(Box.createHorizontalGlue());
    mid.add(Box.createHorizontalGlue());

    // informacion adicional
    JPanel infoPanel = new JPanel(new SpringLayout());
    final JTextField info = new JTextField(25);
    info.getDocument().addDocumentListener(changeListener);
    infoPanel.add(new JLabel(i18n.getString("Resources.info")));
    infoPanel.add(info);
    infoPanel.setOpaque(false);
    info.setOpaque(false);
    SpringUtilities.makeCompactGrid(infoPanel, 1, 2, 6, 6, 6, 18);

    if (r != null) {
        info.setText(r.getInfoAdicional());
    } else {
        info.setText("");
    }
    info.setEditable(true);

    // Espacio en blanco
    mid.add(Box.createHorizontalGlue());
    mid.add(Box.createHorizontalGlue());

    SpringUtilities.makeCompactGrid(mid, 5, 4, 6, 6, 6, 18);
    base.add(mid);
    base.add(infoPanel);

    JPanel buttons = new JPanel();
    buttons.setOpaque(false);
    JButton accept = null;
    if (r == null) {
        accept = new JButton("Crear", LogicConstants.getIcon("button_crear"));
    } else {
        accept = new JButton("Guardar", LogicConstants.getIcon("button_save"));
    }
    accept.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                if (cambios || r == null || r.getId() == null) {
                    boolean shithappens = true;
                    if ((r == null || r.getId() == null)) { // Estamos
                        // creando
                        // uno nuevo
                        if (RecursoConsultas.alreadyExists(name.getText())) {
                            shithappens = false;
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.nombreUnico"));
                        } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils
                                .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) {
                            JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT,
                                    "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI));
                            shithappens = false;
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && LogicConstants.isNumeric(issi.getText())
                                && RecursoConsultas.alreadyExists(new Integer(issi.getText()))) {
                            shithappens = false;
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.dispositivoUnico"));
                        }
                    }
                    if (shithappens) {
                        if (name.getText().isEmpty()) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.nombreNulo"));
                        } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils
                                .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) {
                            JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT,
                                    "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI));
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && LogicConstants.isNumeric(issi.getText()) && r != null && r.getId() != null
                                && RecursoConsultas.alreadyExists(new Integer(issi.getText()), r.getId())) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.issiUnico"));
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && !LogicConstants.isNumeric(issi.getText())) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noNumerico"));
                            // } else if (identificador.getText().isEmpty())
                            // {
                            // JOptionPane
                            // .showMessageDialog(
                            // RecursoDialog.this,
                            // i18n.getString("admin.recursos.popup.error.identificadorNulo"));
                        } else if (subfleets.getSelectedIndex() == -1) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noSubflota"));
                        } else if (types.getSelectedItem() == null
                                || types.getSelectedItem().toString().trim().isEmpty()) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noTipo"));
                        } else {
                            int i = JOptionPane.showConfirmDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.dialogo.guardar.titulo"),
                                    i18n.getString("admin.recursos.popup.dialogo.guardar.guardar"),
                                    JOptionPane.YES_NO_CANCEL_OPTION);

                            if (i == JOptionPane.YES_OPTION) {

                                Recurso recurso = r;

                                if (r == null) {
                                    recurso = new Recurso();
                                }

                                recurso.setInfoAdicional(info.getText());
                                if (issi.getText() != null && issi.getText().length() > 0) {
                                    recurso.setDispositivo(new Integer(issi.getText()));
                                } else {
                                    recurso.setDispositivo(null);
                                }
                                recurso.setFlotas(FlotaConsultas.find(subfleets.getSelectedItem().toString()));
                                if (squads.getSelectedItem() != null && enabled.isSelected()) {
                                    recurso.setPatrullas(
                                            PatrullaConsultas.find(squads.getSelectedItem().toString()));
                                } else {
                                    recurso.setPatrullas(null);
                                }
                                recurso.setNombre(name.getText());
                                recurso.setHabilitado(enabled.isSelected());
                                // recurso.setIdentificador(identificador
                                // .getText());
                                recurso.setTipo(types.getSelectedItem().toString());
                                dispose();

                                RecursoAdmin.saveOrUpdate(recurso);
                                adminResources.refresh(null);

                                PluginEventHandler.fireChange(adminResources);
                            } else if (i == JOptionPane.NO_OPTION) {
                                dispose();
                            }
                        }
                    }
                } else {
                    log.debug("No hay cambios");
                    dispose();
                }

            } catch (Throwable t) {
                log.error("Error guardando un recurso", t);
            }
        }
    });
    buttons.add(accept);

    JButton cancelar = new JButton("Cancelar", LogicConstants.getIcon("button_cancel"));

    cancelar.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (cambios) {
                if (JOptionPane.showConfirmDialog(RecursoDialog.this,
                        "Existen cambios sin guardar. Seguro que desea cerrar la ventana?",
                        "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION) != JOptionPane.CANCEL_OPTION) {
                    dispose();
                }
            } else {
                dispose();
            }
        }
    });

    buttons.add(cancelar);

    base.add(buttons);

    getContentPane().add(base);
    setLocationRelativeTo(null);
    cambios = false;
    if (r == null) {
        cambios = true;
    }

    pack();

    int x;
    int y;

    Container myParent = getBasicWindow().getPluginContainer().getDetachedTab(0);
    Point topLeft = myParent.getLocationOnScreen();
    Dimension parentSize = myParent.getSize();

    Dimension mySize = getSize();

    if (parentSize.width > mySize.width) {
        x = ((parentSize.width - mySize.width) / 2) + topLeft.x;
    } else {
        x = topLeft.x;
    }

    if (parentSize.height > mySize.height) {
        y = ((parentSize.height - mySize.height) / 2) + topLeft.y;
    } else {
        y = topLeft.y;
    }

    setLocation(x, y);
    cambios = false;
}

From source file:net.sf.taverna.t2.activities.wsdlsir.views.WSDLActivityConfigurationView.java

private void initComponents() {

    this.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);

    int gridy = 0;

    // title panel
    JPanel titlePanel = new JPanel(new BorderLayout());
    titlePanel.setBackground(Color.WHITE);
    JLabel titleLabel = new JLabel("Security configuration");
    titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 13.5f));
    titleLabel.setBorder(new EmptyBorder(10, 10, 0, 10));
    DialogTextArea titleMessage = new DialogTextArea("Select a security profile for the service");
    titleMessage.setMargin(new Insets(5, 20, 10, 10));
    titleMessage.setFont(titleMessage.getFont().deriveFont(11f));
    titleMessage.setEditable(false);//from  ww  w  .j a  va2 s.  c  o  m
    titleMessage.setFocusable(false);
    titlePanel.setBorder(new EmptyBorder(10, 10, 0, 10));
    titlePanel.add(titleLabel, BorderLayout.NORTH);
    titlePanel.add(titleMessage, BorderLayout.CENTER);
    addDivider(titlePanel, SwingConstants.BOTTOM, true);

    // Main panel
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new GridBagLayout());
    mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

    //Create the radio buttons
    noSecurityRadioButton = new JRadioButton("None");
    noSecurityRadioButton.addItemListener(this);

    wsSecurityAuthNRadioButton = new JRadioButton("WS-Security username and password authentication");
    wsSecurityAuthNRadioButton.addItemListener(this);

    httpSecurityAuthNRadioButton = new JRadioButton("HTTP username and password authentication");
    httpSecurityAuthNRadioButton.addItemListener(this);

    SAMLSecurityAuthNRadioButton = new JRadioButton("SAML WEB SSO profile authentication");
    SAMLSecurityAuthNRadioButton.addItemListener(this);

    //Group the radio buttons
    buttonGroup = new ButtonGroup();
    buttonGroup.add(noSecurityRadioButton);
    buttonGroup.add(wsSecurityAuthNRadioButton);
    buttonGroup.add(httpSecurityAuthNRadioButton);
    buttonGroup.add(SAMLSecurityAuthNRadioButton);

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 1.0;
    gbc.weighty = 0.0;

    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(5, 10, 0, 0);
    mainPanel.add(noSecurityRadioButton, gbc);

    noSecurityLabel = new JLabel("Service requires no security");
    noSecurityLabel.setFont(noSecurityLabel.getFont().deriveFont(11f));
    //      addDivider(noSecurityLabel, SwingConstants.BOTTOM, false);
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(0, 40, 10, 10);
    mainPanel.add(noSecurityLabel, gbc);

    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(5, 10, 0, 0);
    mainPanel.add(httpSecurityAuthNRadioButton, gbc);

    ActionListener usernamePasswordListener = new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            // Get Credential Manager UI to get the username and password for the service
            CredentialManagerUI credManagerUI = CredentialManagerUI.getInstance();
            if (credManagerUI != null)
                credManagerUI.newPasswordForService(oldBean.getWsdl());
        }
    };

    httpSecurityAuthNLabel = new JLabel(
            "Service requires HTTP username and password in order to authenticate the user");
    httpSecurityAuthNLabel.setFont(httpSecurityAuthNLabel.getFont().deriveFont(11f));
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(0, 40, 10, 10);
    mainPanel.add(httpSecurityAuthNLabel, gbc);

    // Set username and password button;
    setHttpUsernamePasswordButton = new JButton("Set username and password");
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.EAST;
    gbc.insets = new Insets(0, 40, 10, 10);
    gbc.weightx = 1.0;
    gbc.weighty = 1.0; // add any vertical space to this component
    mainPanel.add(setHttpUsernamePasswordButton, gbc);
    setHttpUsernamePasswordButton.addActionListener(usernamePasswordListener);

    /////SAML

    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(5, 10, 0, 0);
    mainPanel.add(SAMLSecurityAuthNRadioButton, gbc);

    ActionListener getCookieListener = new ActionListener() {

        /**
         * This listener will use the CallPreparator to obtain the cookies (included shibsession_XXX cookie) and 
         * save it in the Credential Manager (as the password for user "nomatter")
         */
        public void actionPerformed(ActionEvent e) {
            try {
                WSDLParser parser = new WSDLParser(newBean.getWsdl());
                List<String> endpoints = parser.getOperationEndpointLocations(newBean.getOperation());
                for (String endpoint : endpoints) //Actually i am only expecting one endpoint
                {
                    if (debug)
                        System.out
                                .println("Obtaining a SAML cookies to save in credential manager:" + endpoint);

                    Cookie[] cookies = CallPreparator.createCookieForCallToEndpoint(endpoint);

                    // Uncomment for just the shibsession cookie
                    //                  Cookie[] cookiessession = new Cookie[1];
                    //                  for (Cookie cook : cookies)
                    //                     if (cook.getName().contains("shibsession"))
                    //                        cookiessession[0]=cook;
                    //                  cookies=cookiessession;

                    CredentialManager credman = CredentialManager.getInstance();
                    credman.saveUsernameAndPasswordForService(
                            new UsernamePassword("nomatter", serializetoString(cookies)), new URI(endpoint));
                }
            } catch (WSDLException ex) {
                System.err.println(
                        "Problem getting or saving SAML cookie: " + newBean.getWsdl() + ". " + ex.getMessage());
                ex.printStackTrace();
            } catch (ParserConfigurationException ex) {
                System.err.println(
                        "Problem getting or saving SAML cookie: " + newBean.getWsdl() + ". " + ex.getMessage());
                ex.printStackTrace();
            } catch (Exception ex) {
                System.err.println(
                        "Problem getting or saving SAML cookie: " + newBean.getWsdl() + ". " + ex.getMessage());
                ex.printStackTrace();
            }
        }
    };

    SAMLSecurityAuthNLabel = new JLabel("<html>"
            + "Service requires SAML Web SSO profile to be perfomed in order to authenticate the user. "
            + "A cookie will be saved in your Credential Manger. "
            + "In the case that it stops working, please delete the entry in your Credential Manager or re-authenticate"
            + "</html>");
    SAMLSecurityAuthNLabel.setFont(SAMLSecurityAuthNLabel.getFont().deriveFont(11f));
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(3, 40, 10, 10);
    mainPanel.add(SAMLSecurityAuthNLabel, gbc);

    // Set username and password button;
    setSAMLGETCookieButton = new JButton("Authenticate and save Authentication data in Credential Manger");
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.EAST;
    gbc.insets = new Insets(0, 40, 10, 10);
    gbc.weightx = 1.0;
    gbc.weighty = 1.0; // add any vertical space to this component
    mainPanel.add(setSAMLGETCookieButton, gbc);
    setSAMLGETCookieButton.addActionListener(getCookieListener);

    //END SAML

    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(5, 10, 0, 0);
    mainPanel.add(wsSecurityAuthNRadioButton, gbc);

    wsSecurityAuthNLabel = new JLabel(
            "Service requires WS-Security username and password in order to authenticate the user");
    wsSecurityAuthNLabel.setFont(wsSecurityAuthNLabel.getFont().deriveFont(11f));
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(0, 40, 0, 0);
    mainPanel.add(wsSecurityAuthNLabel, gbc);

    // Password type list
    passwordTypeComboBox = new JComboBox(passwordTypes);
    passwordTypeComboBox.setRenderer(new ComboBoxTooltipRenderer());
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(10, 40, 0, 0);
    mainPanel.add(passwordTypeComboBox, gbc);

    // 'Add timestamp' checkbox
    addTimestampCheckBox = new JCheckBox("Add a timestamp to SOAP message");
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(5, 40, 10, 10);
    mainPanel.add(addTimestampCheckBox, gbc);

    // Set username and password button;
    setWsdlUsernamePasswordButton = new JButton("Set username and password");
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.EAST;
    gbc.insets = new Insets(0, 40, 10, 10);
    gbc.weightx = 1.0;
    gbc.weighty = 1.0; // add any vertical space to this component
    mainPanel.add(setWsdlUsernamePasswordButton, gbc);
    setWsdlUsernamePasswordButton.addActionListener(usernamePasswordListener);

    addDivider(mainPanel, SwingConstants.BOTTOM, true);

    // OK/Cancel button panel
    JPanel okCancelPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    JButton okButton = new JButton("OK");
    okButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            okPressed();
        }
    });
    JButton cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            cancelPressed();
        }
    });
    okCancelPanel.add(cancelButton);
    okCancelPanel.add(okButton);

    // Enable/disable controls based on what is the current security profiles
    String securityProfile = oldBean.getSecurityProfile();
    if (securityProfile == null) {
        noSecurityRadioButton.setSelected(true);
    } else {
        if (securityProfile.equals(SecurityProfiles.WSSECURITY_USERNAMETOKEN_PLAINTEXTPASSWORD)
                || securityProfile.equals(SecurityProfiles.WSSECURITY_USERNAMETOKEN_DIGESTPASSWORD)
                || securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_PLAINTEXTPASSWORD)
                || securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_DIGESTPASSWORD)) {
            wsSecurityAuthNRadioButton.setSelected(true);
        }
        if (securityProfile.equals(SecurityProfiles.HTTP_BASIC_AUTHN)
                || securityProfile.equals(SecurityProfiles.HTTP_DIGEST_AUTHN)) {
            httpSecurityAuthNRadioButton.setSelected(true);
        }
        if (securityProfile.equals(SecurityProfiles.SAMLWEBSSOAUTH)) {
            SAMLSecurityAuthNRadioButton.setSelected(true);
        }
        if (securityProfile.equals(SecurityProfiles.WSSECURITY_USERNAMETOKEN_PLAINTEXTPASSWORD)
                || securityProfile
                        .equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_PLAINTEXTPASSWORD)) {
            passwordTypeComboBox.setSelectedItem(PLAINTEXT_PASSWORD);
        } else if (securityProfile.equals(SecurityProfiles.WSSECURITY_USERNAMETOKEN_DIGESTPASSWORD)
                || securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_DIGESTPASSWORD)) {
            passwordTypeComboBox.setSelectedItem(DIGEST_PASSWORD);
        }
        if (securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_DIGESTPASSWORD)
                || securityProfile
                        .equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_PLAINTEXTPASSWORD)) {
            addTimestampCheckBox.setSelected(true);
        } else {
            addTimestampCheckBox.setSelected(false);
        }
    }

    // Put everything together
    JPanel layoutPanel = new JPanel(new BorderLayout());
    layoutPanel.add(titlePanel, BorderLayout.NORTH);
    layoutPanel.add(mainPanel, BorderLayout.CENTER);
    layoutPanel.add(okCancelPanel, BorderLayout.SOUTH);
    layoutPanel.setPreferredSize(new Dimension(550, 490));

    this.getContentPane().add(layoutPanel);
    this.pack();
}

From source file:net.sf.dsig.DSApplet.java

private void initSwing() {
    try {//w  w  w  .ja  v a  2s  .  c o m
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        logger.warn("UIManager.setLookAndFeel() failed", e);
    }

    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
    panel.setBackground(Color.decode(backgroundColor));
    add(panel);

    boolean lockPrinted = false;
    if (formId != null) {
        Icon lockIcon = new ImageIcon(getClass().getResource("/icons/lock.png"));
        lockPrinted = true;

        JButton button = new JButton("Sign", lockIcon);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                available.acquireUninterruptibly();
                try {
                    signInternal(formId, null);
                } catch (Exception ex) {
                    logger.error("Internal sign failed", e);
                } finally {
                    available.release();
                }
            }
        });
        panel.add(button);
    }

    Icon infoIcon = new ImageIcon(getClass().getResource(lockPrinted ? "/icons/info.png" : "/icons/lock.png"));
    JLabel infoLabel = new JLabel(infoIcon);
    infoLabel.addMouseListener(new MouseListener() {
        public void mouseClicked(MouseEvent e) {
            JOptionPane.showMessageDialog(null, printInfoMessage());
        }

        public void mouseEntered(MouseEvent e) {
            /* NOOP */ }

        public void mouseExited(MouseEvent e) {
            /* NOOP */ }

        public void mousePressed(MouseEvent e) {
            /* NOOP */ }

        public void mouseReleased(MouseEvent e) {
            /* NOOP */ }
    });
    panel.add(infoLabel);
}

From source file:lol.search.RankedStatsPage.java

private JScrollPane championSelectPanel() {
    JPanel mainPanel = new JPanel(new FlowLayout());
    //mainPanel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
    mainPanel.setBackground(backgroundColor);
    for (int i = 0; i < this.objChampRankedList.size(); i++) {
        int position = counter;
        ImageIcon champImageIcon = this.OBJ_RANKED_STATS_BY_ID.getChampionIconOf(this.champKeyList.get(i));
        JButton champButton = new JButton();
        champButton.setIcon(champImageIcon);
        if (i == 0) {
            champButton.setIcon(this.profileIcon);
            champButton.setToolTipText("Overall Stats");
        }//from w  w  w  .j  av  a 2s .c  o m
        champButton.setPreferredSize(new Dimension(55, 55));
        champButton.setBackground(Color.BLACK);
        champButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) { //button pressed
                background.setIcon(OBJ_GAME_STATIC_DATA.getBackgroundImageIcon(champKeyList.get(position)));
                loadArtLabel.setIcon(OBJ_GAME_STATIC_DATA.initLoadingArt(champKeyList.get(position)));
                nameHeader.setText(OBJ_ALL_CHAMPS_BY_ID.getChampNameFromId(champIdList.get(position)));

                titleHeader.setText(" " + OBJ_ALL_CHAMPS_BY_ID.getChampTitleFromId(champIdList.get(position)));
                String sessionsWon = "";
                String sessionsLost = "";
                String winPercentString = "";
                try {
                    int won = objChampRankedList.get(position).getJSONObject("stats")
                            .getInt("totalSessionsWon");
                    sessionsWon = Integer.toString(won);
                    int lost = objChampRankedList.get(position).getJSONObject("stats")
                            .getInt("totalSessionsLost");
                    sessionsLost = Integer.toString(lost);
                    winPercentString = getWinPercentage(won, lost);
                    totalGamesInt = won + lost;
                    avgKillsLabelValue.setText(new DecimalFormat("##.##")
                            .format((double) objChampRankedList.get(position).getJSONObject("stats")
                                    .getInt("totalChampionKills") / (double) totalGamesInt));
                    avgAssistsLabelValue
                            .setText(new DecimalFormat("##.##").format((double) objChampRankedList.get(position)
                                    .getJSONObject("stats").getInt("totalAssists") / (double) totalGamesInt));
                    avgDeathsLabelValue.setText(new DecimalFormat("##.##")
                            .format((double) objChampRankedList.get(position).getJSONObject("stats")
                                    .getInt("totalDeathsPerSession") / (double) totalGamesInt));
                    avgMinionKillsLabelValue.setText(new DecimalFormat("##.##")
                            .format((double) objChampRankedList.get(position).getJSONObject("stats")
                                    .getInt("totalMinionKills") / (double) totalGamesInt));
                    avgDoubleKillsLabelValue.setText(new DecimalFormat("##.##")
                            .format((double) objChampRankedList.get(position).getJSONObject("stats")
                                    .getInt("totalDoubleKills") / (double) totalGamesInt));
                    avgTripleKillsLabelValue.setText(new DecimalFormat("##.##")
                            .format((double) objChampRankedList.get(position).getJSONObject("stats")
                                    .getInt("totalTripleKills") / (double) totalGamesInt));
                    avgQuadKillsLabelValue.setText(new DecimalFormat("##.##")
                            .format((double) objChampRankedList.get(position).getJSONObject("stats")
                                    .getInt("totalQuadraKills") / (double) totalGamesInt));
                    avgPentaKillsLabelValue.setText(new DecimalFormat("##.##")
                            .format((double) objChampRankedList.get(position).getJSONObject("stats")
                                    .getInt("totalPentaKills") / (double) totalGamesInt));
                    totalKillsLabelValue.setText(new DecimalFormat("#######").format((double) objChampRankedList
                            .get(position).getJSONObject("stats").getInt("totalChampionKills")));
                    totalDeathsLabelValue
                            .setText(new DecimalFormat("#######").format((double) objChampRankedList
                                    .get(position).getJSONObject("stats").getInt("totalDeathsPerSession")));
                    totalAssistsLabelValue
                            .setText(new DecimalFormat("#######").format((double) objChampRankedList
                                    .get(position).getJSONObject("stats").getInt("totalAssists")));
                    totalMinionsLabelValue
                            .setText(new DecimalFormat("#######").format((double) objChampRankedList
                                    .get(position).getJSONObject("stats").getInt("totalMinionKills")));
                    totalDoubleKillsLabelValue
                            .setText(new DecimalFormat("#######").format((double) objChampRankedList
                                    .get(position).getJSONObject("stats").getInt("totalDoubleKills")));
                    totalTripleKillsLabelValue
                            .setText(new DecimalFormat("#######").format((double) objChampRankedList
                                    .get(position).getJSONObject("stats").getInt("totalTripleKills")));
                    totalQuadKillsLabelValue
                            .setText(new DecimalFormat("#######").format((double) objChampRankedList
                                    .get(position).getJSONObject("stats").getInt("totalQuadraKills")));
                    totalPentaKillsLabelValue
                            .setText(new DecimalFormat("#######").format((double) objChampRankedList
                                    .get(position).getJSONObject("stats").getInt("totalPentaKills")));
                } catch (JSONException ex) {
                    Logger.getLogger(RankedStatsPage.class.getName()).log(Level.SEVERE, null, ex);
                }
                totalWins.setText(sessionsWon);
                totalLosses.setText(sessionsLost);
                winPercent.setText(winPercentString + "%");
                totalGamesPlayed.setText(String.valueOf(totalGamesInt));
                masterFrame.revalidate();
                masterFrame.repaint();
            }
        });
        champButton.setToolTipText(OBJ_ALL_CHAMPS_BY_ID.getChampNameFromId(champIdList.get(position)));
        champButtons.add(champButton);
        //champButton.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        counter++;
    }
    for (int i = 0; i < champButtons.size(); i++) {
        mainPanel.add(champButtons.get(i));
        mainPanel.revalidate();
    }
    JScrollPane scrollPane = new JScrollPane(mainPanel);
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
    scrollPane.setPreferredSize(new Dimension(1200, 85));
    scrollPane.setBackground(new Color(0, 0, 0, 100));
    scrollPane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    scrollPane.getHorizontalScrollBar().setUI(new BasicScrollBarUI() {
        @Override
        protected void configureScrollBarColors() {
            this.thumbColor = new Color(124, 124, 124, 255);
            this.trackColor = Color.BLACK;
        }
    });

    return scrollPane;
}