Example usage for java.awt FlowLayout LEFT

List of usage examples for java.awt FlowLayout LEFT

Introduction

In this page you can find the example usage for java.awt FlowLayout LEFT.

Prototype

int LEFT

To view the source code for java.awt FlowLayout LEFT.

Click Source Link

Document

This value indicates that each row of components should be left-justified.

Usage

From source file:logdruid.ui.RecordingList.java

/**
 * Create the panel.//from www.  ja  v  a 2  s .  c o m
 */
public RecordingList(final Repository rep) {

    if (Preferences.getPreference("timings").equals("true")) {
        header = (String[]) new String[] { "name", "regexp", "type", "active", "success time", "failed time",
                "match attempt", "success match" };
    } else {
        header = (String[]) new String[] { "name", "regexp", "type", "active" };
    }

    records = rep.getRecordings();
    // Collections.sort(records);
    Iterator it = records.iterator();
    while (it.hasNext()) {
        Recording record = (Recording) it.next();
        stats = DataVault.getRecordingStats(record.getName());
        if (stats != null) {
            data.add(new Object[] { record.getName(), record.getRegexp(), record.getType(),
                    record.getIsActive(), stats[0], stats[1], stats[2], stats[3] });
        } else {
            data.add(new Object[] { record.getName(), record.getRegexp(), record.getType(),
                    record.getIsActive(), 0, 0, 0, 0 });
        }
    }

    repository = rep;
    model = new MyTableModel2(data, header);

    JPanel panel_1 = new JPanel();
    GridBagConstraints gbc_panel_1 = new GridBagConstraints();
    gbc_panel_1.fill = GridBagConstraints.BOTH;
    gbc_panel_1.insets = new Insets(5, 0, 5, 5);
    gbc_panel_1.gridx = 1;
    gbc_panel_1.gridy = 0;
    panel_1.setLayout(new BorderLayout(0, 0));

    table = new JTable(model);
    JScrollPane scrollPane = new JScrollPane(table);
    int column;
    panel_1.add(scrollPane);

    table.setPreferredScrollableViewportSize(new Dimension(0, 150));
    table.setFillsViewportHeight(true);

    // Set up column sizes.
    initColumnSizes(table);
    table.setAutoCreateRowSorter(true);
    //   RowSorter sorter = table.getRowSorter();
    //      sorter.setSortKeys(Arrays.asList(new RowSorter.SortKey(0, SortOrder.ASCENDING)));
    if (model.getRowCount() > 0) {
        table.getRowSorter().toggleSortOrder(0);
        table.getRowSorter().toggleSortOrder(2);
    }
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        public void valueChanged(ListSelectionEvent e) {
            int selectedRow = ((table.getSelectedRow() != -1)
                    ? table.convertRowIndexToModel(table.getSelectedRow())
                    : -1);
            ;
            logger.info("ListSelectionListener - selectedRow: " + selectedRow);
            if (selectedRow >= 0) {
                if (jPanelDetail != null) {
                    logger.info("ListSelectionListener - valueChanged");
                    jPanelDetail.removeAll();
                    recEditor = getEditor(repository.getRecording(selectedRow));
                    if (recEditor != null) {
                        jPanelDetail.add(recEditor, BorderLayout.CENTER);
                    }
                    jPanelDetail.revalidate();
                }
            }
        }
    });
    JPanel panel = new JPanel();
    FlowLayout flowLayout = (FlowLayout) panel.getLayout();
    flowLayout.setAlignment(FlowLayout.LEFT);
    flowLayout.setVgap(2);
    flowLayout.setHgap(2);
    panel_1.add(panel, BorderLayout.SOUTH);

    JButton btnNewMeta = new JButton("New Meta");
    panel.add(btnNewMeta);
    btnNewMeta.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            int rowCount = table.getRowCount();
            jPanelDetail.removeAll();
            Recording re = new MetadataRecording("name", "regex", "example line", "", true, null);
            recEditor = new MetadataRecordingEditor(thiis, repository, "the line", "regex",
                    (MetadataRecording) re);
            jPanelDetail.add(recEditor, BorderLayout.CENTER);
            repository.addRecording(re);
            model.addRow(
                    new Object[] { re.getName(), re.getRegexp(), re.getType(), re.getIsActive(), 0, 0, 0, 0 });
            model.fireTableRowsInserted(rowCount, rowCount);
            table.setRowSelectionInterval(rowCount, rowCount);
            logger.info("New record - row count : " + rowCount);
        }
    });

    JButton btnDuplicate = new JButton("Duplicate");
    btnDuplicate.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int rowCount = table.getRowCount();
            int selectRow = ((table.getSelectedRow() != -1) ? table.getSelectedRow() : -1);
            int selectedRow = ((table.getSelectedRow() != -1)
                    ? table.convertRowIndexToModel(table.getSelectedRow())
                    : -1);
            repository.addRecording(
                    repository.getRecording(table.convertRowIndexToModel(table.getSelectedRow())).duplicate());
            model.fireTableRowsInserted(rowCount, rowCount);
            table.setRowSelectionInterval(selectRow, selectRow);
        }
    });

    JButton btnNewStat = new JButton("New Stat");
    btnNewStat.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int rowCount = table.getRowCount();
            jPanelDetail.removeAll();
            Recording re = new StatRecording("name", "regex", "example line", "", true, null);
            recEditor = new StatRecordingEditor(thiis, repository, "the line", "regex", (StatRecording) re);
            jPanelDetail.add(recEditor, BorderLayout.CENTER);
            repository.addRecording(re);
            model.addRow(
                    new Object[] { re.getName(), re.getRegexp(), re.getType(), re.getIsActive(), 0, 0, 0, 0 });
            model.fireTableRowsInserted(rowCount, rowCount);
            table.setRowSelectionInterval(rowCount, rowCount);
            logger.info("New record - row count : " + rowCount);
        }
    });
    panel.add(btnNewStat);

    JButton btnNewEvent = new JButton("New Event");
    btnNewEvent.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int rowCount = table.getRowCount();
            logger.info("table.getRowCount()" + table.getRowCount());
            jPanelDetail.removeAll();
            Recording re = new EventRecording("name", "regex", "example line", "", true, null);
            recEditor = new EventRecordingEditor(thiis, repository, "the line", "regex", (EventRecording) re);
            jPanelDetail.add(recEditor, BorderLayout.CENTER);
            repository.addRecording(re);
            model.addRow(
                    new Object[] { re.getName(), re.getRegexp(), re.getType(), re.getIsActive(), 0, 0, 0, 0 });
            model.fireTableRowsInserted(rowCount, rowCount);
            table.setRowSelectionInterval(rowCount, rowCount);
            logger.info("New record - row count : " + rowCount);
        }
    });
    panel.add(btnNewEvent);
    panel.add(btnDuplicate);

    JButton btnDelete = new JButton("Delete");
    btnDelete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int rowCount = table.getRowCount();
            int selectedRow = ((table.getSelectedRow() != -1)
                    ? table.convertRowIndexToModel(table.getSelectedRow())
                    : -1);
            ;
            int realSelectedRow = table.getSelectedRow();
            logger.info("selectedRow : " + selectedRow + ", row count: " + table.getRowCount());
            if (rowCount != 0) {
                repository.deleteRecording(selectedRow);
                model.fireTableRowsDeleted(selectedRow, selectedRow);
                //         table.remove(selectedRow);
                if (realSelectedRow != -1) {
                    if (realSelectedRow != 0)
                        table.setRowSelectionInterval(realSelectedRow - 1, realSelectedRow - 1);
                    else if (realSelectedRow > 0)
                        table.setRowSelectionInterval(realSelectedRow, realSelectedRow);
                    else if (rowCount > 1)
                        table.setRowSelectionInterval(0, 0);
                }
                /*            if (table.getRowCount() > 0) {
                               if (selectedRow == table.getRowCount()) {
                                  table.setRowSelectionInterval(selectedRow - 1, selectedRow - 1);
                               } else
                                  table.setRowSelectionInterval(selectedRow, selectedRow);
                            }*/
            }
        }
    });
    panel.add(btnDelete);
    setLayout(new BorderLayout(0, 0));

    JSplitPane splitPane = new JSplitPane();
    splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
    add(splitPane, BorderLayout.CENTER);

    jPanelDetail = new JPanel();
    GridBagConstraints gbc_jPanelDetail = new GridBagConstraints();
    gbc_jPanelDetail.insets = new Insets(0, 0, 0, 5);
    gbc_jPanelDetail.fill = GridBagConstraints.BOTH;
    gbc_jPanelDetail.gridx = 1;
    gbc_jPanelDetail.gridy = 4;
    splitPane.setBottomComponent(jPanelDetail);
    splitPane.setTopComponent(panel_1);
    jPanelDetail.setLayout(new BorderLayout(0, 0));
    if (repository.getRecordingCount() > 0) {
        //recEditor = getEditor(repository.getRecording(0));
        //jPanelDetail.add(recEditor, BorderLayout.CENTER);
        table.setRowSelectionInterval(0, 0);
    }
    jPanelDetail.revalidate();

}

From source file:edu.mit.fss.examples.visual.gui.WorldWindVisualization.java

/**
 * Instantiates a new world wind visualization.
 *
 * @throws OrekitException the orekit exception
 *///  w  ww .j  a va 2 s.  c o  m
