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(int min, int max, int value) 

Source Link

Document

Creates a horizontal slider using the specified min, max and value.

Usage

From source file:biomine.bmvis2.pipeline.BestPathHiderOperation.java

public JComponent getSettingsComponent(final SettingsChangeCallback settingsChangeCallback,
        final VisualGraph graph) {
    long nodeCount = graph.getAllNodes().size();

    if (oldCount != 0) {
        long newTarget = (target * nodeCount) / oldCount;
        this.target = Math.max(newTarget, target);
    } else/*from   ww w.j  a  v a 2 s  .c  om*/
        this.target = nodeCount;

    this.oldCount = nodeCount;

    JPanel ret = new JPanel();

    // if int overflows, we're fucked
    final JSlider sl = new JSlider(0, (int) nodeCount, (int) Math.min(target, nodeCount));
    sl.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent arg0) {
            if (target == sl.getValue())
                return;
            target = sl.getValue();
            settingsChangeCallback.settingsChanged(false);
        }
    });

    ret.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.weightx = 1;
    c.weighty = 0;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    //c.gridwidth=2;

    ret.add(sl, c);
    c.gridy++;

    int choices = graph.getNodesOfInterest().size() + 1;

    Object[] items = new Object[choices];
    items[0] = "All PoIs";

    for (int i = 1; i < choices; i++) {
        items[i] = i + " nearest";
    }
    final JComboBox pathTypeBox = new JComboBox(items);
    pathTypeBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            int i = pathTypeBox.getSelectedIndex();
            grader.setPathK(i);
            settingsChangeCallback.settingsChanged(false);
        }
    });

    ret.add(new JLabel("hide by best path quality to:"), c);
    c.gridy++;
    ret.add(pathTypeBox, c);
    c.gridy++;

    System.out.println("new confpane nodeCount = " + nodeCount);

    final JCheckBox useMatchingColoring = new JCheckBox();
    ret.add(useMatchingColoring, c);

    useMatchingColoring.setAction(new AbstractAction("Use matching coloring") {
        public void actionPerformed(ActionEvent arg0) {
            matchColoring = useMatchingColoring.isSelected();
            settingsChangeCallback.settingsChanged(false);
        }
    });

    useMatchingColoring.setAlignmentX(JComponent.CENTER_ALIGNMENT);

    c.gridy++;

    final JCheckBox labelsBox = new JCheckBox();
    ret.add(labelsBox, c);

    labelsBox.setAction(new AbstractAction("Show goodness in node labels") {
        public void actionPerformed(ActionEvent arg0) {
            showLabel = labelsBox.isSelected();
            settingsChangeCallback.settingsChanged(false);
        }
    });

    return ret;
}

From source file:biomine.bmvis2.pipeline.EdgeSimplificationOperation.java

public JComponent getSettingsComponent(final SettingsChangeCallback settingsChangeCallback, VisualGraph graph) {
    this.graph = graph;
    int edgeCount = SimplificationUtils.countNormalEdges(graph);

    if (oldEdgeCount != 0) {
        long newTarget = (this.target * edgeCount) / this.oldEdgeCount;
        if (newTarget != this.target) {
            this.target = Math.max(newTarget, this.target);
            Logging.info("simplifier", "New edge count target: " + this.target);
        }/*ww  w. j a  va2s .c o m*/
    } else
        this.target = edgeCount;

    this.oldEdgeCount = edgeCount;

    JPanel ret = new JPanel();
    final JSlider sl = new JSlider(0, edgeCount, (int) Math.min(target, edgeCount));
    sl.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent arg0) {
            if (target == sl.getValue())
                return;
            target = sl.getValue();

            if (EdgeSimplificationOperation.this.getGraph() == null)
                settingsChangeCallback.settingsChanged(false);
            else
                EdgeSimplificationOperation.this.hideHidables(EdgeSimplificationOperation.this.getGraph());
        }
    });
    ret.setLayout(new BoxLayout(ret, BoxLayout.Y_AXIS));
    ret.add(sl);

    ret.add(costLabel);
    return ret;
}

From source file:ImageOpByRomain.java

