Example usage for javax.swing JSlider JSlider

List of usage examples for javax.swing JSlider JSlider

Introduction

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

Prototype

public JSlider(BoundedRangeModel brm) 

Source Link

Document

Creates a horizontal slider using the specified BoundedRangeModel.

Usage

From source file:Main.java

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

    JSlider slider = new JSlider(JSlider.VERTICAL);
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    String title = (args.length == 0 ? "Sample Slider" : args[0]);
    JFrame frame = new JFrame(title);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JSlider js4 = new JSlider(JSlider.VERTICAL);
    Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel>();
    table.put(0, new JLabel("O"));
    table.put(10, new JLabel("Ten"));
    table.put(25, new JLabel("Twenty-Five"));
    table.put(34, new JLabel("Thirty-Four"));
    table.put(52, new JLabel("Fifty-Two"));
    table.put(70, new JLabel("Seventy"));
    table.put(82, new JLabel("Eighty-Two"));
    table.put(100, new JLabel("100"));
    js4.setLabelTable(table);//from  w  ww  . ja  v a  2 s  .  c o m
    js4.setPaintLabels(true);
    js4.setSnapToTicks(true);
    frame.add(js4, BorderLayout.EAST);
    frame.setSize(300, 200);
    frame.setVisible(true);

}

From source file:Main.java

/**
 * Creates a JSlider built/*from  w w w. j a va  2  s.c  o  m*/
 * using a {@link DefaultBoundedRangeModel} and 
 * containing a {@link MouseWheelListener} 
 * and some usual default settings
 * 
 * @param model
 * @return the corresponding {@link JSlider}
 */
public static JSlider createJSlider(final BoundedRangeModel model) {
    final JSlider slider = new JSlider(model);
    slider.addMouseWheelListener(new MouseWheelListener() {
        @Override
        public void mouseWheelMoved(MouseWheelEvent e) {
            slider.setValue(-e.getWheelRotation() * model.getMaximum() / 100 + model.getValue());
        }
    });
    slider.setPaintTicks(true);
    slider.setPaintLabels(true);
    //      slider.setMajorTickSpacing(model.getMaximum()/2);
    //      slider.setMinorTickSpacing(model.getMaximum()/10);
    //      slider.setSnapToTicks(true);
    return slider;
}

From source file:MainClass.java

public MainClass() {
    Container cp = new Box(BoxLayout.X_AXIS);
    setContentPane(cp);/*from   w ww  . j  a  v  a2s  .  com*/
    JPanel firstPanel = new JPanel();
    propertyComboBox = new JComboBox();
    propertyComboBox.addItem("text");
    propertyComboBox.addItem("font");
    propertyComboBox.addItem("background");
    propertyComboBox.addItem("foreground");
    firstPanel.add(propertyComboBox);
    cp.add(firstPanel);
    cp.add(Box.createGlue());

    tf = new JTextField("Hello");
    tf.setForeground(Color.RED);
    tf.setDragEnabled(true);
    cp.add(tf);

    cp.add(Box.createGlue());

    l = new JLabel("Hello");
    l.setBackground(Color.YELLOW);
    cp.add(l);

    cp.add(Box.createGlue());

    JSlider stryder = new JSlider(SwingConstants.VERTICAL);
    stryder.setMinimum(10);
    stryder.setValue(14);
    stryder.setMaximum(72);
    stryder.setMajorTickSpacing(10);
    stryder.setPaintTicks(true);

    cp.add(stryder);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500, 300);

    setMyTransferHandlers((String) propertyComboBox.getSelectedItem());

    MouseListener myDragListener = new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            JComponent c = (JComponent) e.getSource();
            TransferHandler handler = c.getTransferHandler();
            handler.exportAsDrag(c, e, TransferHandler.COPY);
        }
    };
    l.addMouseListener(myDragListener);

    propertyComboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ce) {
            JComboBox bx = (JComboBox) ce.getSource();
            String prop = (String) bx.getSelectedItem();
            setMyTransferHandlers(prop);
        }
    });

    tf.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            JTextField jtf = (JTextField) evt.getSource();
            String fontName = jtf.getText();
            Font font = new Font(fontName, Font.BOLD, 18);
            tf.setFont(font);
        }
    });

    stryder.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent evt) {
            JSlider sl = (JSlider) evt.getSource();
            Font oldf = tf.getFont();
            Font newf = oldf.deriveFont((float) sl.getValue());
            tf.setFont(newf);
        }
    });
}