public WorldWindVisualization() throws OrekitException {
    logger.trace("Creating Orekit reference frames.");
    eme = ReferenceFrame.EME2000.getOrekitFrame();
    itrf = ReferenceFrame.ITRF2008.getOrekitFrame();
    // world wind frame is a fixed rotation from Earth inertial frame
    wwj = new Frame(itrf, new Transform(date, new Rotation(RotationOrder.ZXZ, 0, -Math.PI / 2, -Math.PI / 2)),
            "World Wind");

    logger.trace("Creating World Window GL canvas and adding to panel.");
    wwd = new WorldWindowGLCanvas();
    wwd.setModel(new BasicModel());
    wwd.setPreferredSize(new Dimension(800, 600));
    setLayout(new BorderLayout());
    add(wwd, BorderLayout.CENTER);

    logger.trace("Creating and adding a renderable layer.");
    displayLayer = new RenderableLayer();
    wwd.getModel().getLayers().add(displayLayer);

    logger.trace("Creating and adding a marker layer.");
    markerLayer = new MarkerLayer();
    // allow markers above/below surface
    markerLayer.setOverrideMarkerElevation(false);
    wwd.getModel().getLayers().add(markerLayer);

    logger.trace("Creating and adding a sun renderable.");
    Vector3D position = sun.getPVCoordinates(date, wwj).getPosition();
    sunShape = new Ellipsoid(wwd.getModel().getGlobe().computePositionFromPoint(convert(position)), 696000000.,
            696000000., 696000000.);
    ShapeAttributes sunAttributes = new BasicShapeAttributes();
    sunAttributes.setInteriorMaterial(Material.YELLOW);
    sunAttributes.setInteriorOpacity(1.0);
    sunShape.setAttributes(sunAttributes);
    displayLayer.addRenderable(sunShape);

    logger.trace("Creating and adding a terminator.");
    LatLon antiSun = LatLon.fromRadians(-sunShape.getCenterPosition().getLatitude().radians,
            FastMath.PI + sunShape.getCenterPosition().getLongitude().radians);
    // set radius to a quarter Earth chord at the anti-sun position less
    // a small amount (100 m) to avoid graphics problems
    terminatorShape = new SurfaceCircle(antiSun,
            wwd.getModel().getGlobe().getRadiusAt(antiSun) * FastMath.PI / 2 - 100);
    ShapeAttributes nightAttributes = new BasicShapeAttributes();
    nightAttributes.setInteriorMaterial(Material.BLACK);
    nightAttributes.setInteriorOpacity(0.5);
    terminatorShape.setAttributes(nightAttributes);
    displayLayer.addRenderable(terminatorShape);

    logger.trace("Creating and adding a panel for buttons.");
    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    buttonPanel.add(new JCheckBox(new AbstractAction("Inertial Frame") {
        private static final long serialVersionUID = 2287109397693524964L;

        @Override
        public void actionPerformed(ActionEvent e) {
            setInertialFrame(((JCheckBox) e.getSource()).isSelected());
        }
    }));
    buttonPanel.add(new JButton(editOptionsAction));
    add(buttonPanel, BorderLayout.SOUTH);

    logger.trace(
            "Creating a timer to rotate the sun renderable, " + "terminator surface circle, and stars layer.");
    Timer rotationTimer = new Timer(15, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            wwd.redraw();
            try {
                BasicOrbitView wwdView;
                if (wwd.getView() instanceof BasicOrbitView) {
                    wwdView = (BasicOrbitView) wwd.getView();
                } else {
                    return;
                }

                // rotate camera to simulate inertial frame
                if (wwd.getView().isAnimating() || !inertialFrame.get()) {
                    // update eme datum
                    rotationDatum = wwj.getTransformTo(eme, date)
                            .transformPosition(convert(wwdView.getCenterPoint()));
                } else if (inertialFrame.get()) {
                    Position newCenter = wwd.getModel().getGlobe().computePositionFromPoint(
                            convert(eme.getTransformTo(wwj, date).transformPosition(rotationDatum)));
                    // move to eme datum
                    wwdView.setCenterPosition(newCenter);
                }

                // rotate stars layer
                for (Layer layer : wwd.getModel().getLayers()) {
                    if (layer instanceof StarsLayer) {
                        StarsLayer stars = (StarsLayer) layer;
                        // find the EME coordinates of (0,0)
                        Vector3D emeDatum = wwj.getTransformTo(eme, date).transformPosition(convert(
                                wwd.getModel().getGlobe().computePointFromLocation(LatLon.fromDegrees(0, 0))));
                        // find the WWJ coordinates the equivalent point in ITRF
                        Vector3D wwjDatum = itrf.getTransformTo(wwj, date).transformPosition(emeDatum);
                        // set the longitude offset to the opposite of 
                        // the difference in longitude (i.e. from 0)
                        stars.setLongitudeOffset(wwd.getModel().getGlobe()
                                .computePositionFromPoint(convert(wwjDatum)).getLongitude().multiply(-1));
                    }
                }
            } catch (OrekitException ex) {
                logger.error(ex);
            }
        }
    });
    // set initial 2-second delay for initialization
    rotationTimer.setInitialDelay(2000);
    rotationTimer.start();
}

From source file:com.hp.alm.ali.idea.ui.MultipleItemsDialog.java

public MultipleItemsDialog(Project project, String title, final MultipleItemsDialogModel<K, E> model) {
    super(project, title, true);

    this.model = model;

    mySelectionModel = new MySelectionModel();
    myListSelectionListener = new MyListSelectionListener();

    tooMany = new JLabel("Too many results, narrow your search");
    tooMany.setBorder(BorderFactory.createEtchedBorder());
    tooMany.setVisible(false);/*from  ww w. j  a v  a2s  .c  o  m*/
    selected = new JLabel("Showing currently selected items");
    selected.setVisible(false);
    toggleSelected = new JToggleButton();
    toggleSelected.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            model.setShowingSelected(toggleSelected.isSelected());
            if (!model.isShowingSelected() && !model.getSelectedFields().isEmpty()) {
                updateSelectionFromModel();
            } else if (model.isShowingSelected()) {
                header.getFilterEditor(1).setContent("");
            }
        }
    });
    updateSelected();

    table = new JBTable() {
        @Override
        public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
            int column = convertColumnIndexToModel(columnIndex);
            mySelectionModel.setFirstColumnEvent(column == 0);
            super.changeSelection(rowIndex, columnIndex, toggle, extend);
        }
    };
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(false);
    table.setAutoCreateColumnsFromModel(false);
    table.setModel(model);
    final MyTableRowSorter sorter = new MyTableRowSorter(model);
    table.setRowSorter(sorter);
    table.setDefaultRenderer(Boolean.class, new MyRenderer());
    table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
    table.setSelectionModel(mySelectionModel);

    sorter.setIgnoreAddRowSorterListener(true); // prevent auto-selection (functionality not accessible via proper API)
    header = new TableFilterHeader(table);
    sorter.setIgnoreAddRowSorterListener(false);

    sorter.setSortKeys(Arrays.asList(new RowSorter.SortKey(1, SortOrder.ASCENDING)));
    JPanel panel = new JPanel(new BorderLayout());
    JPanel toolbar = new JPanel(new BorderLayout());
    toolbar.setBorder(BorderFactory.createEtchedBorder());
    panel.add(toolbar, BorderLayout.NORTH);
    toolbar.add(toggleSelected, BorderLayout.EAST);

    if (model.isMultiple()) {
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        table.getColumnModel().addColumn(createColumn(0, model, 45, 45));
        header.getFilterEditor(0).setEditable(false);
        header.getFilterEditor(0).setUserInteractionEnabled(false);

        final LinkListener selectUnselect = new LinkListener() {
            public void linkSelected(LinkLabel aSource, Object aLinkData) {
                if (model.isShowingSelected()) {
                    if (!Boolean.TRUE.equals(aLinkData)) {
                        List<Integer> ixs = new ArrayList<Integer>();
                        for (int i = 0; i < sorter.getViewRowCount(); i++) {
                            ixs.add(sorter.convertRowIndexToModel(i));
                        }
                        // make sure indexes are not affected by removal by starting from the last
                        Collections.sort(ixs);
                        Collections.reverse(ixs);
                        for (int ix : ixs) {
                            model.setValueAt(aLinkData, ix, 0);
                        }
                    }
                } else {
                    if (Boolean.TRUE.equals(aLinkData)) {
                        mySelectionModel.doAddSelectionInterval(0, table.getRowCount() - 1);
                    } else {
                        mySelectionModel.removeSelectionInterval(0, table.getRowCount() - 1);
                    }
                }
            }
        };

        JPanel left = new JPanel(new FlowLayout(FlowLayout.LEFT));
        left.add(new LinkLabel("Select All", IconLoader.getIcon("/actions/selectall.png"), selectUnselect,
                true));
        left.add(new LinkLabel("Unselect All", IconLoader.getIcon("/actions/unselectall.png"), selectUnselect,
                false));
        toolbar.add(left, BorderLayout.WEST);
    } else {
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }
    table.getColumnModel().addColumn(createColumn(1, model, 450, null));
    table.getSelectionModel().addListSelectionListener(myListSelectionListener);

    model.addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            selected.setVisible(model.isShowingSelected());
            tooMany.setVisible(model.hasMore() && !model.isShowingSelected());
            updateSelected();
        }
    });

    JPanel contentPanel = new JPanel(new BorderLayout());
    contentPanel.add(selected, BorderLayout.NORTH);
    contentPanel.add(new JBScrollPane(table), BorderLayout.CENTER);
    contentPanel.add(tooMany, BorderLayout.SOUTH);
    panel.add(contentPanel, BorderLayout.CENTER);
    JPanel buttons = new JPanel();
    okButton = new JButton("OK");
    okButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            ok = true;
            close(true);
        }
    });
    buttons.add(okButton);
    JButton cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            close(false);
        }
    });
    buttons.add(cancel);
    panel.add(buttons, BorderLayout.SOUTH);
    getContentPane().add(panel, BorderLayout.CENTER);

    pack();
    setResizable(false);
    centerOnOwner();

    requestPropertyFilterFocus(header);

    load(true, null);
}

From source file:org.encog.workbench.tabs.visualize.epl.EPLTreeTab.java