private void buildControlsPanel() {
    JPanel controls = new JPanel(new GridBagLayout());

    // red component
    controls.add(new JLabel("Red: 0"), new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.LINE_END,
            GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
    controls.add(redSlider = new JSlider(0, 255, 255), new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0,
            GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    controls.add(new JLabel("255"), new GridBagConstraints(2, 0, 1, 1, 1.0, 1.0, GridBagConstraints.LINE_START,
            GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));

    // green component
    controls.add(new JLabel("Green: 0"), new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0,
            GridBagConstraints.LINE_END, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
    controls.add(greenSlider = new JSlider(0, 255, 255), new GridBagConstraints(1, 1, 1, 1, 1.0, 1.0,
            GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    controls.add(new JLabel("255"), new GridBagConstraints(2, 1, 1, 1, 1.0, 1.0, GridBagConstraints.LINE_START,
            GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));

    // blue component
    controls.add(new JLabel("Blue: 0"), new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0,
            GridBagConstraints.LINE_END, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
    controls.add(blueSlider = new JSlider(0, 255, 255), new GridBagConstraints(1, 2, 1, 1, 1.0, 1.0,
            GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    controls.add(new JLabel("255"), new GridBagConstraints(2, 2, 1, 1, 1.0, 1.0, GridBagConstraints.LINE_START,
            GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));

    // mix value//w  w w .jav  a 2  s  .c o m
    controls.add(new JLabel("Mix: 0%"), new GridBagConstraints(0, 3, 1, 1, 1.0, 1.0,
            GridBagConstraints.LINE_END, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
    controls.add(alphaSlider = new JSlider(0, 100, 50), new GridBagConstraints(1, 3, 1, 1, 1.0, 1.0,
            GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    controls.add(new JLabel("100%"), new GridBagConstraints(2, 3, 1, 1, 1.0, 1.0, GridBagConstraints.LINE_START,
            GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));

    // change listener
    ChangeListener colorChange = new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            imagePanel.setColor(new Color(redSlider.getValue(), greenSlider.getValue(), blueSlider.getValue()));
        }
    };
    redSlider.addChangeListener(colorChange);
    greenSlider.addChangeListener(colorChange);
    blueSlider.addChangeListener(colorChange);

    // alpha listener
    alphaSlider.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            imagePanel.setMix((float) alphaSlider.getValue() / 100.0f);
        }
    });

    add(controls, BorderLayout.SOUTH);
}

From source file:biomine.bmvis2.pipeline.RepresentiveHighlightOperation.java

public JComponent getSettingsComponent(final SettingsChangeCallback v, VisualGraph graph) {
    final JSlider slider = new JSlider(0, graph.getRootNode().getDescendants().size(), 0);
    slider.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent arg0) {
            numberOfNodes = slider.getValue();
            v.settingsChanged(false);//from www . j  a v  a2  s .  co  m
        }
    });
    return slider;
}

From source file:com.moteiv.trawler.Trawler.java

protected Box getControls() {
    java.util.Dictionary labels;/*from   www .  jav  a 2 s  . c  o m*/
    if (controls == null) {
        controls = Box.createVerticalBox();
        JPanel runtimeControls = new JPanel(new GridLayout(0, 1));
        runtimeControls.setBorder(BorderFactory.createTitledBorder("Runtime Controls"));

        vLog = new JCheckBox("Log packets", false);
        vLog.addActionListener(this);
        runtimeControls.add(vLog);
        runtimeControls.add(new JLabel("Edge persistence (sec)", JLabel.LEFT));
        eDispose = new JSlider(0, 300, 10);
        eDispose.setMajorTickSpacing(100);
        eDispose.setMinorTickSpacing(10);
        eDispose.setPaintTicks(true);
        eDispose.setPaintTrack(true);
        //       labels = eDispose.getLabelTable();

        eDispose.setPaintLabels(true);
        eDispose.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                LinkData.setEdgeDelay((1 + eDispose.getValue()) * 1000);
                savePrefs();
            }
        });
        runtimeControls.add(eDispose);
        runtimeControls.add(new JLabel("Vertex persistence (sec)", JLabel.LEFT));
        vDispose = new JSlider(0, 300, 30);
        vDispose.setMajorTickSpacing(100);
        vDispose.setMinorTickSpacing(10);
        vDispose.setPaintTicks(true);
        vDispose.setPaintTrack(true);
        vDispose.setPaintLabels(true);
        vDispose.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                NodeData.setNodeDelay((1 + vDispose.getValue()) * 1000);
                savePrefs();
            }
        });
        runtimeControls.add(vDispose);
        graphReset = new JButton("Reset Nodes");
        graphReset.addActionListener(this);
        runtimeControls.add(graphReset);
        controls.add(runtimeControls);

        JPanel vertexControl = new JPanel(new GridLayout(0, 1));
        vertexControl.setBorder(BorderFactory.createTitledBorder("Node display"));
        vLabels = new JCheckBox("Display vertex details", true);
        vLabels.addActionListener(this);

        vertexControl.add(vLabels);
        vBlink = new JCheckBox("Blink on incoming packets");
        vBlink.addActionListener(this);
        vertexControl.add(vBlink);
        vSave = new JCheckBox("Save node locations", true);
        vSave.addActionListener(this);
        vertexControl.add(vSave);
        controls.add(vertexControl);
        JPanel edgeControl = new JPanel(new GridLayout(0, 1));
        edgeControl.setBorder(BorderFactory.createTitledBorder("Link diplay"));
        eLabels = new JCheckBox("Display link quality", true);
        eLabels.addActionListener(this);
        edgeControl.add(eLabels);
        eFilter = new JCheckBox("Show alternate parents", true);
        eFilter.addActionListener(this);
        edgeControl.add(eFilter);
        controls.add(edgeControl);
    }
    return controls;
}