From source file:Transfer.java

public Transfer() {

    // Establish the GUI
    Container cp = new Box(BoxLayout.X_AXIS);
    setContentPane(cp);/*from  ww  w  . j  a  v a  2s  .  c  om*/
    JPanel firstPanel = new JPanel();
    propertyComboBox = new JComboBox();
    propertyComboBox.addItem("text");
    propertyComboBox.addItem("font");
    propertyComboBox.addItem("background");
    propertyComboBox.addItem("foreground");
    firstPanel.add(propertyComboBox);
    cp.add(firstPanel);
    cp.add(Box.createGlue());

    tf = new JTextField("Hello");
    tf.setForeground(Color.RED);
    tf.setDragEnabled(true);
    cp.add(tf);

    cp.add(Box.createGlue());

    l = new JLabel("Hello");
    l.setBackground(Color.YELLOW);
    cp.add(l);

    cp.add(Box.createGlue());

    JSlider stryder = new JSlider(SwingConstants.VERTICAL);
    stryder.setMinimum(10);
    stryder.setValue(14);
    stryder.setMaximum(72);
    stryder.setMajorTickSpacing(10);
    stryder.setPaintTicks(true);

    cp.add(stryder);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500, 300);

    // Add Listeners and Converters
    setMyTransferHandlers((String) propertyComboBox.getSelectedItem());

    // Mousing in the Label starts a Drag.
    MouseListener myDragListener = new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            JComponent c = (JComponent) e.getSource();
            TransferHandler handler = c.getTransferHandler();
            handler.exportAsDrag(c, e, TransferHandler.COPY);
        }
    };
    l.addMouseListener(myDragListener);

    // Selecting in the ComboBox makes that the property that is xfered.
    propertyComboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ce) {
            JComboBox bx = (JComboBox) ce.getSource();
            String prop = (String) bx.getSelectedItem();
            setMyTransferHandlers(prop);
        }
    });

    // Typing a word and pressing enter in the TextField tries
    // to set that as the font name.
    tf.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            JTextField jtf = (JTextField) evt.getSource();
            String fontName = jtf.getText();
            Font font = new Font(fontName, Font.BOLD, 18);
            tf.setFont(font);
        }
    });

    // Setting the Slider sets that font into the textfield.
    stryder.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent evt) {
            JSlider sl = (JSlider) evt.getSource();
            Font oldf = tf.getFont();
            Font newf = oldf.deriveFont((float) sl.getValue());
            tf.setFont(newf);
        }
    });

}

From source file:components.ConversionPanel.java