public EPLTreeTab(final EncogProgram prg) {
    super(null);/*from w  ww.  j  a v  a  2 s  .com*/

    // Graph<V, E> where V is the type of the vertices
    // and E is the type of the edges
    // Graph<V, E> where V is the type of the vertices 
    // and E is the type of the edges
    this.graph = new DelegateForest<ProgramNode, Integer>(
            new DirectedOrderedSparseMultigraph<ProgramNode, Integer>());

    buildGraph(prg);
    // Add some vertices. From above we defined these to be type Integer.
    // The Layout<V, E> is parameterized by the vertex and edge types
    TreeLayout<ProgramNode, Integer> treeLayout = new TreeLayout<ProgramNode, Integer>(graph);

    Transformer<ProgramNode, Paint> vertexPaint = new Transformer<ProgramNode, Paint>() {
        public Paint transform(ProgramNode v) {
            return Color.white;
        }
    };

    //layout.setSize(new Dimension(5000,5000)); // sets the initial size of the space
    // The BasicVisualizationServer<V,E> is parameterized by the edge types
    //BasicVisualizationServer<DrawnNeuron, DrawnConnection> vv = new BasicVisualizationServer<DrawnNeuron, DrawnConnection>(
    //      layout);

    //Dimension d = new Dimension(600,600);

    vv = new VisualizationViewer<ProgramNode, Integer>(treeLayout, new Dimension(600, 600));

    //vv.setPreferredSize(d); //Sets the viewing area size

    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
    vv.getRenderContext().setVertexLabelTransformer(new Transformer<ProgramNode, String>() {

        @Override
        public String transform(ProgramNode node) {
            ProgramExtensionTemplate temp = node.getTemplate();
            if (temp == StandardExtensions.EXTENSION_VAR_SUPPORT) {
                int varIndex = (int) node.getData()[0].toIntValue();
                return prg.getVariables().getVariableName(varIndex);
            } else if (temp == StandardExtensions.EXTENSION_CONST_SUPPORT) {
                ExpressionValue expr = node.getData()[0];
                if (expr.isFloat()) {
                    return Format.formatDouble(expr.toFloatValue(), 2);
                } else {
                    return node.getData()[0].toStringValue();
                }
            } else if (node.getTemplate().getNodeType().isOperator()) {
                return node.getTemplate().getName();
            } else {
                return node.getTemplate().getName() + "()";
            }

        }
    });

    vv.setVertexToolTipTransformer(new ToStringLabeller<ProgramNode>());

    vv.setVertexToolTipTransformer(new Transformer<ProgramNode, String>() {
        public String transform(ProgramNode node) {
            ProgramExtensionTemplate temp = node.getTemplate();
            if (temp == StandardExtensions.EXTENSION_CONST_SUPPORT) {
                return node.getData()[0].toStringValue();
            } else {
                return null;
            }
        }
    });

    /*vv.setEdgeToolTipTransformer(new Transformer<DrawnConnection,String>() {
       public String transform(DrawnConnection edge) {
    return edge.getToolTip();
       }});*/

    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    this.setLayout(new BorderLayout());
    add(panel, BorderLayout.CENTER);
    final AbstractModalGraphMouse graphMouse = new DefaultModalGraphMouse<ProgramNode, Integer>();
    vv.setGraphMouse(graphMouse);
    vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint);
    vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line());
    vv.getRenderContext().setEdgeArrowPredicate(new Predicate() {
        @Override
        public boolean evaluate(Object arg0) {
            // TODO Auto-generated method stub
            return false;
        }
    });
    Predicate d;

    vv.addKeyListener(graphMouse.getModeKeyListener());

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JButton reset = new JButton("reset");
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).setToIdentity();
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).setToIdentity();
        }
    });

    JPanel controls = new JPanel();
    controls.setLayout(new FlowLayout(FlowLayout.LEFT));
    controls.add(plus);
    controls.add(minus);
    controls.add(reset);
    Border border = BorderFactory.createEtchedBorder();
    controls.setBorder(border);
    add(controls, BorderLayout.NORTH);

}

From source file:org.encog.workbench.tabs.visualize.structure.StructureTab.java

public StructureTab(MLMethod method) {
    super(null);//  ww w .java 2 s .  c  o  m

    // Graph<V, E> where V is the type of the vertices
    // and E is the type of the edges
    Graph<DrawnNeuron, DrawnConnection> g = null;

    if (method instanceof BasicNetwork) {
        BasicNetwork network = (BasicNetwork) method;
        g = buildGraph(network.getStructure().getFlat());
    } else if (method instanceof NEATNetwork) {
        NEATNetwork neat = (NEATNetwork) method;
        g = buildGraph(neat);
    }

    if (g == null) {
        throw new WorkBenchError("Can't visualize network: " + method.getClass().getSimpleName());
    }

    Transformer<DrawnNeuron, Point2D> staticTranformer = new Transformer<DrawnNeuron, Point2D>() {

        public Point2D transform(DrawnNeuron n) {
            int x = (int) (n.getX() * 600);
            int y = (int) (n.getY() * 300);

            Point2D result = new Point(x + 32, y);
            return result;
        }
    };

    Transformer<DrawnNeuron, Paint> vertexPaint = new Transformer<DrawnNeuron, Paint>() {
        public Paint transform(DrawnNeuron neuron) {
            switch (neuron.getType()) {
            case Bias:
                return Color.yellow;
            case Input:
                return Color.white;
            case Output:
                return Color.green;
            case Context:
                return Color.cyan;
            default:
                return Color.red;
            }
        }

    };

    Transformer<DrawnConnection, Paint> edgePaint = new Transformer<DrawnConnection, Paint>() {
        public Paint transform(DrawnConnection connection) {
            if (connection.isContext()) {
                return Color.lightGray;
            } else {
                return Color.black;
            }
        }
    };

    // The Layout<V, E> is parameterized by the vertex and edge types
    StaticLayout<DrawnNeuron, DrawnConnection> layout = new StaticLayout<DrawnNeuron, DrawnConnection>(g,
            staticTranformer);

    layout.setSize(new Dimension(5000, 5000)); // sets the initial size of the space
    // The BasicVisualizationServer<V,E> is parameterized by the edge types
    //BasicVisualizationServer<DrawnNeuron, DrawnConnection> vv = new BasicVisualizationServer<DrawnNeuron, DrawnConnection>(
    //      layout);

    //Dimension d = new Dimension(600,600);

    vv = new VisualizationViewer<DrawnNeuron, DrawnConnection>(layout);

    //vv.setPreferredSize(d); //Sets the viewing area size

    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
    vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint);
    vv.getRenderContext().setEdgeDrawPaintTransformer(edgePaint);
    vv.getRenderContext().setArrowDrawPaintTransformer(edgePaint);
    vv.getRenderContext().setArrowFillPaintTransformer(edgePaint);

    vv.setVertexToolTipTransformer(new ToStringLabeller());

    vv.setVertexToolTipTransformer(new Transformer<DrawnNeuron, String>() {
        public String transform(DrawnNeuron edge) {
            return edge.getToolTip();
        }
    });

    vv.setEdgeToolTipTransformer(new Transformer<DrawnConnection, String>() {
        public String transform(DrawnConnection edge) {
            return edge.getToolTip();
        }
    });

    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    this.setLayout(new BorderLayout());
    add(panel, BorderLayout.CENTER);
    final AbstractModalGraphMouse graphMouse = new DefaultModalGraphMouse();
    vv.setGraphMouse(graphMouse);

    vv.addKeyListener(graphMouse.getModeKeyListener());

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JButton reset = new JButton("reset");
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).setToIdentity();
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).setToIdentity();
        }
    });

    JPanel controls = new JPanel();
    controls.setLayout(new FlowLayout(FlowLayout.LEFT));
    controls.add(plus);
    controls.add(minus);
    controls.add(reset);
    Border border = BorderFactory.createEtchedBorder();
    controls.setBorder(border);
    add(controls, BorderLayout.NORTH);

}

From source file:net.sf.taverna.t2.workbench.views.results.workflow.RenderedResultComponent.java

/**
 * Creates the component./* w ww  .  j  a  va  2  s .c om*/
 */
public RenderedResultComponent(RendererRegistry rendererRegistry, List<SaveIndividualResultSPI> saveActions) {
    this.rendererRegistry = rendererRegistry;
    setLayout(new BorderLayout());

    // Results type combo box
    renderersComboBox = new JComboBox<>();
    renderersComboBox.setModel(new DefaultComboBoxModel<String>()); // initially empty

    renderersComboBox.setRenderer(new ColorCellRenderer());
    renderersComboBox.setEditable(false);
    renderersComboBox.setEnabled(false); // initially disabled

    // Set the new listener - listen for changes in the currently selected renderer
    renderersComboBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED && !ERROR_DOCUMENT.equals(e.getItem()))
                // render the result using the newly selected renderer
                renderResult();
        }
    });

    JPanel resultsTypePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    resultsTypePanel.add(new JLabel("Value type"));
    resultsTypePanel.add(renderersComboBox);

    // Refresh (re-render) button
    refreshButton = new JButton("Refresh", refreshIcon);
    refreshButton.setEnabled(false);
    refreshButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            renderResult();
            refreshButton.getParent().requestFocusInWindow();
            /*
             * so that the button does not stay focused after it is clicked
             * on and did its action
             */
        }
    });
    resultsTypePanel.add(refreshButton);

    // Check box for wrapping text if result is of type "text/plain"
    wrapTextCheckBox = new JCheckBox(WRAP_TEXT);
    wrapTextCheckBox.setVisible(false);
    wrapTextCheckBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            // Should have only one child component holding the rendered result
            // Check for empty just as well
            if (renderedResultPanel.getComponents().length == 0)
                return;
            Component component = renderedResultPanel.getComponent(0);
            if (component instanceof DialogTextArea) {
                nodeToWrapSelection.put(path, e.getStateChange() == SELECTED);
                renderResult();
            }
        }
    });

    resultsTypePanel.add(wrapTextCheckBox);

    // 'Save result' buttons panel
    saveButtonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    for (SaveIndividualResultSPI action : saveActions) {
        action.setResultReference(null);
        final JButton saveButton = new JButton(action.getAction());
        saveButton.setEnabled(false);
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveButton.getParent().requestFocusInWindow();
                /*
                 * so that the button does not stay focused after it is
                 * clicked on and did its action
                 */
            }
        });
        saveButtonsPanel.add(saveButton);
    }

    // Top panel contains result type combobox and various save buttons
    JPanel topPanel = new JPanel();
    topPanel.setLayout(new BoxLayout(topPanel, LINE_AXIS));
    topPanel.add(resultsTypePanel);
    topPanel.add(saveButtonsPanel);

    // Rendered results panel - initially empty
    renderedResultPanel = new JPanel(new BorderLayout());

    // Add all components
    add(topPanel, NORTH);
    add(new JScrollPane(renderedResultPanel), CENTER);
}