From source file:edu.uci.ics.jung.samples.PerspectiveTransformerDemo.java

/**
 * create an instance of a simple graph with controls to
 * demo the zoom and perspective features.
 * /*from   ww w.j a va2  s  .c o m*/
 */
@SuppressWarnings("serial")
public PerspectiveTransformerDemo() {

    // create a simple graph for the demo
    graph = TestGraphs.getOneComponentGraph();

    graphLayout = new FRLayout<String, Number>(graph);
    ((FRLayout<String, Number>) graphLayout).setMaxIterations(1000);

    Dimension preferredSize = new Dimension(600, 600);
    Map<String, Point2D> map = new HashMap<String, Point2D>();
    Transformer<String, Point2D> vlf = TransformerUtils.mapTransformer(map);
    grid = this.generateVertexGrid(map, preferredSize, 25);
    gridLayout = new StaticLayout<String, Number>(grid, vlf, preferredSize);

    final VisualizationModel<String, Number> visualizationModel = new DefaultVisualizationModel<String, Number>(
            graphLayout, preferredSize);
    vv = new VisualizationViewer<String, Number>(visualizationModel, preferredSize);
    PickedState<Number> pes = vv.getPickedEdgeState();
    vv.getRenderContext()
            .setEdgeDrawPaintTransformer(new PickableEdgePaintTransformer<Number>(pes, Color.black, Color.red));
    vv.getRenderContext().setVertexShapeTransformer(new Transformer<String, Shape>() {

        public Shape transform(String v) {
            return new Rectangle2D.Float(-10, -10, 20, 20);
        }
    });
    vv.setBackground(Color.white);

    // add a listener for ToolTips
    vv.setVertexToolTipTransformer(new ToStringLabeller<String>());

    Container content = getContentPane();
    GraphZoomScrollPane gzsp = new GraphZoomScrollPane(vv);
    content.add(gzsp);

    /**
     * the regular graph mouse for the normal view
     */
    final DefaultModalGraphMouse<Number, Number> graphMouse = new DefaultModalGraphMouse<Number, Number>();

    vv.setGraphMouse(graphMouse);

    viewSupport = new PerspectiveViewTransformSupport<String, Number>(vv);
    layoutSupport = new PerspectiveLayoutTransformSupport<String, Number>(vv);

    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, 0.9f, vv.getCenter());
        }
    });
    final JSlider horizontalSlider = new JSlider(-120, 120, 0) {

        /* (non-Javadoc)
         * @see javax.swing.JComponent#getPreferredSize()
         */
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(80, super.getPreferredSize().height);
        }
    };

    final JSlider verticalSlider = new JSlider(-120, 120, 0) {

        /* (non-Javadoc)
         * @see javax.swing.JComponent#getPreferredSize()
         */
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(super.getPreferredSize().width, 80);
        }
    };
    verticalSlider.setOrientation(JSlider.VERTICAL);
    final ChangeListener changeListener = new ChangeListener() {

        public void stateChanged(ChangeEvent e) {
            int vval = -verticalSlider.getValue();
            int hval = horizontalSlider.getValue();

            Dimension d = vv.getSize();
            PerspectiveTransform pt = null;
            pt = PerspectiveTransform.getQuadToQuad(vval, hval, d.width - vval, -hval, d.width + vval,
                    d.height + hval, -vval, d.height - hval,

                    0, 0, d.width, 0, d.width, d.height, 0, d.height);

            viewSupport.getPerspectiveTransformer().setPerspectiveTransform(pt);
            layoutSupport.getPerspectiveTransformer().setPerspectiveTransform(pt);
            vv.repaint();
        }
    };
    horizontalSlider.addChangeListener(changeListener);
    verticalSlider.addChangeListener(changeListener);

    JPanel perspectivePanel = new JPanel(new BorderLayout());
    JPanel perspectiveCenterPanel = new JPanel(new BorderLayout());
    perspectivePanel.setBorder(BorderFactory.createTitledBorder("Perspective Controls"));
    final JButton center = new JButton("Center");
    center.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            horizontalSlider.setValue(0);
            verticalSlider.setValue(0);
        }
    });
    ButtonGroup radio = new ButtonGroup();
    JRadioButton normal = new JRadioButton("None");
    normal.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            boolean selected = e.getStateChange() == ItemEvent.SELECTED;
            if (selected) {
                if (viewSupport != null) {
                    viewSupport.deactivate();
                }
                if (layoutSupport != null) {
                    layoutSupport.deactivate();
                }
            }
            center.setEnabled(!selected);
            horizontalSlider.setEnabled(!selected);
            verticalSlider.setEnabled(!selected);
        }
    });

    final JRadioButton perspectiveView = new JRadioButton("In View");
    perspectiveView.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            viewSupport.activate(e.getStateChange() == ItemEvent.SELECTED);
        }
    });
    final JRadioButton perspectiveModel = new JRadioButton("In Layout");
    perspectiveModel.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            layoutSupport.activate(e.getStateChange() == ItemEvent.SELECTED);
        }
    });

    radio.add(normal);
    radio.add(perspectiveModel);
    radio.add(perspectiveView);
    normal.setSelected(true);

    ButtonGroup graphRadio = new ButtonGroup();
    JRadioButton graphButton = new JRadioButton("Graph");
    graphButton.setSelected(true);
    graphButton.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                visualizationModel.setGraphLayout(graphLayout);
                vv.repaint();
            }
        }
    });
    JRadioButton gridButton = new JRadioButton("Grid");
    gridButton.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                visualizationModel.setGraphLayout(gridLayout);
                vv.repaint();
            }
        }
    });
    graphRadio.add(graphButton);
    graphRadio.add(gridButton);

    JPanel modePanel = new JPanel(new GridLayout(2, 1));
    modePanel.setBorder(BorderFactory.createTitledBorder("Display"));
    modePanel.add(graphButton);
    modePanel.add(gridButton);

    JMenuBar menubar = new JMenuBar();
    menubar.add(graphMouse.getModeMenu());
    gzsp.setCorner(menubar);

    Container controls = new JPanel(new BorderLayout());
    JPanel zoomControls = new JPanel(new GridLayout(2, 1));
    zoomControls.setBorder(BorderFactory.createTitledBorder("Zoom"));
    JPanel perspectiveControls = new JPanel(new GridLayout(3, 1));
    zoomControls.add(plus);
    zoomControls.add(minus);
    perspectiveControls.add(normal);
    perspectiveControls.add(perspectiveModel);
    perspectiveControls.add(perspectiveView);

    controls.add(zoomControls, BorderLayout.WEST);
    controls.add(modePanel);
    perspectivePanel.add(perspectiveControls, BorderLayout.WEST);
    perspectiveCenterPanel.add(horizontalSlider, BorderLayout.SOUTH);
    perspectivePanel.add(verticalSlider, BorderLayout.EAST);
    perspectiveCenterPanel.add(center);
    perspectivePanel.add(perspectiveCenterPanel);
    controls.add(perspectivePanel, BorderLayout.EAST);

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