ConversionPanel(Converter myController, String myTitle, Unit[] myUnits, ConverterRangeModel myModel) {
    if (MULTICOLORED) {
        setOpaque(true);/*from w ww . j  a  v a 2 s. c o  m*/
        setBackground(new Color(0, 255, 255));
    }
    setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(myTitle),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));

    //Save arguments in instance variables.
    controller = myController;
    units = myUnits;
    title = myTitle;
    sliderModel = myModel;

    //Create the text field format, and then the text field.
    numberFormat = NumberFormat.getNumberInstance();
    numberFormat.setMaximumFractionDigits(2);
    NumberFormatter formatter = new NumberFormatter(numberFormat);
    formatter.setAllowsInvalid(false);
    formatter.setCommitsOnValidEdit(true);//seems to be a no-op --
    //aha -- it changes the value property but doesn't cause the result to
    //be parsed (that happens on focus loss/return, I think).
    //
    textField = new JFormattedTextField(formatter);
    textField.setColumns(10);
    textField.setValue(new Double(sliderModel.getDoubleValue()));
    textField.addPropertyChangeListener(this);

    //Add the combo box.
    unitChooser = new JComboBox();
    for (int i = 0; i < units.length; i++) { //Populate it.
        unitChooser.addItem(units[i].description);
    }
    unitChooser.setSelectedIndex(0);
    sliderModel.setMultiplier(units[0].multiplier);
    unitChooser.addActionListener(this);

    //Add the slider.
    slider = new JSlider(sliderModel);
    sliderModel.addChangeListener(this);

    //Make the text field/slider group a fixed size
    //to make stacked ConversionPanels nicely aligned.
    JPanel unitGroup = new JPanel() {
        public Dimension getMinimumSize() {
            return getPreferredSize();
        }

        public Dimension getPreferredSize() {
            return new Dimension(150, super.getPreferredSize().height);
        }

        public Dimension getMaximumSize() {
            return getPreferredSize();
        }
    };
    unitGroup.setLayout(new BoxLayout(unitGroup, BoxLayout.PAGE_AXIS));
    if (MULTICOLORED) {
        unitGroup.setOpaque(true);
        unitGroup.setBackground(new Color(0, 0, 255));
    }
    unitGroup.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
    unitGroup.add(textField);
    unitGroup.add(slider);

    //Create a subpanel so the combo box isn't too tall
    //and is sufficiently wide.
    JPanel chooserPanel = new JPanel();
    chooserPanel.setLayout(new BoxLayout(chooserPanel, BoxLayout.PAGE_AXIS));
    if (MULTICOLORED) {
        chooserPanel.setOpaque(true);
        chooserPanel.setBackground(new Color(255, 0, 255));
    }
    chooserPanel.add(unitChooser);
    chooserPanel.add(Box.createHorizontalStrut(100));

    //Put everything together.
    setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
    add(unitGroup);
    add(chooserPanel);
    unitGroup.setAlignmentY(TOP_ALIGNMENT);
    chooserPanel.setAlignmentY(TOP_ALIGNMENT);
}

From source file:net.sf.jclal.gui.view.components.chart.ExternalBasicChart.java

/**
 *
 * @param windowsTitleParam The title of the window.
 * @param chartTitleParam The title of the chart panel.
 * @param xTitleParam The X-axis label.//from w w w  .  j a  v  a 2s .com
 */
public ExternalBasicChart(String windowsTitleParam, String chartTitleParam, String xTitleParam) {

    reportFrecuency = 1;

    menubar = new JMenuBar();
    menubar.add(createMenu());

    max = -1;

    windowsTitle = windowsTitleParam;
    chartTitle = chartTitleParam;
    xTitle = xTitleParam;

    queryNames = new ArrayList<String>();
    evaluationsCollection = new ArrayList<List<AbstractEvaluation>>();
    controlCurveColor = new HashMap<String, Color>();
    set = new HashSet<Integer>();
    setSeries = new HashSet<String>();
    colors = new ArrayList<Color>();

    chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new Dimension(640, 480));
    chartPanel.setFillZoomRectangle(true);
    chartPanel.setMouseWheelEnabled(true);

    slider = new JSlider(JSlider.HORIZONTAL);
    slider.setPaintTicks(true);
    slider.setPaintLabels(true);
    slider.setToolTipText("Changes the report frecuency");
    slider.setSnapToTicks(true);
    slider.setMinimum(1);
    slider.setMinorTickSpacing(1);

    slider.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(javax.swing.event.ChangeEvent evt) {

            reportFrecuency = ((JSlider) evt.getSource()).getValue();

            slider.setToolTipText(String.valueOf(reportFrecuency));

            jComboBoxItemStateChanged();
        }
    });

    comboBox = new JComboBox<String>();

    comboBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent evt) {

            jComboBoxItemStateChanged();
        }
    });

    content = new JPanel(new BorderLayout());
    content.add(comboBox, BorderLayout.NORTH);
    content.add(chartPanel, BorderLayout.CENTER);
    content.add(slider, BorderLayout.SOUTH);

    setJMenuBar(menubar);
    setTitle(windowsTitle);
    setContentPane(this.content);
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

}

From source file:au.edu.uwa.csse.plot.Clustering.java