From source file:com.googlecode.libautocaptcha.tools.VodafoneItalyTool.java

private void initFrame() {
    frame = new JFrame();
    frame.setTitle("libautocaptcha vodafone.it tool");
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);

    JPanel setupPanel = new JPanel();
    FlowLayout flowLayout = (FlowLayout) setupPanel.getLayout();
    flowLayout.setAlignment(FlowLayout.LEFT);
    tabbedPane.addTab("Setup", null, setupPanel, null);

    JPanel setupFormPanel = new JPanel();
    setupPanel.add(setupFormPanel);//w  w  w .j a  v a  2s .co  m
    GridBagLayout gbl_setupFormPanel = new GridBagLayout();
    gbl_setupFormPanel.columnWidths = new int[] { 150, 250 };
    gbl_setupFormPanel.rowHeights = new int[] { 0, 0, 0 };
    gbl_setupFormPanel.columnWeights = new double[] { 0.0, 1.0 };
    gbl_setupFormPanel.rowWeights = new double[] { 0.0, 0.0, 0.0 };
    setupFormPanel.setLayout(gbl_setupFormPanel);

    JLabel usernameLabel = new JLabel("Username");
    GridBagConstraints gbc_usernameLabel = new GridBagConstraints();
    gbc_usernameLabel.anchor = GridBagConstraints.WEST;
    gbc_usernameLabel.fill = GridBagConstraints.VERTICAL;
    gbc_usernameLabel.insets = new Insets(0, 0, 5, 5);
    gbc_usernameLabel.gridx = 0;
    gbc_usernameLabel.gridy = 0;
    setupFormPanel.add(usernameLabel, gbc_usernameLabel);
    usernameField = new JTextField();
    GridBagConstraints gbc_usernameField = new GridBagConstraints();
    gbc_usernameField.fill = GridBagConstraints.BOTH;
    gbc_usernameField.insets = new Insets(0, 0, 5, 0);
    gbc_usernameField.gridx = 1;
    gbc_usernameField.gridy = 0;
    setupFormPanel.add(usernameField, gbc_usernameField);
    usernameField.setColumns(10);

    JLabel passwordLabel = new JLabel("Password");
    GridBagConstraints gbc_passwordLabel = new GridBagConstraints();
    gbc_passwordLabel.anchor = GridBagConstraints.WEST;
    gbc_passwordLabel.fill = GridBagConstraints.VERTICAL;
    gbc_passwordLabel.insets = new Insets(0, 0, 5, 5);
    gbc_passwordLabel.gridx = 0;
    gbc_passwordLabel.gridy = 1;
    setupFormPanel.add(passwordLabel, gbc_passwordLabel);
    passwordField = new JPasswordField();
    GridBagConstraints gbc_passwordField = new GridBagConstraints();
    gbc_passwordField.fill = GridBagConstraints.BOTH;
    gbc_passwordField.insets = new Insets(0, 0, 5, 0);
    gbc_passwordField.gridx = 1;
    gbc_passwordField.gridy = 1;
    setupFormPanel.add(passwordField, gbc_passwordField);
    passwordField.setColumns(10);

    JLabel receiverLabel = new JLabel("Mobile number");
    GridBagConstraints gbc_receiverLabel = new GridBagConstraints();
    gbc_receiverLabel.fill = GridBagConstraints.VERTICAL;
    gbc_receiverLabel.anchor = GridBagConstraints.WEST;
    gbc_receiverLabel.insets = new Insets(0, 0, 5, 5);
    gbc_receiverLabel.gridx = 0;
    gbc_receiverLabel.gridy = 2;
    setupFormPanel.add(receiverLabel, gbc_receiverLabel);

    receiverField = new JTextField();
    GridBagConstraints gbc_receiverField = new GridBagConstraints();
    gbc_receiverField.insets = new Insets(0, 0, 5, 0);
    gbc_receiverField.fill = GridBagConstraints.BOTH;
    gbc_receiverField.gridx = 1;
    gbc_receiverField.gridy = 2;
    setupFormPanel.add(receiverField, gbc_receiverField);
    receiverField.setColumns(10);

    JPanel backgroundPanel = new JPanel();
    FlowLayout flowLayout_1 = (FlowLayout) backgroundPanel.getLayout();
    flowLayout_1.setAlignment(FlowLayout.LEFT);
    tabbedPane.addTab("Background", null, backgroundPanel, null);

    JPanel backgroundFormPanel = new JPanel();
    backgroundPanel.add(backgroundFormPanel);
    GridBagLayout gbl_backgroundFormPanel = new GridBagLayout();
    gbl_backgroundFormPanel.columnWidths = new int[] { 150, 50, 100, 0 };
    gbl_backgroundFormPanel.rowHeights = new int[] { 0, 25, 0 };
    gbl_backgroundFormPanel.columnWeights = new double[] { 0.0, 0.0, 0.0, Double.MIN_VALUE };
    gbl_backgroundFormPanel.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
    backgroundFormPanel.setLayout(gbl_backgroundFormPanel);

    JLabel numberLabel = new JLabel("Number of CAPTCHAs");
    GridBagConstraints gbc_numberLabel = new GridBagConstraints();
    gbc_numberLabel.anchor = GridBagConstraints.WEST;
    gbc_numberLabel.insets = new Insets(0, 0, 5, 5);
    gbc_numberLabel.gridx = 0;
    gbc_numberLabel.gridy = 0;
    backgroundFormPanel.add(numberLabel, gbc_numberLabel);

    numberField = new JTextField();
    numberField.setText("5");
    GridBagConstraints gbc_numberField = new GridBagConstraints();
    gbc_numberField.anchor = GridBagConstraints.WEST;
    gbc_numberField.insets = new Insets(0, 0, 5, 5);
    gbc_numberField.gridx = 1;
    gbc_numberField.gridy = 0;
    backgroundFormPanel.add(numberField, gbc_numberField);
    numberField.setColumns(3);

    JButton numberButton = new JButton("Download");
    numberButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int counter = 0;

            do {
                BufferedImage captcha = downloadCAPTCHA();
                if (captcha != null) {
                    try {
                        int number = new File(tempFolder.getAbsolutePath()).listFiles().length;
                        File file = new File(tempFolder.getAbsolutePath() + "/background_" + number + ".png");
                        ImageIO.write(captcha, "png", file);
                        Thread.sleep(2500);
                    } catch (Exception x) {
                        x.printStackTrace();
                    }
                }
            } while (++counter < Integer.valueOf(numberField.getText()));

            Image background = loadBackground();
            if (background != null) {
                backgroundImage.setIcon(new ImageIcon(background));
            }
        }
    });
    GridBagConstraints gbc_numberButton = new GridBagConstraints();
    gbc_numberButton.anchor = GridBagConstraints.NORTHWEST;
    gbc_numberButton.insets = new Insets(0, 0, 5, 0);
    gbc_numberButton.gridx = 2;
    gbc_numberButton.gridy = 0;
    backgroundFormPanel.add(numberButton, gbc_numberButton);

    JLabel backgroundLabel = new JLabel("Current background");
    GridBagConstraints gbc_backgroundLabel = new GridBagConstraints();
    gbc_backgroundLabel.anchor = GridBagConstraints.WEST;
    gbc_backgroundLabel.insets = new Insets(0, 0, 0, 5);
    gbc_backgroundLabel.gridx = 0;
    gbc_backgroundLabel.gridy = 1;
    backgroundFormPanel.add(backgroundLabel, gbc_backgroundLabel);

    backgroundImage = new JLabel("");
    GridBagConstraints gbc_backgroundImage = new GridBagConstraints();
    gbc_backgroundImage.anchor = GridBagConstraints.WEST;
    gbc_backgroundImage.gridwidth = 2;
    gbc_backgroundImage.insets = new Insets(0, 0, 0, 5);
    gbc_backgroundImage.gridx = 1;
    gbc_backgroundImage.gridy = 1;
    backgroundFormPanel.add(backgroundImage, gbc_backgroundImage);

    JPanel trainingPanel = new JPanel();
    tabbedPane.addTab("Training", null, trainingPanel, null);
    GridBagLayout gbl_trainingPanel = new GridBagLayout();
    gbl_trainingPanel.columnWidths = new int[] { 437, 0 };
    gbl_trainingPanel.rowHeights = new int[] { 0, 0, 0 };
    gbl_trainingPanel.columnWeights = new double[] { 0.0, Double.MIN_VALUE };
    gbl_trainingPanel.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
    trainingPanel.setLayout(gbl_trainingPanel);

    trainingLoadPanel = new JPanel();
    GridBagConstraints gbc_trainingLoadPanel = new GridBagConstraints();
    gbc_trainingLoadPanel.anchor = GridBagConstraints.NORTHWEST;
    gbc_trainingLoadPanel.insets = new Insets(0, 0, 5, 0);
    gbc_trainingLoadPanel.gridx = 0;
    gbc_trainingLoadPanel.gridy = 0;
    trainingPanel.add(trainingLoadPanel, gbc_trainingLoadPanel);
    trainingLoadPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));

    JButton trainingLoadButton = new JButton("Download");
    trainingLoadButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            trainingCaptcha = downloadCAPTCHA();
            if (trainingCaptcha != null) {
                trainingCaptchaImage.setIcon(new ImageIcon(trainingCaptcha));
                List<Image> glyphs = loadGlyphs(trainingCaptcha);
                for (int g = 0; g < 5; ++g) {
                    trainingGlyphImage[g].setIcon(null);
                    trainingGlyphField[g].setText("");
                }
                for (int g = 0; g < glyphs.size() && g < 5; ++g) {
                    trainingGlyph[g] = glyphs.get(g);
                    trainingGlyphImage[g].setIcon(new ImageIcon(trainingGlyph[g]));
                }
                trainingLoadPanel.invalidate();
                trainingSavePanel.invalidate();
            }
        }
    });
    trainingLoadPanel.add(trainingLoadButton);

    trainingCaptchaImage = new JLabel("");
    trainingLoadPanel.add(trainingCaptchaImage);

    trainingSavePanel = new JPanel();
    GridBagConstraints gbc_trainingSavePanel = new GridBagConstraints();
    gbc_trainingSavePanel.insets = new Insets(0, 5, 0, 0);
    gbc_trainingSavePanel.anchor = GridBagConstraints.NORTHWEST;
    gbc_trainingSavePanel.gridx = 0;
    gbc_trainingSavePanel.gridy = 1;
    trainingPanel.add(trainingSavePanel, gbc_trainingSavePanel);
    GridBagLayout gbl_trainingSavePanel = new GridBagLayout();
    gbl_trainingSavePanel.columnWidths = new int[] { 25, 25, 25, 25, 25, 0, 0 };
    gbl_trainingSavePanel.rowHeights = new int[] { 25, 0, 0 };
    gbl_trainingSavePanel.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
    gbl_trainingSavePanel.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
    trainingSavePanel.setLayout(gbl_trainingSavePanel);

    trainingGlyph = new Image[5];
    trainingGlyphImage = new JLabel[5];
    trainingGlyphField = new JTextField[5];

    trainingGlyphImage[0] = new JLabel("");
    GridBagConstraints gbc_glyphImage0 = new GridBagConstraints();
    gbc_glyphImage0.anchor = GridBagConstraints.NORTHWEST;
    gbc_glyphImage0.insets = new Insets(0, 0, 5, 5);
    gbc_glyphImage0.gridx = 0;
    gbc_glyphImage0.gridy = 0;
    trainingGlyphImage[0].setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));
    trainingSavePanel.add(trainingGlyphImage[0], gbc_glyphImage0);

    trainingGlyphImage[1] = new JLabel("");
    GridBagConstraints gbc_glyphImage1 = new GridBagConstraints();
    gbc_glyphImage1.anchor = GridBagConstraints.NORTHWEST;
    gbc_glyphImage1.insets = new Insets(0, 0, 5, 5);
    gbc_glyphImage1.gridx = 1;
    gbc_glyphImage1.gridy = 0;
    trainingGlyphImage[1].setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));
    trainingSavePanel.add(trainingGlyphImage[1], gbc_glyphImage1);

    trainingGlyphImage[2] = new JLabel("");
    GridBagConstraints gbc_glyphImage2 = new GridBagConstraints();
    gbc_glyphImage2.anchor = GridBagConstraints.NORTHWEST;
    gbc_glyphImage2.insets = new Insets(0, 0, 5, 5);
    gbc_glyphImage2.gridx = 2;
    gbc_glyphImage2.gridy = 0;
    trainingGlyphImage[2].setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));
    trainingSavePanel.add(trainingGlyphImage[2], gbc_glyphImage2);

    trainingGlyphImage[3] = new JLabel("");
    GridBagConstraints gbc_glyphImage3 = new GridBagConstraints();
    gbc_glyphImage3.anchor = GridBagConstraints.NORTHWEST;
    gbc_glyphImage3.insets = new Insets(0, 0, 5, 5);
    gbc_glyphImage3.gridx = 3;
    gbc_glyphImage3.gridy = 0;
    trainingGlyphImage[3].setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));
    trainingSavePanel.add(trainingGlyphImage[3], gbc_glyphImage3);

    trainingGlyphImage[4] = new JLabel("");
    GridBagConstraints gbc_glyphImage4 = new GridBagConstraints();
    gbc_glyphImage4.insets = new Insets(0, 0, 5, 5);
    gbc_glyphImage4.anchor = GridBagConstraints.NORTHWEST;
    gbc_glyphImage4.gridx = 4;
    gbc_glyphImage4.gridy = 0;
    trainingGlyphImage[4].setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));
    trainingSavePanel.add(trainingGlyphImage[4], gbc_glyphImage4);

    JButton trainingSaveButton = new JButton("Train");
    trainingSaveButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            for (int g = 0; g < 5; ++g) {
                String s = trainingGlyphField[g].getText();
                if (s.length() == 1) {
                    char c = Character.toUpperCase(s.charAt(0));
                    net.sourceforge.javaocr.Image glyph = convertImage(trainingGlyph[g]);
                    grayFilter.process(glyph);
                    ThresholdFilter thresholdFilter = new ThresholdFilter(0, FG, BG);
                    thresholdFilter.process(glyph);
                    train(glyph, c);
                }
                trainingGlyphField[g].setText("");
            }

            for (Map.Entry<Character, Cluster> m : clusters.entrySet()) {
                System.out.println("****************************************");
                System.out.print(" character:  ");
                //          int samples = ((EuclidianDistanceCluster) m.getValue()).getAmountSamples();
                int samples = ((SigmaWeightedEuclidianDistanceCluster) m.getValue()).getAmountSamples();
                for (int s = 0; s < samples; ++s)
                    System.out.print(m.getKey());
                System.out.println();
                double[] c = m.getValue().center();
                for (int i = 0; i < c.length; ++i)
                    System.out.println(" centroid[" + i + "]: " + c[i]);
            }

            System.out.println("****************************************");
            System.out.println("TOTAL CLUSTERS: " + clusters.size());
        }
    });
    GridBagConstraints gbc_trainingSaveButton = new GridBagConstraints();
    gbc_trainingSaveButton.gridheight = 2;
    gbc_trainingSaveButton.insets = new Insets(0, 0, 5, 0);
    gbc_trainingSaveButton.gridx = 5;
    gbc_trainingSaveButton.gridy = 0;
    trainingSavePanel.add(trainingSaveButton, gbc_trainingSaveButton);

    trainingGlyphField[0] = new JTextField();
    GridBagConstraints gbc_glyphField0 = new GridBagConstraints();
    gbc_glyphField0.fill = GridBagConstraints.HORIZONTAL;
    gbc_glyphField0.anchor = GridBagConstraints.NORTHWEST;
    gbc_glyphField0.insets = new Insets(0, 0, 0, 5);
    gbc_glyphField0.gridx = 0;
    gbc_glyphField0.gridy = 1;
    trainingSavePanel.add(trainingGlyphField[0], gbc_glyphField0);
    trainingGlyphField[0].setColumns(2);

    trainingGlyphField[1] = new JTextField();
    GridBagConstraints gbc_glyphField1 = new GridBagConstraints();
    gbc_glyphField1.fill = GridBagConstraints.HORIZONTAL;
    gbc_glyphField1.anchor = GridBagConstraints.NORTHWEST;
    gbc_glyphField1.insets = new Insets(0, 0, 0, 5);
    gbc_glyphField1.gridx = 1;
    gbc_glyphField1.gridy = 1;
    trainingSavePanel.add(trainingGlyphField[1], gbc_glyphField1);
    trainingGlyphField[1].setColumns(2);

    trainingGlyphField[2] = new JTextField();
    GridBagConstraints gbc_glyphField2 = new GridBagConstraints();
    gbc_glyphField2.fill = GridBagConstraints.HORIZONTAL;
    gbc_glyphField2.anchor = GridBagConstraints.NORTHWEST;
    gbc_glyphField2.insets = new Insets(0, 0, 0, 5);
    gbc_glyphField2.gridx = 2;
    gbc_glyphField2.gridy = 1;
    trainingSavePanel.add(trainingGlyphField[2], gbc_glyphField2);
    trainingGlyphField[2].setColumns(2);

    trainingGlyphField[3] = new JTextField();
    GridBagConstraints gbc_glyphField3 = new GridBagConstraints();
    gbc_glyphField3.fill = GridBagConstraints.HORIZONTAL;
    gbc_glyphField3.anchor = GridBagConstraints.NORTHWEST;
    gbc_glyphField3.insets = new Insets(0, 0, 0, 5);
    gbc_glyphField3.gridx = 3;
    gbc_glyphField3.gridy = 1;
    trainingSavePanel.add(trainingGlyphField[3], gbc_glyphField3);
    trainingGlyphField[3].setColumns(2);

    trainingGlyphField[4] = new JTextField();
    GridBagConstraints gbc_glyphField4 = new GridBagConstraints();
    gbc_glyphField4.insets = new Insets(0, 0, 0, 5);
    gbc_glyphField4.fill = GridBagConstraints.HORIZONTAL;
    gbc_glyphField4.anchor = GridBagConstraints.NORTHWEST;
    gbc_glyphField4.gridx = 4;
    gbc_glyphField4.gridy = 1;
    trainingSavePanel.add(trainingGlyphField[4], gbc_glyphField4);
    trainingGlyphField[4].setColumns(2);

    JPanel testingPanel = new JPanel();
    tabbedPane.addTab("Testing", null, testingPanel, null);
    GridBagLayout gbl_testingPanel = new GridBagLayout();
    gbl_testingPanel.columnWidths = new int[] { 437, 0 };
    gbl_testingPanel.rowHeights = new int[] { 0, 0, 0, 0 };
    gbl_testingPanel.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
    gbl_testingPanel.rowWeights = new double[] { 0.0, 0.0, 1.0, Double.MIN_VALUE };
    testingPanel.setLayout(gbl_testingPanel);

    testingLoadPanel = new JPanel();
    GridBagConstraints gbc_testingLoadPanel = new GridBagConstraints();
    gbc_testingLoadPanel.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingLoadPanel.insets = new Insets(0, 0, 5, 0);
    gbc_testingLoadPanel.gridx = 0;
    gbc_testingLoadPanel.gridy = 0;
    testingPanel.add(testingLoadPanel, gbc_testingLoadPanel);
    testingLoadPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));

    JButton testingLoadButton = new JButton("Download");
    testingLoadButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            testingCaptcha = downloadCAPTCHA();
            if (testingCaptcha != null) {
                testingCaptchaImage.setIcon(new ImageIcon(testingCaptcha));
                List<Image> glyphs = loadGlyphs(testingCaptcha);
                for (int g = 0; g < 5; ++g) {
                    testingGlyphImage[g].setIcon(null);
                    testingGlyphField[g].setText("");
                }
                for (int g = 0; g < glyphs.size() && g < 5; ++g) {
                    testingGlyph[g] = glyphs.get(g);
                    testingGlyphImage[g].setIcon(new ImageIcon(testingGlyph[g]));
                }
                testingLoadPanel.invalidate();
                testingSavePanel.invalidate();
            }
        }
    });
    testingLoadPanel.add(testingLoadButton);

    testingCaptchaImage = new JLabel("");
    testingLoadPanel.add(testingCaptchaImage);

    testingSavePanel = new JPanel();
    GridBagConstraints gbc_testingSavePanel = new GridBagConstraints();
    gbc_testingSavePanel.insets = new Insets(0, 5, 5, 0);
    gbc_testingSavePanel.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingSavePanel.gridx = 0;
    gbc_testingSavePanel.gridy = 1;
    testingPanel.add(testingSavePanel, gbc_testingSavePanel);
    GridBagLayout gbl_testingSavePanel = new GridBagLayout();
    gbl_testingSavePanel.columnWidths = new int[] { 25, 25, 25, 25, 25, 0, 0 };
    gbl_testingSavePanel.rowHeights = new int[] { 25, 0, 0 };
    gbl_testingSavePanel.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
    gbl_testingSavePanel.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
    testingSavePanel.setLayout(gbl_testingSavePanel);

    testingGlyph = new Image[5];
    testingGlyphImage = new JLabel[5];
    testingGlyphField = new JTextField[5];

    testingGlyphImage[0] = new JLabel("");
    GridBagConstraints gbc_testingGlyphImage0 = new GridBagConstraints();
    gbc_testingGlyphImage0.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingGlyphImage0.insets = new Insets(0, 0, 5, 5);
    gbc_testingGlyphImage0.gridx = 0;
    gbc_testingGlyphImage0.gridy = 0;
    testingGlyphImage[0].setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));
    testingSavePanel.add(testingGlyphImage[0], gbc_testingGlyphImage0);

    testingGlyphImage[1] = new JLabel("");
    GridBagConstraints gbc_testingGlyphImage1 = new GridBagConstraints();
    gbc_testingGlyphImage1.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingGlyphImage1.insets = new Insets(0, 0, 5, 5);
    gbc_testingGlyphImage1.gridx = 1;
    gbc_testingGlyphImage1.gridy = 0;
    testingGlyphImage[1].setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));
    testingSavePanel.add(testingGlyphImage[1], gbc_testingGlyphImage1);

    testingGlyphImage[2] = new JLabel("");
    GridBagConstraints gbc_testingGlyphImage2 = new GridBagConstraints();
    gbc_testingGlyphImage2.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingGlyphImage2.insets = new Insets(0, 0, 5, 5);
    gbc_testingGlyphImage2.gridx = 2;
    gbc_testingGlyphImage2.gridy = 0;
    testingGlyphImage[2].setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));
    testingSavePanel.add(testingGlyphImage[2], gbc_testingGlyphImage2);

    testingGlyphImage[3] = new JLabel("");
    GridBagConstraints gbc_testingGlyphImage3 = new GridBagConstraints();
    gbc_testingGlyphImage3.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingGlyphImage3.insets = new Insets(0, 0, 5, 5);
    gbc_testingGlyphImage3.gridx = 3;
    gbc_testingGlyphImage3.gridy = 0;
    testingGlyphImage[3].setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));
    testingSavePanel.add(testingGlyphImage[3], gbc_testingGlyphImage3);

    testingGlyphImage[4] = new JLabel("");
    GridBagConstraints gbc_testingGlyphImage4 = new GridBagConstraints();
    gbc_testingGlyphImage4.insets = new Insets(0, 0, 5, 5);
    gbc_testingGlyphImage4.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingGlyphImage4.gridx = 4;
    gbc_testingGlyphImage4.gridy = 0;
    testingGlyphImage[4].setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));
    testingSavePanel.add(testingGlyphImage[4], gbc_testingGlyphImage4);

    JButton testingSaveButton = new JButton("Save and test");
    testingSaveButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String text = "";
            for (int g = 0; g < 5; ++g) {
                String s = testingGlyphField[g].getText();
                if (s.length() == 1)
                    text += s.toUpperCase();
                trainingGlyphField[g].setText("");
            }

            if (text.length() != 5)
                return;

            try {
                File file = new File(tempFolder.getAbsolutePath() + "/captcha_" + text + ".png");
                ImageIO.write(testingCaptcha, "png", file);
            } catch (IOException x) {
                x.printStackTrace();
            }

            testingViewArea.setText(loadStatistics());
        }
    });
    GridBagConstraints gbc_testingSaveButton = new GridBagConstraints();
    gbc_testingSaveButton.gridheight = 2;
    gbc_testingSaveButton.insets = new Insets(0, 0, 5, 0);
    gbc_testingSaveButton.gridx = 5;
    gbc_testingSaveButton.gridy = 0;
    testingSavePanel.add(testingSaveButton, gbc_testingSaveButton);

    testingGlyphField[0] = new JTextField();
    GridBagConstraints gbc_testingGlyphField0 = new GridBagConstraints();
    gbc_testingGlyphField0.fill = GridBagConstraints.HORIZONTAL;
    gbc_testingGlyphField0.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingGlyphField0.insets = new Insets(0, 0, 0, 5);
    gbc_testingGlyphField0.gridx = 0;
    gbc_testingGlyphField0.gridy = 1;
    testingSavePanel.add(testingGlyphField[0], gbc_testingGlyphField0);
    testingGlyphField[0].setColumns(2);

    testingGlyphField[1] = new JTextField();
    GridBagConstraints gbc_testingGlyphField1 = new GridBagConstraints();
    gbc_testingGlyphField1.fill = GridBagConstraints.HORIZONTAL;
    gbc_testingGlyphField1.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingGlyphField1.insets = new Insets(0, 0, 0, 5);
    gbc_testingGlyphField1.gridx = 1;
    gbc_testingGlyphField1.gridy = 1;
    testingSavePanel.add(testingGlyphField[1], gbc_testingGlyphField1);
    testingGlyphField[1].setColumns(2);

    testingGlyphField[2] = new JTextField();
    GridBagConstraints gbc_testingGlyphField2 = new GridBagConstraints();
    gbc_testingGlyphField2.fill = GridBagConstraints.HORIZONTAL;
    gbc_testingGlyphField2.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingGlyphField2.insets = new Insets(0, 0, 0, 5);
    gbc_testingGlyphField2.gridx = 2;
    gbc_testingGlyphField2.gridy = 1;
    testingSavePanel.add(testingGlyphField[2], gbc_testingGlyphField2);
    testingGlyphField[2].setColumns(2);

    testingGlyphField[3] = new JTextField();
    GridBagConstraints gbc_testingGlyphField3 = new GridBagConstraints();
    gbc_testingGlyphField3.fill = GridBagConstraints.HORIZONTAL;
    gbc_testingGlyphField3.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingGlyphField3.insets = new Insets(0, 0, 0, 5);
    gbc_testingGlyphField3.gridx = 3;
    gbc_testingGlyphField3.gridy = 1;
    testingSavePanel.add(testingGlyphField[3], gbc_testingGlyphField3);
    testingGlyphField[3].setColumns(2);

    testingGlyphField[4] = new JTextField();
    GridBagConstraints gbc_testingGlyphField4 = new GridBagConstraints();
    gbc_testingGlyphField4.insets = new Insets(0, 0, 0, 5);
    gbc_testingGlyphField4.fill = GridBagConstraints.HORIZONTAL;
    gbc_testingGlyphField4.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingGlyphField4.gridx = 4;
    gbc_testingGlyphField4.gridy = 1;
    testingSavePanel.add(testingGlyphField[4], gbc_testingGlyphField4);

    JPanel testingViewPanel = new JPanel();
    GridBagConstraints gbc_testingViewPanel = new GridBagConstraints();
    gbc_testingViewPanel.fill = GridBagConstraints.HORIZONTAL;
    gbc_testingViewPanel.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingViewPanel.gridx = 0;
    gbc_testingViewPanel.gridy = 2;
    testingPanel.add(testingViewPanel, gbc_testingViewPanel);
    GridBagLayout gbl_testingViewPanel = new GridBagLayout();
    gbl_testingViewPanel.columnWidths = new int[] { 330, 0 };
    gbl_testingViewPanel.rowHeights = new int[] { 75, 0 };
    gbl_testingViewPanel.columnWeights = new double[] { 0.0, Double.MIN_VALUE };
    gbl_testingViewPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
    testingViewPanel.setLayout(gbl_testingViewPanel);

    testingViewArea = new JTextArea();
    testingViewArea.setRows(5);
    testingViewArea.setColumns(30);
    GridBagConstraints gbc_testingViewArea = new GridBagConstraints();
    gbc_testingViewArea.fill = GridBagConstraints.BOTH;
    gbc_testingViewArea.anchor = GridBagConstraints.NORTHWEST;
    gbc_testingViewArea.gridx = 0;
    gbc_testingViewArea.gridy = 0;
    testingViewPanel.add(testingViewArea, gbc_testingViewArea);
    testingGlyphField[4].setColumns(2);

    JPanel outputPanel = new JPanel();
    FlowLayout flowLayout2 = (FlowLayout) outputPanel.getLayout();
    flowLayout2.setAlignment(FlowLayout.LEFT);
    tabbedPane.addTab("Output", null, outputPanel, null);

    JPanel outputFormPanel = new JPanel();
    outputPanel.add(outputFormPanel);
    GridBagLayout gbl_outputFormPanel = new GridBagLayout();
    gbl_outputFormPanel.columnWidths = new int[] { 150, 250 };
    gbl_outputFormPanel.rowHeights = new int[] { 0 };
    gbl_outputFormPanel.columnWeights = new double[] { 0.0, 1.0 };
    gbl_outputFormPanel.rowWeights = new double[] { 0.0 };
    outputFormPanel.setLayout(gbl_outputFormPanel);

    JLabel javaLabel = new JLabel("Output .java file");
    GridBagConstraints gbc_javaLabel = new GridBagConstraints();
    gbc_javaLabel.anchor = GridBagConstraints.WEST;
    gbc_javaLabel.fill = GridBagConstraints.VERTICAL;
    gbc_javaLabel.insets = new Insets(0, 0, 5, 5);
    gbc_javaLabel.gridx = 0;
    gbc_javaLabel.gridy = 0;
    outputFormPanel.add(javaLabel, gbc_javaLabel);

    javaField = new JTextField();
    javaField.addFocusListener(new FocusListener() {
        public void focusLost(FocusEvent e) {
            javaField.removeFocusListener(this);
        }

        public void focusGained(FocusEvent e) {
            JFileChooser chooser = new JFileChooser(outFolderName);
            chooser.setSelectedFile(new File(outFileName));
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            if (chooser.showDialog(frame, "Save .java file") == JFileChooser.APPROVE_OPTION) {
                javaField.setText(chooser.getSelectedFile().getAbsolutePath());

                try {
                    PrintWriter output = new PrintWriter(
                            new FileWriter(chooser.getSelectedFile().getAbsolutePath()));
                    output.println("package com.googlecode.libautocaptcha.decoder.data;");
                    output.println("import net.sourceforge.javaocr.plugin.cluster.Cluster;");
                    output.println("import net.sourceforge.javaocr.plugin.cluster.MahalanobisDistanceCluster;");
                    output.println("public class VodafoneItalyData {");

                    output.println("  public static final int[] " + BACKGROUND_FIELD + " = ");
                    output.print("    new int[] { ");
                    for (int y = 0; y < HEIGHT; ++y)
                        for (int x = 0; x < WIDTH; ++x)
                            output.print(background.get(x, y) + ", ");
                    output.println("};");

                    output.println("  public static final char[] " + CHARACTERS_FIELD + " = ");
                    output.print("    new char[] { ");
                    for (Character c : clusters.keySet())
                        output.print("'" + c + "', ");
                    output.println("};");

                    output.println("  public static final Cluster[] " + CLUSTERS_FIELD + " = ");
                    output.print("    new MahalanobisDistanceCluster[] { ");
                    for (Cluster c : clusters.values()) {
                        output.print("new MahalanobisDistanceCluster(new double[] { ");
                        double[] mx = ((MahalanobisDistanceCluster) c).getMx();
                        for (double i : mx)
                            output.print(i + ", ");
                        output.print("}, new double[][] { ");
                        double[][] invcov = ((MahalanobisDistanceCluster) c).getInvcov();
                        for (double[] row : invcov) {
                            output.print("new double[] { ");
                            for (double i : row)
                                output.print(i + ", ");
                            output.print("}, ");
                        }
                        output.print("}), ");
                    }
                    output.println("};");

                    output.println("}");
                    output.close();
                } catch (IOException x) {
                    x.printStackTrace();
                }
            }
        }
    });
    GridBagConstraints gbc_javaField = new GridBagConstraints();
    gbc_javaField.fill = GridBagConstraints.BOTH;
    gbc_javaField.insets = new Insets(0, 0, 5, 0);
    gbc_javaField.gridx = 1;
    gbc_javaField.gridy = 0;
    outputFormPanel.add(javaField, gbc_javaField);
    javaField.setColumns(10);

    JPanel statusPanel = new JPanel();
    frame.getContentPane().add(statusPanel, BorderLayout.SOUTH);
    GridBagLayout gbl_statusPanel = new GridBagLayout();
    gbl_statusPanel.columnWidths = new int[] { 150, 0, 0 };
    gbl_statusPanel.rowHeights = new int[] { 14, 0 };
    gbl_statusPanel.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
    gbl_statusPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
    statusPanel.setLayout(gbl_statusPanel);

    statusBar = new JProgressBar();
    GridBagConstraints gbc_statusBar = new GridBagConstraints();
    gbc_statusBar.insets = new Insets(0, 0, 0, 5);
    gbc_statusBar.gridx = 0;
    gbc_statusBar.gridy = 0;
    statusPanel.add(statusBar, gbc_statusBar);

    statusLabel = new JLabel("");
    GridBagConstraints gbc_statusLabel = new GridBagConstraints();
    gbc_statusLabel.fill = GridBagConstraints.HORIZONTAL;
    gbc_statusLabel.gridx = 1;
    gbc_statusLabel.gridy = 0;
    statusPanel.add(statusLabel, gbc_statusLabel);
}