From source file:Presentation.MainWindow.java

private void addSlider() {
    JSlider sliderTemp = new JSlider(12, 26, 26);
    sliderTemp.setLabelTable(sliderTemp.createStandardLabels(14));
    sliderTemp.setMinorTickSpacing(1);/*ww  w. ja  v a 2 s.  co  m*/
    sliderTemp.setPaintLabels(true);
    sliderTemp.setPaintTicks(true);
    this.tSlider = sliderTemp;
    Label labelConsigne = new Label("Temprature de consigne : " + tSlider.getValue() + " C");
    //Label labelOutdoorTemp = new Label(Singleton.getInstance().getAcquisition().getOutdoorTemp());
    this.tLabel = labelConsigne;
    mPanel.add(labelConsigne);
    mPanel.add(sliderTemp);
}

From source file:SoundPlayer.java

public SoundPlayer(File f, boolean isMidi) throws IOException, UnsupportedAudioFileException,
        LineUnavailableException, MidiUnavailableException, InvalidMidiDataException {
    if (isMidi) { // The file is a MIDI file
        midi = true;/*w w w . j a  v a 2s .com*/
        // First, get a Sequencer to play sequences of MIDI events
        // That is, to send events to a Synthesizer at the right time.
        sequencer = MidiSystem.getSequencer(); // Used to play sequences
        sequencer.open(); // Turn it on.

        // Get a Synthesizer for the Sequencer to send notes to
        Synthesizer synth = MidiSystem.getSynthesizer();
        synth.open(); // acquire whatever resources it needs

        // The Sequencer obtained above may be connected to a Synthesizer
        // by default, or it may not. Therefore, we explicitly connect it.
        Transmitter transmitter = sequencer.getTransmitter();
        Receiver receiver = synth.getReceiver();
        transmitter.setReceiver(receiver);

        // Read the sequence from the file and tell the sequencer about it
        sequence = MidiSystem.getSequence(f);
        sequencer.setSequence(sequence);
        audioLength = (int) sequence.getTickLength(); // Get sequence length
    } else { // The file is sampled audio
        midi = false;
        // Getting a Clip object for a file of sampled audio data is kind
        // of cumbersome. The following lines do what we need.
        AudioInputStream ain = AudioSystem.getAudioInputStream(f);
        try {
            DataLine.Info info = new DataLine.Info(Clip.class, ain.getFormat());
            clip = (Clip) AudioSystem.getLine(info);
            clip.open(ain);
        } finally { // We're done with the input stream.
            ain.close();
        }
        // Get the clip length in microseconds and convert to milliseconds
        audioLength = (int) (clip.getMicrosecondLength() / 1000);
    }

    // Now create the basic GUI
    play = new JButton("Play"); // Play/stop button
    progress = new JSlider(0, audioLength, 0); // Shows position in sound
    time = new JLabel("0"); // Shows position as a #

    // When clicked, start or stop playing the sound
    play.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (playing)
                stop();
            else
                play();
        }
    });

    // Whenever the slider value changes, first update the time label.
    // Next, if we're not already at the new position, skip to it.
    progress.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            int value = progress.getValue();
            // Update the time label
            if (midi)
                time.setText(value + "");
            else
                time.setText(value / 1000 + "." + (value % 1000) / 100);
            // If we're not already there, skip there.
            if (value != audioPosition)
                skip(value);
        }
    });

    // This timer calls the tick() method 10 times a second to keep
    // our slider in sync with the music.
    timer = new javax.swing.Timer(100, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            tick();
        }
    });

    // put those controls in a row
    Box row = Box.createHorizontalBox();
    row.add(play);
    row.add(progress);
    row.add(time);

    // And add them to this component.
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    this.add(row);

    // Now add additional controls based on the type of the sound
    if (midi)
        addMidiControls();
    else
        addSampledControls();
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.diagnostics.ApproximationSetViewer.java