private void setUpView(Graph graph) throws IOException {

    //Create a simple layout frame
    //specify the Fruchterman-Rheingold layout algorithm
    final AggregateLayout<Integer, Number> layout = new AggregateLayout<Integer, Number>(
            new FRLayout<Integer, Number>(graph));

    vv = new VisualizationViewer<Integer, Number>(layout);
    vv.setBackground(Color.white);
    vv.setVertexToolTipTransformer(Plot.vertexLabelTransformer);
    //Tell the renderer to use our own customized color rendering
    vv.getRenderContext()/*from   w w  w .j a v  a 2s  . co m*/
            .setVertexFillPaintTransformer(MapTransformer.<Integer, Paint>getInstance(vertexPaints));
    vv.getRenderContext().setVertexDrawPaintTransformer(new Transformer<Integer, Paint>() {
        public Paint transform(Integer v) {
            if (vv.getPickedVertexState().isPicked(v)) {
                return Color.cyan;
            } else {
                return Color.BLACK;
            }
        }
    });

    vv.getRenderContext().setEdgeDrawPaintTransformer(MapTransformer.<Number, Paint>getInstance(edgePaints));

    vv.getRenderContext().setEdgeStrokeTransformer(new Transformer<Number, Stroke>() {
        protected final Stroke THIN = new BasicStroke(1);
        protected final Stroke THICK = new BasicStroke(2);

        public Stroke transform(Number e) {
            Paint c = edgePaints.get(e);
            if (c == Color.LIGHT_GRAY)
                return THIN;
            else
                return THICK;
        }
    });

    //add restart button
    JButton scramble = new JButton("Restart");
    scramble.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Layout layout = vv.getGraphLayout();
            layout.initialize();
            Relaxer relaxer = vv.getModel().getRelaxer();
            if (relaxer != null) {
                relaxer.stop();
                relaxer.prerelax();
                relaxer.relax();
            }
        }

    });

    DefaultModalGraphMouse gm = new DefaultModalGraphMouse();
    vv.setGraphMouse(gm);

    final JToggleButton groupVertices = new JToggleButton("Group Clusters");

    //Create slider to adjust the number of edges to remove when clustering
    final JSlider edgeBetweennessSlider = new JSlider(JSlider.HORIZONTAL);
    edgeBetweennessSlider.setBackground(Color.WHITE);
    edgeBetweennessSlider.setPreferredSize(new Dimension(210, 50));
    edgeBetweennessSlider.setPaintTicks(true);
    edgeBetweennessSlider.setMaximum(graph.getEdgeCount());
    edgeBetweennessSlider.setMinimum(0);
    edgeBetweennessSlider.setValue(0);
    edgeBetweennessSlider.setMajorTickSpacing(10);
    edgeBetweennessSlider.setPaintLabels(true);
    edgeBetweennessSlider.setPaintTicks(true);

    //      edgeBetweennessSlider.setBorder(BorderFactory.createLineBorder(Color.black));
    //TO DO: edgeBetweennessSlider.add(new JLabel("Node Size (PageRank With Priors):"));
    //I also want the slider value to appear
    final JPanel eastControls = new JPanel();
    eastControls.setOpaque(true);
    eastControls.setLayout(new BoxLayout(eastControls, BoxLayout.Y_AXIS));
    eastControls.add(Box.createVerticalGlue());
    eastControls.add(edgeBetweennessSlider);

    final String COMMANDSTRING = "Edges removed for clusters: ";
    final String eastSize = COMMANDSTRING + edgeBetweennessSlider.getValue();

    final TitledBorder sliderBorder = BorderFactory.createTitledBorder(eastSize);
    eastControls.setBorder(sliderBorder);
    //eastControls.add(eastSize);
    eastControls.add(Box.createVerticalGlue());

    groupVertices.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            clusterAndRecolor(layout, edgeBetweennessSlider.getValue(), similarColors,
                    e.getStateChange() == ItemEvent.SELECTED);
            vv.repaint();
        }
    });

    clusterAndRecolor(layout, 0, similarColors, groupVertices.isSelected());

    edgeBetweennessSlider.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            JSlider source = (JSlider) e.getSource();
            if (!source.getValueIsAdjusting()) {
                int numEdgesToRemove = source.getValue();
                clusterAndRecolor(layout, numEdgesToRemove, similarColors, groupVertices.isSelected());
                sliderBorder.setTitle(COMMANDSTRING + edgeBetweennessSlider.getValue());
                eastControls.repaint();
                vv.validate();
                vv.repaint();
            }
        }
    });

    Container content = getContentPane();
    content.add(new GraphZoomScrollPane(vv));
    JPanel south = new JPanel();
    JPanel grid = new JPanel(new GridLayout(2, 1));
    grid.add(scramble);
    grid.add(groupVertices);
    south.add(grid);
    south.add(eastControls);
    JPanel p = new JPanel();
    p.setBorder(BorderFactory.createTitledBorder("Mouse Mode"));
    p.add(gm.getModeComboBox());
    south.add(p);
    content.add(south, BorderLayout.SOUTH);
}