From source file:org.encog.workbench.tabs.visualize.structure.GenomeStructureTab.java

public GenomeStructureTab(NEATGenome genome) {
    super(null);// w  ww.j a v a2s  . c  o  m
    this.genome = genome;

    // Graph<V, E> where V is the type of the vertices
    // and E is the type of the edges
    Graph<DrawnNeuron, DrawnConnection> g = null;
    g = buildGraph(genome);

    if (g == null) {
        throw new WorkBenchError("Can't visualize genome");
    }

    Transformer<DrawnNeuron, Point2D> staticTranformer = new Transformer<DrawnNeuron, Point2D>() {

        public Point2D transform(DrawnNeuron n) {
            int x = (int) (n.getX() * 600);
            int y = (int) (n.getY() * 300);

            Point2D result = new Point(x + 32, y);
            return result;
        }
    };

    Transformer<DrawnNeuron, Paint> vertexPaint = new Transformer<DrawnNeuron, Paint>() {
        public Paint transform(DrawnNeuron neuron) {
            switch (neuron.getType()) {
            case Bias:
                return Color.yellow;
            case Input:
                return Color.white;
            case Output:
                return Color.green;
            case Context:
                return Color.cyan;
            case Linear:
                return Color.blue;
            case Sigmoid:
                return Color.magenta;
            case Gaussian:
                return Color.cyan;
            case SIN:
                return Color.gray;
            default:
                return Color.red;
            }
        }

    };

    Transformer<DrawnConnection, Paint> edgePaint = new Transformer<DrawnConnection, Paint>() {
        public Paint transform(DrawnConnection connection) {
            if (connection.isContext()) {
                return Color.lightGray;
            } else {
                return Color.black;
            }
        }
    };

    // The Layout<V, E> is parameterized by the vertex and edge types
    StaticLayout<DrawnNeuron, DrawnConnection> layout = new StaticLayout<DrawnNeuron, DrawnConnection>(g,
            staticTranformer);

    layout.setSize(new Dimension(5000, 5000)); // sets the initial size of
    // the space
    // The BasicVisualizationServer<V,E> is parameterized by the edge types
    // BasicVisualizationServer<DrawnNeuron, DrawnConnection> vv = new
    // BasicVisualizationServer<DrawnNeuron, DrawnConnection>(
    // layout);

    // Dimension d = new Dimension(600,600);

    vv = new VisualizationViewer<DrawnNeuron, DrawnConnection>(layout);

    // vv.setPreferredSize(d); //Sets the viewing area size

    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
    vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint);
    vv.getRenderContext().setEdgeDrawPaintTransformer(edgePaint);
    vv.getRenderContext().setArrowDrawPaintTransformer(edgePaint);
    vv.getRenderContext().setArrowFillPaintTransformer(edgePaint);

    vv.setVertexToolTipTransformer(new ToStringLabeller());

    vv.setVertexToolTipTransformer(new Transformer<DrawnNeuron, String>() {
        public String transform(DrawnNeuron edge) {
            return edge.getToolTip();
        }
    });

    vv.setEdgeToolTipTransformer(new Transformer<DrawnConnection, String>() {
        public String transform(DrawnConnection edge) {
            return edge.getToolTip();
        }
    });

    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    this.setLayout(new BorderLayout());
    add(panel, BorderLayout.CENTER);
    final AbstractModalGraphMouse graphMouse = new DefaultModalGraphMouse();
    vv.setGraphMouse(graphMouse);

    vv.addKeyListener(graphMouse.getModeKeyListener());

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JButton reset = new JButton("reset");
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).setToIdentity();
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).setToIdentity();
        }
    });

    JPanel controls = new JPanel();
    controls.setLayout(new FlowLayout(FlowLayout.LEFT));
    controls.add(plus);
    controls.add(minus);
    controls.add(reset);
    Border border = BorderFactory.createEtchedBorder();
    controls.setBorder(border);
    add(controls, BorderLayout.NORTH);
    add(new LegendPanel(true), BorderLayout.SOUTH);

}