/**
 * Initializes this window.  This method is invoked in the constructor, and
 * should not be invoked again.//from w  ww  . java  2  s . c  o  m
 */
protected void initialize() {
    //initialize the NFE slider
    int minimumNFE = Integer.MAX_VALUE;
    int maximumNFE = Integer.MIN_VALUE;

    for (Accumulator accumulator : accumulators) {
        minimumNFE = Math.min(minimumNFE, (Integer) accumulator.get("NFE", 0));
        maximumNFE = Math.max(maximumNFE, (Integer) accumulator.get("NFE", accumulator.size("NFE") - 1));
    }

    slider = new JSlider(minimumNFE, maximumNFE, minimumNFE);
    slider.setPaintTicks(true);
    slider.setMinorTickSpacing(100);
    slider.setMajorTickSpacing(1000);
    slider.addChangeListener(this);

    //initializes the options available for axis plotting
    Solution solution = (Solution) ((List<?>) accumulators.get(0).get("Approximation Set", 0)).get(0);
    Vector<String> objectives = new Vector<String>();

    for (int i = 0; i < solution.getNumberOfObjectives(); i++) {
        objectives.add(localization.getString("text.objective", i + 1));
    }

    for (int i = 0; i < solution.getNumberOfConstraints(); i++) {
        objectives.add(localization.getString("text.constraint", i + 1));
    }

    for (int i = 0; i < solution.getNumberOfVariables(); i++) {
        objectives.add(localization.getString("text.variable", i + 1));
    }

    xAxisSelection = new JComboBox(objectives);
    yAxisSelection = new JComboBox(objectives);

    xAxisSelection.setSelectedIndex(0);
    yAxisSelection.setSelectedIndex(1);

    xAxisSelection.addActionListener(this);
    yAxisSelection.addActionListener(this);

    //initialize the reference set bounds
    initializeReferenceSetBounds();

    //initialize plotting controls
    useInitialBounds = new JRadioButton(localization.getString("action.useInitialBounds.name"));
    useReferenceSetBounds = new JRadioButton(localization.getString("action.useReferenceSetBounds.name"));
    useDynamicBounds = new JRadioButton(localization.getString("action.useDynamicBounds.name"));
    useZoomBounds = new JRadioButton(localization.getString("action.useZoom.name"));

    useInitialBounds.setToolTipText(localization.getString("action.useInitialBounds.description"));
    useReferenceSetBounds.setToolTipText(localization.getString("action.useReferenceSetBounds.description"));
    useDynamicBounds.setToolTipText(localization.getString("action.useDynamicBounds.description"));
    useZoomBounds.setToolTipText(localization.getString("action.useZoom.description"));

    ButtonGroup rangeButtonGroup = new ButtonGroup();
    rangeButtonGroup.add(useInitialBounds);
    rangeButtonGroup.add(useReferenceSetBounds);
    rangeButtonGroup.add(useDynamicBounds);
    rangeButtonGroup.add(useZoomBounds);

    if (referenceSet == null) {
        useReferenceSetBounds.setEnabled(false);
    }

    useInitialBounds.setSelected(true);
    useInitialBounds.addActionListener(this);
    useReferenceSetBounds.addActionListener(this);
    useDynamicBounds.addActionListener(this);
    useZoomBounds.addActionListener(this);

    //initialize the seed list
    String[] seeds = new String[accumulators.size()];

    for (int i = 0; i < accumulators.size(); i++) {
        seeds[i] = localization.getString("text.seed", i + 1);
    }

    seedList = new JList(seeds);
    seedList.addListSelectionListener(this);

    selectAll = new JButton(new AbstractAction() {

        private static final long serialVersionUID = -3709557130361259485L;

        {
            putValue(Action.NAME, localization.getString("action.selectAll.name"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            seedList.getSelectionModel().setSelectionInterval(0, seedList.getModel().getSize() - 1);
        }

    });

    //initialize miscellaneous components
    paintHelper = new PaintHelper();
    paintHelper.set(localization.getString("text.referenceSet"), Color.BLACK);

    chartContainer = new JPanel(new BorderLayout());
}

From source file:at.tuwien.ifs.somtoolbox.apps.viewer.controls.ClusteringControl.java

public void init() {

    maxCluster = state.growingLayer.getXSize() * state.growingLayer.getYSize();

    spinnerNoCluster = new JSpinner(new SpinnerNumberModel(1, 1, maxCluster, 1));
    spinnerNoCluster.addChangeListener(new ChangeListener() {
        @Override//from   w w  w  . j ava2  s . c  o m
        public void stateChanged(ChangeEvent e) {
            numClusters = (Integer) ((JSpinner) e.getSource()).getValue();
            SortedMap<Integer, ClusterElementsStorage> m = mapPane.getMap().getCurrentClusteringTree()
                    .getAllClusteringElements();
            if (m.containsKey(numClusters)) {
                st = m.get(numClusters).sticky;
            } else {
                st = false;
            }
            sticky.setSelected(st);
            redrawClustering();
        }
    });

    JPanel clusterPanel = UiUtils.makeBorderedPanel(new FlowLayout(FlowLayout.LEFT, 10, 0), "Clusters");

    sticky.setToolTipText(
            "Marks this number of clusters as sticky for a certain leve; the next set of clusters will have a smaller boundary");
    sticky.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            st = sticky.isSelected();
            SortedMap<Integer, ClusterElementsStorage> m = mapPane.getMap().getCurrentClusteringTree()
                    .getAllClusteringElements();
            if (m.containsKey(numClusters)) {
                ClusterElementsStorage c = m.get(numClusters);
                c.sticky = st;
                // System.out.println("test");
                // ((ClusterElementsStorageNode)m.get(numClusters)).sticky = st;
                redrawClustering();
            }
        }
    });

    colorCluster = new JCheckBox("colour", state.colorClusters);
    colorCluster.setToolTipText("Fill the clusters in colours");
    colorCluster.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            state.colorClusters = colorCluster.isSelected();
            // TODO: Palette anzeigen (?)
            redrawClustering();
        }
    });

    UiUtils.fillPanel(clusterPanel, new JLabel("#"), spinnerNoCluster, sticky, colorCluster);
    getContentPane().add(clusterPanel, c.nextRow());

    dendogramPanel = UiUtils.makeBorderedPanel(new GridLayout(0, 1), "Dendogram");
    getContentPane().add(dendogramPanel, c.nextRow());

    JPanel numLabelPanel = UiUtils.makeBorderedPanel(new GridBagLayout(), "Labels");
    GridBagConstraintsIFS gcLabels = new GridBagConstraintsIFS();

    labelSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 99, 1));
    labelSpinner.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            numLabels = (Integer) ((JSpinner) e.getSource()).getValue();
            state.clusterWithLabels = numLabels;
            redrawClustering();
        }
    });

    this.showValues = new JCheckBox("values", state.labelsWithValues);
    this.showValues.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            state.labelsWithValues = showValues.isSelected();
            redrawClustering();
        }
    });

    int start = new Double((1 - state.clusterByValue) * 100).intValue();
    valueQe = new JSlider(0, 100, start);
    valueQe.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            int byValue = ((JSlider) e.getSource()).getValue();
            state.clusterByValue = 1 - byValue / 100;
            redrawClustering();
        }
    });

    numLabelPanel.add(new JLabel("# Labels"), gcLabels);
    numLabelPanel.add(labelSpinner, gcLabels.nextCol());
    numLabelPanel.add(showValues, gcLabels.nextCol());
    numLabelPanel.add(valueQe, gcLabels.nextRow().setGridWidth(3).setFill(GridBagConstraints.HORIZONTAL));
    getContentPane().add(numLabelPanel, c.nextRow());

    Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
    labelTable.put(0, new JLabel("by Value"));
    labelTable.put(100, new JLabel("by Qe"));
    valueQe.setToolTipText("Method how to select representative labels - by QE, or the attribute values");
    valueQe.setLabelTable(labelTable);
    valueQe.setPaintLabels(true);

    final JComboBox initialisationBox = new JComboBox(KMeans.InitType.values());
    initialisationBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Object o = mapPane.getMap().getClusteringTreeBuilder();
            if (o instanceof KMeansTreeBuilder) {
                ((KMeansTreeBuilder) o).reInit((KMeans.InitType) initialisationBox.getSelectedItem());
                // FIXME: is this call needed?
                mapPane.getMap().getCurrentClusteringTree().getAllClusteringElements();
                redrawClustering();
            }
        }
    });

    getContentPane().add(UiUtils.fillPanel(kmeansInitialisationPanel, new JLabel("k-Means initialisation"),
            initialisationBox), c.nextRow());

    JPanel borderPanel = new TitledCollapsiblePanel("Border", new GridLayout(1, 4), true);

    JSpinner borderSpinner = new JSpinner(
            new SpinnerNumberModel(ClusteringTree.INITIAL_BORDER_WIDTH_MAGNIFICATION_FACTOR, 0.1, 5, 0.1));
    borderSpinner.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            state.clusterBorderWidthMagnificationFactor = ((Double) ((JSpinner) e.getSource()).getValue())
                    .floatValue();
            redrawClustering();
        }
    });

    borderPanel.add(new JLabel("width"));
    borderPanel.add(borderSpinner);

    borderPanel.add(new JLabel("colour"));
    buttonColour = new JButton("");
    buttonColour.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new ClusterBoderColorChooser(state.parentFrame, state.clusterBorderColour, ClusteringControl.this);
        }
    });
    buttonColour.setBackground(state.clusterBorderColour);
    borderPanel.add(buttonColour);

    getContentPane().add(borderPanel, c.nextRow());

    JPanel evaluationPanel = new TitledCollapsiblePanel("Cluster Evaluation", new GridLayout(3, 2), true);

    evaluationPanel.add(new JLabel("quality measure"));
    qualityMeasureButton = new JButton();
    qualityMeasureButton.setText("ent/pur calc");
    qualityMeasureButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("doing entropy here");
            ClusteringTree clusteringTree = state.mapPNode.getClusteringTree();
            if (clusteringTree == null) {
                // we have not clustered yet
                return;
            }
            // System.out.println(clusteringTree.getChildrenCount());

            // FIXME put this in a method and call it on numcluster.change()
            SOMLibClassInformation classInfo = state.inputDataObjects.getClassInfo();
            ArrayList<ClusterNode> clusters = clusteringTree.getNodesAtLevel(numClusters);
            System.out.println(clusters.size());
            // EntropyMeasure.computeEntropy(clusters, classInfo);
            EntropyAndPurityCalculator eapc = new EntropyAndPurityCalculator(clusters, classInfo);
            // FIXME round first
            entropyLabel.setText(String.valueOf(eapc.getEntropy()));
            purityLabel.setText(String.valueOf(eapc.getPurity()));

        }
    });
    evaluationPanel.add(qualityMeasureButton);
    GridBagConstraintsIFS gcEval = new GridBagConstraintsIFS();

    evaluationPanel.add(new JLabel("entropy"), gcEval);
    evaluationPanel.add(new JLabel("purity"), gcEval.nextCol());

    entropyLabel = new JLabel("n/a");
    purityLabel = new JLabel("n/a");

    evaluationPanel.add(entropyLabel, gcEval.nextRow());
    evaluationPanel.add(purityLabel, gcEval.nextCol());

    getContentPane().add(evaluationPanel, c.nextRow());

    JPanel panelButtons = new JPanel(new GridLayout(1, 4));

    JButton saveButton = new JButton("Save");
    saveButton.setFont(smallFont);
    saveButton.setMargin(SMALL_INSETS);
    saveButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser;
            if (state.fileChooser.getSelectedFile() != null) {
                fileChooser = new JFileChooser(state.fileChooser.getSelectedFile().getPath());
            } else {
                fileChooser = new JFileChooser();
            }
            fileChooser.addChoosableFileFilter(clusteringFilter);
            fileChooser.addChoosableFileFilter(xmlFilter);

            File filePath = ExportUtils.getFilePath(ClusteringControl.this, fileChooser,
                    "Save Clustering and Labels");

            if (filePath != null) {
                if (xmlFilter.accept(filePath)) {
                    LabelXmlUtils.saveLabelsToFile(state.mapPNode, filePath);
                } else {
                    try {
                        FileOutputStream fos = new FileOutputStream(filePath);
                        GZIPOutputStream gzipOs = new GZIPOutputStream(fos);
                        PObjectOutputStream oos = new PObjectOutputStream(gzipOs);

                        oos.writeObjectTree(mapPane.getMap().getCurrentClusteringTree());
                        oos.writeObjectTree(mapPane.getMap().getManualLabels());
                        oos.writeInt(state.clusterWithLabels);
                        oos.writeBoolean(state.labelsWithValues);
                        oos.writeDouble(state.clusterByValue);
                        oos.writeObject(spinnerNoCluster.getValue());

                        oos.close();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                // keep the selected path for future references
                state.fileChooser.setSelectedFile(filePath.getParentFile());
            }
        }
    });
    panelButtons.add(saveButton);

    JButton loadButton = new JButton("Load");
    loadButton.setFont(smallFont);
    loadButton.setMargin(SMALL_INSETS);
    loadButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = getFileChooser();
            fileChooser.setName("Open Clustering");
            fileChooser.addChoosableFileFilter(xmlFilter);
            fileChooser.addChoosableFileFilter(clusteringFilter);

            int returnVal = fileChooser.showDialog(ClusteringControl.this, "Open");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File filePath = fileChooser.getSelectedFile();
                if (xmlFilter.accept(filePath)) {
                    PNode restoredLabels = null;
                    try {
                        restoredLabels = LabelXmlUtils.restoreLabelsFromFile(fileChooser.getSelectedFile());
                        PNode manual = state.mapPNode.getManualLabels();

                        ArrayList<PNode> tmp = new ArrayList<PNode>();
                        for (ListIterator<?> iter = restoredLabels.getChildrenIterator(); iter.hasNext();) {
                            PNode element = (PNode) iter.next();
                            tmp.add(element);
                        }
                        manual.addChildren(tmp);
                        Logger.getLogger("at.tuwien.ifs.somtoolbox")
                                .info("Successfully loaded cluster labels.");
                    } catch (Exception e1) {
                        e1.printStackTrace();
                        Logger.getLogger("at.tuwien.ifs.somtoolbox")
                                .info("Error loading cluster labels: " + e1.getMessage());
                    }

                } else {

                    try {
                        FileInputStream fis = new FileInputStream(filePath);
                        GZIPInputStream gzipIs = new GZIPInputStream(fis);
                        ObjectInputStream ois = new ObjectInputStream(gzipIs);
                        ClusteringTree tree = (ClusteringTree) ois.readObject();

                        PNode manual = (PNode) ois.readObject();
                        PNode all = mapPane.getMap().getManualLabels();
                        ArrayList<PNode> tmp = new ArrayList<PNode>();
                        for (ListIterator<?> iter = manual.getChildrenIterator(); iter.hasNext();) {
                            PNode element = (PNode) iter.next();
                            tmp.add(element);
                        }
                        all.addChildren(tmp);

                        state.clusterWithLabels = ois.readInt();
                        labelSpinner.setValue(state.clusterWithLabels);
                        state.labelsWithValues = ois.readBoolean();
                        showValues.setSelected(state.labelsWithValues);
                        state.clusterByValue = ois.readDouble();
                        valueQe.setValue(new Double((1 - state.clusterByValue) * 100).intValue());

                        mapPane.getMap().buildTree(tree);
                        spinnerNoCluster.setValue(ois.readObject());

                        ois.close();
                        Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Successfully loaded clustering.");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        Logger.getLogger("at.tuwien.ifs.somtoolbox")
                                .info("Error loading clustering: " + ex.getMessage());
                    }

                }
                // keep the selected path for future references
                state.fileChooser.setSelectedFile(filePath.getParentFile());
            }
        }

    });
    panelButtons.add(loadButton);

    JButton exportImages = new JButton("Export");
    exportImages.setFont(smallFont);
    exportImages.setMargin(SMALL_INSETS);
    exportImages.setToolTipText("Export labels as images (not yet working)");
    exportImages.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            if (CommonSOMViewerStateData.fileNamePrefix != null
                    && !CommonSOMViewerStateData.fileNamePrefix.equals("")) {
                fileChooser.setCurrentDirectory(new File(CommonSOMViewerStateData.fileNamePrefix));
            } else {
                fileChooser.setCurrentDirectory(state.getFileChooser().getCurrentDirectory());
            }
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (fileChooser.getSelectedFile() != null) { // reusing the dialog
                fileChooser.setSelectedFile(null);
            }
            fileChooser.setName("Choose path");
            int returnVal = fileChooser.showDialog(ClusteringControl.this, "Choose path");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                // save images
                String path = fileChooser.getSelectedFile().getAbsolutePath();
                Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Writing label images to " + path);
            }
        }
    });
    panelButtons.add(exportImages);

    JButton deleteManual = new JButton("Delete");
    deleteManual.setFont(smallFont);
    deleteManual.setMargin(SMALL_INSETS);
    deleteManual.setToolTipText("Delete manually added labels.");
    deleteManual.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            state.mapPNode.getManualLabels().removeAllChildren();
            Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Manual Labels deleted.");
        }
    });
    panelButtons.add(deleteManual);
    c.anchor = GridBagConstraints.NORTH;
    this.getContentPane().add(panelButtons, c.nextRow());

    this.setVisible(true);
}