From source file:geovista.network.gui.ClusteringDemo.java

private void setUpView() throws IOException {

    /*/*from   w w w.j  av  a  2  s.c o  m*/
     * Factory<Integer> vertexFactory = new Factory<Integer>() { int n = 0;
     * public Integer create() { return n++; } }; Factory<Number>
     * edgeFactory = new Factory<Number>() { int n = 0; public Number
     * create() { return n++; } };
     */

    /*
     * PajekNetReader<Graph<Integer, Number>, Integer,Number> pnr = new
     * PajekNetReader<Graph<Integer, Number>, Integer,Number>(vertexFactory,
     * edgeFactory);
     * 
     * final Graph<Integer,Number> graph = new SparseMultigraph<Integer,
     * Number>();
     * 
     * pnr.load(br, graph);
     */

    // Create a simple layout frame
    // specify the Fruchterman-Rheingold layout algorithm
    layout = new AggregateLayout<Integer, Number>(new FRLayout<Integer, Number>(g));

    vv = new VisualizationViewer<Integer, Number>(layout);
    vv.setBackground(Color.white);
    // Tell the renderer to use our own customized color rendering
    vv.getRenderContext()
            .setVertexFillPaintTransformer(MapTransformer.<Integer, Paint>getInstance(vertexPaints));
    vv.getRenderContext().setVertexDrawPaintTransformer(new Transformer<Integer, Paint>() {
        public Paint transform(Integer v) {
            if (vv.getPickedVertexState().isPicked(v)) {
                return Color.blue;
            } else {
                return Color.BLACK;
            }
        }
    });

    vv.getRenderContext().setEdgeDrawPaintTransformer(MapTransformer.<Number, Paint>getInstance(edgePaints));

    vv.getRenderContext().setEdgeStrokeTransformer(new Transformer<Number, Stroke>() {
        protected final Stroke THIN = new BasicStroke(1);
        protected final Stroke THICK = new BasicStroke(2);

        public Stroke transform(Number e) {
            Paint c = edgePaints.get(e);
            if (c == Color.LIGHT_GRAY) {
                return THIN;
            } else {
                return THICK;
            }
        }
    });

    /*
     * //add restart button JButton scramble = new JButton("Restart");
     * scramble.addActionListener(new ActionListener() { public void
     * actionPerformed(ActionEvent arg0) { Layout layout =
     * vv.getGraphLayout(); layout.initialize(); Relaxer relaxer =
     * vv.getModel().getRelaxer(); if(relaxer != null) { relaxer.stop();
     * relaxer.prerelax(); relaxer.relax(); } }
     * 
     * });
     * 
     * DefaultModalGraphMouse gm = new DefaultModalGraphMouse();
     * vv.setGraphMouse(gm);
     */

    final JToggleButton groupVertices = new JToggleButton("Group Clusters");

    // Create slider to adjust the number of edges to remove when clustering
    final JSlider edgeBetweennessSlider = new JSlider(JSlider.HORIZONTAL);
    edgeBetweennessSlider.setBackground(Color.WHITE);
    edgeBetweennessSlider.setPreferredSize(new Dimension(210, 50));
    edgeBetweennessSlider.setPaintTicks(true);
    edgeBetweennessSlider.setMaximum(g.getEdgeCount());
    edgeBetweennessSlider.setMinimum(0);
    edgeBetweennessSlider.setValue(0);
    edgeBetweennessSlider.setMajorTickSpacing(10);
    edgeBetweennessSlider.setPaintLabels(true);
    edgeBetweennessSlider.setPaintTicks(true);

    // edgeBetweennessSlider.setBorder(BorderFactory.createLineBorder(Color.black));
    // TO DO: edgeBetweennessSlider.add(new
    // JLabel("Node Size (PageRank With Priors):"));
    // I also want the slider value to appear
    final JPanel eastControls = new JPanel();
    /*
     * eastControls.setOpaque(true); eastControls.setLayout(new
     * BoxLayout(eastControls, BoxLayout.Y_AXIS));
     * eastControls.add(Box.createVerticalGlue());
     */
    // eastControls.add(edgeBetweennessSlider);

    final Box cluster_panel = Box.createVerticalBox();
    cluster_panel.setBorder(BorderFactory.createTitledBorder("Cluster"));
    cluster_panel.add(edgeBetweennessSlider);

    final String COMMANDSTRING = "Edges removed for clusters: ";
    final String eastSize = COMMANDSTRING + edgeBetweennessSlider.getValue();

    final TitledBorder sliderBorder = BorderFactory.createTitledBorder(eastSize);
    /*
     * eastControls.setBorder(sliderBorder); //eastControls.add(eastSize);
     * eastControls.add(Box.createVerticalGlue());
     */

    groupVertices.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            clusterAndRecolor(layout, edgeBetweennessSlider.getValue(), similarColors,
                    e.getStateChange() == ItemEvent.SELECTED);
            vv.repaint();
        }
    });

    clusterAndRecolor(layout, 0, similarColors, groupVertices.isSelected());

    edgeBetweennessSlider.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            JSlider source = (JSlider) e.getSource();
            if (!source.getValueIsAdjusting()) {
                int numEdgesToRemove = source.getValue();
                clusterAndRecolor(layout, numEdgesToRemove, similarColors, groupVertices.isSelected());
                sliderBorder.setTitle(COMMANDSTRING + edgeBetweennessSlider.getValue());
                eastControls.repaint();
                vv.validate();
                vv.repaint();
            }
        }
    });

    cluster_panel.add(groupVertices);
    Container content = getContentPane();
    content.add(new GraphZoomScrollPane(vv));
    JPanel south = new JPanel();
    JPanel grid = new JPanel(new GridLayout(2, 1));
    // grid.add(scramble);
    grid.add(cluster_panel);
    // south.add
    south.add(grid);
    south.add(eastControls);
    JPanel p = new JPanel();
    // p.setBorder(BorderFactory.createTitledBorder("Mouse Mode"));
    // p.add(gm.getModeComboBox());
    south.add(p);

    content.add(south, BorderLayout.SOUTH);
}