From source file:org.tinymediamanager.ui.movies.settings.MovieTrailerSettingsPanel.java

public MovieTrailerSettingsPanel() {
    // data init/*from  www.j  a v a 2 s.c  o  m*/
    List<String> enabledTrailerProviders = settings.getMovieTrailerScrapers();
    int selectedIndex = -1;
    int counter = 0;
    for (MediaScraper scraper : MovieList.getInstance().getAvailableTrailerScrapers()) {
        TrailerScraper trailerScraper = new TrailerScraper(scraper);
        if (enabledTrailerProviders.contains(trailerScraper.getScraperId())) {
            trailerScraper.active = true;
            if (selectedIndex < 0) {
                selectedIndex = counter;
            }
        }
        scrapers.add(trailerScraper);
        counter++;
    }

    // UI init
    setLayout(new FormLayout(
            new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow"),
                    FormSpecs.RELATED_GAP_COLSPEC, },
            new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, RowSpec.decode("default:grow"),
                    FormSpecs.RELATED_GAP_ROWSPEC, }));

    JPanel panelTrailerScrapers = new JPanel();
    panelTrailerScrapers.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            BUNDLE.getString("scraper.trailer"), TitledBorder.LEADING, TitledBorder.TOP, null, null)); // $NON-NLS-1$
    add(panelTrailerScrapers, "2, 2, fill, fill");
    panelTrailerScrapers.setLayout(new FormLayout(
            new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.UNRELATED_GAP_COLSPEC,
                    FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC,
                    ColumnSpec.decode("default:grow"), FormSpecs.RELATED_GAP_COLSPEC,
                    ColumnSpec.decode("200dlu:grow"), FormSpecs.RELATED_GAP_COLSPEC, },
            new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, RowSpec.decode("100dlu:grow"),
                    FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
                    FormSpecs.DEFAULT_ROWSPEC, FormSpecs.LABEL_COMPONENT_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC,
                    FormSpecs.LABEL_COMPONENT_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC,
                    FormSpecs.UNRELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC,
                    FormSpecs.LABEL_COMPONENT_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC,
                    FormSpecs.RELATED_GAP_ROWSPEC, }));

    final JScrollPane scrollPaneScraperDetails = new JScrollPane();
    scrollPaneScraperDetails.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPaneScraperDetails.setBorder(null);
    panelTrailerScrapers.add(scrollPaneScraperDetails, "8, 1, 1, 2, fill, fill");

    JPanel panelScraperDetails = new JPanel();
    scrollPaneScraperDetails.setViewportView(panelScraperDetails);
    panelScraperDetails.setLayout(new FormLayout(new ColumnSpec[] { ColumnSpec.decode("default:grow"), },
            new RowSpec[] { RowSpec.decode("default:grow"), FormSpecs.RELATED_GAP_ROWSPEC,
                    FormSpecs.DEFAULT_ROWSPEC, }));
    {
        // add a CSS rule to force body tags to use the default label font
        // instead of the value in javax.swing.text.html.default.csss
        Font font = UIManager.getFont("Label.font");
        String bodyRule = "body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize()
                + "pt; }";
        tpScraperDescription = new JTextPane();
        tpScraperDescription.setOpaque(false);
        tpScraperDescription.setEditorKit(new HTMLEditorKit());
        ((HTMLDocument) tpScraperDescription.getDocument()).getStyleSheet().addRule(bodyRule);
        panelScraperDetails.add(tpScraperDescription, "1, 1, fill, top");
    }
    panelScraperOptions = new ScrollablePanel();
    panelScraperOptions.setLayout(new FlowLayout(FlowLayout.LEFT));
    panelScraperDetails.add(panelScraperOptions, "1, 3, fill, top");

    JScrollPane scrollPaneScraper = new JScrollPane();
    panelTrailerScrapers.add(scrollPaneScraper, "2, 2, 5, 1, fill, fill");

    tableTrailerScraper = new JTable();
    tableTrailerScraper.setRowHeight(29);
    scrollPaneScraper.setViewportView(tableTrailerScraper);

    JSeparator separator = new JSeparator();
    panelTrailerScrapers.add(separator, "2, 4, 7, 1");

    checkBox = new JCheckBox(BUNDLE.getString("Settings.trailer.preferred")); //$NON-NLS-1$
    panelTrailerScrapers.add(checkBox, "2, 6, 7, 1");

    JLabel lblTrailerSource = new JLabel(BUNDLE.getString("Settings.trailer.source")); //$NON-NLS-1$
    panelTrailerScrapers.add(lblTrailerSource, "4, 8, right, default");

    cbTrailerSource = new JComboBox<>();
    cbTrailerSource.setModel(new DefaultComboBoxModel<>(MovieTrailerSources.values()));
    panelTrailerScrapers.add(cbTrailerSource, "6, 8, fill, default");

    JLabel lblTrailerQuality = new JLabel(BUNDLE.getString("Settings.trailer.quality")); //$NON-NLS-1$
    panelTrailerScrapers.add(lblTrailerQuality, "4, 10, right, default");

    cbTrailerQuality = new JComboBox<>();
    cbTrailerQuality.setModel(new DefaultComboBoxModel<>(MovieTrailerQuality.values()));
    panelTrailerScrapers.add(cbTrailerQuality, "6, 10, fill, default");

    chckbxAutomaticTrailerDownload = new JCheckBox(BUNDLE.getString("Settings.trailer.automaticdownload")); //$NON-NLS-1$
    panelTrailerScrapers.add(chckbxAutomaticTrailerDownload, "2, 12, 7, 1");

    JLabel lblAutomaticTrailerDownloadHint = new JLabel(
            BUNDLE.getString("Settings.trailer.automaticdownload.hint")); //$NON-NLS-1$
    TmmFontHelper.changeFont(lblAutomaticTrailerDownloadHint, 0.833);
    panelTrailerScrapers.add(lblAutomaticTrailerDownloadHint, "4, 14, 5, 1");

    initDataBindings();

    // adjust table columns
    // Checkbox and Logo shall have minimal width
    TableColumnResizer.setMaxWidthForColumn(tableTrailerScraper, 0, 2);
    TableColumnResizer.setMaxWidthForColumn(tableTrailerScraper, 1, 2);
    TableColumnResizer.adjustColumnPreferredWidths(tableTrailerScraper, 5);

    tableTrailerScraper.getModel().addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent arg0) {
            // click on the checkbox
            if (arg0.getColumn() == 0) {
                int row = arg0.getFirstRow();
                TrailerScraper changedScraper = scrapers.get(row);
                if (changedScraper.active) {
                    settings.addMovieTrailerScraper(changedScraper.getScraperId());
                } else {
                    settings.removeMovieTrailerScraper(changedScraper.getScraperId());
                }
            }
        }
    });

    // implement selection listener to load settings
    tableTrailerScraper.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            int index = tableTrailerScraper.convertRowIndexToModel(tableTrailerScraper.getSelectedRow());
            if (index > -1) {
                panelScraperOptions.removeAll();
                if (scrapers.get(index).getMediaProvider().getProviderInfo().getConfig().hasConfig()) {
                    panelScraperOptions
                            .add(new MediaScraperConfigurationPanel(scrapers.get(index).getMediaProvider()));
                }
                panelScraperOptions.revalidate();
            }
        }
    });

    // select default movie scraper
    if (selectedIndex < 0) {
        selectedIndex = 0;
    }
    if (counter > 0) {
        tableTrailerScraper.getSelectionModel().setSelectionInterval(selectedIndex, selectedIndex);
    }
}

From source file:org.piraso.ui.base.PreferencePanel.java

private void initPreferenceComponentsHorizontalChildLayout() {
    handlers = new ArrayList<ParentChildHandler>();
    CellConstraints c = new CellConstraints();

    int size = CollectionUtils.size(provider.getPreferences());

    int l = 0, r = 2;
    chkPreferences = new JCheckBox[size];
    preferenceKeys = new PreferenceProperty[size];

    JLabel lblHeader = new JLabel(provider.getName());
    Font of = lblHeader.getFont();
    lblHeader.setFont(of.deriveFont(Font.BOLD));

    pnlPreferences.add(lblHeader, c.xyw(2, r, 5));
    r += 2;/* w  w w.  j av a2  s.co  m*/

    JButton parentToggle = null;
    JPanel childrenPanel = null;
    ParentChildHandler parentChildHandler = null;

    Iterator<? extends PreferenceProperty> itrp = provider.getPreferences().iterator();
    for (int j = 0; j < provider.getPreferences().size(); j++, l++) {
        PreferenceProperty prop = itrp.next();

        preferenceKeys[l] = prop;
        chkPreferences[l] = new JCheckBox();
        chkPreferences[l].setText(provider.getMessage(prop.getName()));
        chkPreferences[l].setSelected(prop.isDefaultValue());

        if (prop.isChild()) {
            if (childrenPanel == null) {
                childrenPanel = new JPanel();
                childrenPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 1, 1));
                childrenPanel.setOpaque(false);
                childrenPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 1));
                childrenPanel.setVisible(false);

                if (parentChildHandler != null) {
                    parentChildHandler.setChildrenPanel(childrenPanel);
                }

                pnlPreferences.add(childrenPanel, c.xy(6, r));

                r += 2;
            }

            if (parentChildHandler != null) {
                parentChildHandler.addPreference(chkPreferences[l]);
            }

            childrenPanel.add(chkPreferences[l]);
            parentToggle = null;
        } else {
            if (parentToggle != null) {
                parentChildHandler.hide();
            }

            JPanel parentPanel = new JPanel();
            parentPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 1, 1));
            parentPanel.setOpaque(false);

            parentToggle = new JButton(expandImage);

            JLabel previewLabel = new JLabel();
            previewLabel.setForeground(new Color(0, 128, 0));
            previewLabel.setFont(previewLabel.getFont().deriveFont(Font.ITALIC));

            parentChildHandler = new ParentChildHandler(parentToggle, previewLabel);
            parentChildHandler.addPreference(chkPreferences[l]);
            handlers.add(parentChildHandler);

            parentToggle.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));

            parentPanel.add(parentToggle);
            parentPanel.add(chkPreferences[l]);
            parentPanel.add(previewLabel);

            pnlPreferences.add(parentPanel, c.xyw(4, r, 3));

            childrenPanel = null;
            r += 2;
        }

        chkPreferences[l].addActionListener(new CheckBoxClickHandler(l, parentChildHandler));
    }
}