From source file:EdgeLabelDemo.java

/**
 * create an instance of a simple graph with controls to
 * demo the label positioning features//from   ww w.  j av  a2s  .  co  m
 * 
 */
@SuppressWarnings("serial")
public EdgeLabelDemo() {

    // create a simple graph for the demo
    graph = new SparseMultigraph<Integer, Number>();
    Integer[] v = createVertices(3);
    createEdges(v);

    Layout<Integer, Number> layout = new CircleLayout<Integer, Number>(graph);
    vv = new VisualizationViewer<Integer, Number>(layout, new Dimension(600, 400));
    vv.setBackground(Color.white);

    vertexLabelRenderer = vv.getRenderContext().getVertexLabelRenderer();
    edgeLabelRenderer = vv.getRenderContext().getEdgeLabelRenderer();

    Transformer<Number, String> stringer = new Transformer<Number, String>() {
        public String transform(Number e) {
            return "Edge:" + graph.getEndpoints(e).toString();
        }
    };
    vv.getRenderContext().setEdgeLabelTransformer(stringer);
    vv.getRenderContext().setEdgeDrawPaintTransformer(
            new PickableEdgePaintTransformer<Number>(vv.getPickedEdgeState(), Color.black, Color.cyan));
    vv.getRenderContext().setVertexFillPaintTransformer(
            new PickableVertexPaintTransformer<Integer>(vv.getPickedVertexState(), Color.red, Color.yellow));
    // add my listener for ToolTips
    vv.setVertexToolTipTransformer(new ToStringLabeller<Integer>());

    // create a frome to hold the graph
    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    Container content = getContentPane();
    content.add(panel);

    final DefaultModalGraphMouse<Integer, Number> graphMouse = new DefaultModalGraphMouse<Integer, Number>();
    vv.setGraphMouse(graphMouse);

    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());
        }
    });

    ButtonGroup radio = new ButtonGroup();
    JRadioButton lineButton = new JRadioButton("Line");
    lineButton.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line<Integer, Number>());
                vv.repaint();
            }
        }
    });

    JRadioButton quadButton = new JRadioButton("QuadCurve");
    quadButton.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.QuadCurve<Integer, Number>());
                vv.repaint();
            }
        }
    });

    JRadioButton cubicButton = new JRadioButton("CubicCurve");
    cubicButton.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.CubicCurve<Integer, Number>());
                vv.repaint();
            }
        }
    });
    radio.add(lineButton);
    radio.add(quadButton);
    radio.add(cubicButton);

    graphMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING);

    JCheckBox rotate = new JCheckBox("<html><center>EdgeType<p>Parallel</center></html>");
    rotate.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            AbstractButton b = (AbstractButton) e.getSource();
            edgeLabelRenderer.setRotateEdgeLabels(b.isSelected());
            vv.repaint();
        }
    });
    rotate.setSelected(true);
    MutableDirectionalEdgeValue mv = new MutableDirectionalEdgeValue(.5, .7);
    vv.getRenderContext().setEdgeLabelClosenessTransformer(mv);
    JSlider directedSlider = new JSlider(mv.getDirectedModel()) {
        public Dimension getPreferredSize() {
            Dimension d = super.getPreferredSize();
            d.width /= 2;
            return d;
        }
    };
    JSlider undirectedSlider = new JSlider(mv.getUndirectedModel()) {
        public Dimension getPreferredSize() {
            Dimension d = super.getPreferredSize();
            d.width /= 2;
            return d;
        }
    };

    JSlider edgeOffsetSlider = new JSlider(0, 50) {
        public Dimension getPreferredSize() {
            Dimension d = super.getPreferredSize();
            d.width /= 2;
            return d;
        }
    };
    edgeOffsetSlider.addChangeListener(new ChangeListener() {

        public void stateChanged(ChangeEvent e) {
            JSlider s = (JSlider) e.getSource();
            AbstractEdgeShapeTransformer<Integer, Number> aesf = (AbstractEdgeShapeTransformer<Integer, Number>) vv
                    .getRenderContext().getEdgeShapeTransformer();
            aesf.setControlOffsetIncrement(s.getValue());
            vv.repaint();
        }

    });

    Box controls = Box.createHorizontalBox();

    JPanel zoomPanel = new JPanel(new GridLayout(0, 1));
    zoomPanel.setBorder(BorderFactory.createTitledBorder("Scale"));
    zoomPanel.add(plus);
    zoomPanel.add(minus);

    JPanel edgePanel = new JPanel(new GridLayout(0, 1));
    edgePanel.setBorder(BorderFactory.createTitledBorder("EdgeType Type"));
    edgePanel.add(lineButton);
    edgePanel.add(quadButton);
    edgePanel.add(cubicButton);

    JPanel rotatePanel = new JPanel();
    rotatePanel.setBorder(BorderFactory.createTitledBorder("Alignment"));
    rotatePanel.add(rotate);

    JPanel labelPanel = new JPanel(new BorderLayout());
    JPanel sliderPanel = new JPanel(new GridLayout(3, 1));
    JPanel sliderLabelPanel = new JPanel(new GridLayout(3, 1));
    JPanel offsetPanel = new JPanel(new BorderLayout());
    offsetPanel.setBorder(BorderFactory.createTitledBorder("Offset"));
    sliderPanel.add(directedSlider);
    sliderPanel.add(undirectedSlider);
    sliderPanel.add(edgeOffsetSlider);
    sliderLabelPanel.add(new JLabel("Directed", JLabel.RIGHT));
    sliderLabelPanel.add(new JLabel("Undirected", JLabel.RIGHT));
    sliderLabelPanel.add(new JLabel("Edges", JLabel.RIGHT));
    offsetPanel.add(sliderLabelPanel, BorderLayout.WEST);
    offsetPanel.add(sliderPanel);
    labelPanel.add(offsetPanel);
    labelPanel.add(rotatePanel, BorderLayout.WEST);

    JPanel modePanel = new JPanel(new GridLayout(2, 1));
    modePanel.setBorder(BorderFactory.createTitledBorder("Mouse Mode"));
    modePanel.add(graphMouse.getModeComboBox());

    controls.add(zoomPanel);
    controls.add(edgePanel);
    controls.add(labelPanel);
    controls.add(modePanel);
    content.add(controls, BorderLayout.SOUTH);
    quadButton.setSelected(true);
}