Example usage for javax.swing JList addListSelectionListener

List of usage examples for javax.swing JList addListSelectionListener

Introduction

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

Prototype

public void addListSelectionListener(ListSelectionListener listener) 

Source Link

Document

Adds a listener to the list, to be notified each time a change to the selection occurs; the preferred way of listening for selection state changes.

Usage

From source file:com.googlecode.sarasvati.visual.jung.JungVisualizer.java

@SuppressWarnings("serial")
public static void main(String[] args) throws Exception {
    TestSetup.init();/*w  w w  .  j a v  a2  s .co  m*/

    Session session = TestSetup.openSession();
    HibEngine engine = new HibEngine(session);

    JFrame frame = new JFrame("Workflow Visualizer");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setMinimumSize(new Dimension(800, 600));

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    frame.getContentPane().add(splitPane);

    DefaultListModel listModel = new DefaultListModel();
    for (Graph g : engine.getRepository().getGraphs()) {
        listModel.addElement(g);
    }

    ListCellRenderer cellRenderer = new DefaultListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

            Graph g = (Graph) value;

            setText(g.getName() + "." + g.getVersion() + "  ");
            return this;
        }
    };

    final JList graphList = new JList(listModel);
    graphList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    graphList.setCellRenderer(cellRenderer);

    JScrollPane listScrollPane = new JScrollPane(graphList);
    listScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    listScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

    splitPane.add(listScrollPane);

    //TreeLayout<NodeRef, Arc> layout = new TreeLayout<NodeRef, Arc>();

    DirectedSparseMultigraph<Node, Arc> graph = new DirectedSparseMultigraph<Node, Arc>();

    //final SpringLayout2<HibNodeRef, HibArc> layout = new SpringLayout2<HibNodeRef, HibArc>(graph);
    //final KKLayout<HibNodeRef, HibArc> layout = new KKLayout<HibNodeRef, HibArc>(graph);
    final TreeLayout layout = new TreeLayout(graph);
    final BasicVisualizationServer<Node, Arc> vs = new BasicVisualizationServer<Node, Arc>(layout);
    //vs.getRenderContext().setVertexLabelTransformer( new NodeLabeller() );
    //vs.getRenderContext().setEdgeLabelTransformer( new ArcLabeller() );
    vs.getRenderContext().setVertexShapeTransformer(new NodeShapeTransformer());
    vs.getRenderContext().setVertexFillPaintTransformer(new NodeColorTransformer());
    vs.getRenderContext().setLabelOffset(5);
    vs.getRenderContext().setVertexIconTransformer(new Transformer<Node, Icon>() {
        @Override
        public Icon transform(Node node) {
            return "task".equals(node.getType()) ? new TaskIcon(node) : null;
        }
    });

    Transformer<Arc, Paint> edgeColorTrans = new Transformer<Arc, Paint>() {
        private Color darkRed = new Color(128, 0, 0);

        @Override
        public Paint transform(Arc arc) {
            return "reject".equals(arc.getName()) ? darkRed : Color.black;
        }
    };

    vs.getRenderContext().setEdgeDrawPaintTransformer(edgeColorTrans);
    vs.getRenderContext().setArrowDrawPaintTransformer(edgeColorTrans);

    final JScrollPane scrollPane = new JScrollPane(vs);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

    splitPane.add(scrollPane);
    scrollPane.setBackground(Color.white);

    graphList.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
                return;
            }

            final Graph g = (Graph) graphList.getSelectedValue();

            if ((g == null && currentGraph == null) || (g != null && g.equals(currentGraph))) {
                return;
            }

            currentGraph = g;

            DirectedSparseMultigraph<Node, Arc> jungGraph = new DirectedSparseMultigraph<Node, Arc>();

            for (Node ref : currentGraph.getNodes()) {
                jungGraph.addVertex(ref);
            }

            for (Arc arc : currentGraph.getArcs()) {
                jungGraph.addEdge(arc, arc.getStartNode(), arc.getEndNode());
            }

            GraphTree graphTree = new GraphTree(g);
            layout.setGraph(jungGraph);
            layout.setInitializer(new NodeLocationTransformer(graphTree));
            scrollPane.repaint();
        }
    });

    frame.setVisible(true);
}

From source file:Main.java

public static JList generateListFor(Object... objs) {
    Container c = search(objs, Container.class);
    String[] name_value = search(objs, String[].class);
    ListModel model = search(objs, ListModel.class);
    Object[] dataObjects = search(objs, Object[].class);
    Vector dataVector = search(objs, Vector.class);
    ListSelectionListener selectionListener = search(objs, ListSelectionListener.class);
    ListUI ui = search(objs, ListUI.class);
    ListSelectionModel selectionModel = search(objs, ListSelectionModel.class);
    ListCellRenderer cellRenderer = search(objs, ListCellRenderer.class);
    JList list = model == null
            ? (dataObjects == null ? (dataVector == null ? new JList() : new JList(dataVector))
                    : new JList(dataObjects))
            : new JList(model);
    list.setName(name_value == null ? "" : name_value[0]);
    if (selectionListener != null)
        list.addListSelectionListener(selectionListener);
    if (ui != null)
        list.setUI(ui);/*  w  w w .j ava  2  s  .c om*/
    if (selectionModel != null)
        list.setSelectionModel(selectionModel);
    if (cellRenderer != null)
        list.setCellRenderer(cellRenderer);
    addJContainerListeners(list, objs);
    if (c != null)
        addToContainer(c, list);
    return list;
}

From source file:Main.java

public Main() {
    setLayout(new GridLayout(1, 2));
    String[] numbers = { "one", "two", "three", "four", "five", "six", "seven" };
    JList<String> list = new JList<>(numbers);
    list.setVisibleRowCount(1);//  w w w .  j av a  2  s  .  co  m
    list.addListSelectionListener(this);
    JScrollPane s = new JScrollPane(list);
    s.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
    s.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    add(s);
    list.setSelectedIndex(3);
}

From source file:ListTest.java

public ListTest() {
    setTitle("ListTest: Press control to multi-select");
    setSize(400, 300);/* w w  w. j ava  2 s.c om*/
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });

    String[] words = { "quick", "brown", "hungry", "wild", "silent", "huge" };

    JList wordList = new JList(words);
    JScrollPane scrollPane = new JScrollPane(wordList);

    JPanel p = new JPanel();
    p.add(scrollPane);
    wordList.addListSelectionListener(this);

    getContentPane().add(p, "South");
    getContentPane().add(label, "Center");
}

From source file:ListIt.java

public ListIt() {
    JFrame f = new JFrame();
    final PartsListModel pcm = new PartsListModel();
    ListCellRenderer lcr = new MyLabelRenderer();
    JList jl = new JList(pcm);
    jl.setCellRenderer(lcr);/*from  ww w  .  j a v  a2s  .c o m*/
    ListSelectionModel lsm = jl.getSelectionModel();
    lsm.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jl.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                String element[] = (String[]) pcm.getElementAt(e.getFirstIndex());
                System.out.println(element[0] + " : " + element[1] + " : " + element[2]);
            }
        }
    });
    JScrollPane jsp = new JScrollPane(jl);
    JComboBox jc = new JComboBox(pcm);
    jc.setRenderer(lcr);
    JButton jb = new JButton("Add Merchandise");
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            pcm.addElement(partsList[(int) (Math.random() * partsList.length)]);
        }
    });
    Container c = f.getContentPane();
    c.add(jsp, BorderLayout.NORTH);
    c.add(jc, BorderLayout.CENTER);
    c.add(jb, BorderLayout.SOUTH);
    f.setSize(250, 250);
    f.show();
}

From source file:SplitPaneTest.java

public SplitPaneFrame() {
    setTitle("SplitPaneTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    // set up components for planet names, images, descriptions

    final JList planetList = new JList(planets);
    final JLabel planetImage = new JLabel();
    final JTextArea planetDescription = new JTextArea();

    planetList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent event) {
            Planet value = (Planet) planetList.getSelectedValue();

            // update image and description

            planetImage.setIcon(value.getImage());
            planetDescription.setText(value.getDescription());
        }//from  w ww. j  a  va  2 s  .c  om
    });

    // set up split panes

    JSplitPane innerPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, planetList, planetImage);

    innerPane.setContinuousLayout(true);
    innerPane.setOneTouchExpandable(true);

    JSplitPane outerPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, innerPane, planetDescription);

    add(outerPane, BorderLayout.CENTER);
}

From source file:Main.java

public ListRenderingFrame() {
    setTitle("ListRendering");
    setSize(400, 300);// ww  w.  java2s.  c o m
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });

    Vector fonts = new Vector();
    fonts.add(new Font("Serif", Font.PLAIN, 8));
    fonts.add(new Font("SansSerif", Font.BOLD, 12));
    fonts.add(new Font("Monospaced", Font.PLAIN, 16));
    fonts.add(new Font("Dialog", Font.ITALIC, 12));
    fonts.add(new Font("DialogInput", Font.PLAIN, 12));
    JList fontList = new JList(fonts);
    fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    fontList.setCellRenderer(new FontCellRenderer());
    JScrollPane scrollPane = new JScrollPane(fontList);

    JPanel p = new JPanel();
    p.add(scrollPane);
    fontList.addListSelectionListener(this);

    getContentPane().add(p, "Center");

    getContentPane().add(label, "South");
}

From source file:LongListTest.java

public LongListTest() {
    setTitle("LongListTest");
    setSize(400, 300);//from   ww w.ja va  2  s  .  com
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });

    JList wordList = new JList(new WordListModel(300000));
    wordList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    wordList.setFixedCellWidth(50);
    wordList.setFixedCellHeight(15);

    JScrollPane scrollPane = new JScrollPane(wordList);

    JPanel p = new JPanel();
    p.add(scrollPane);
    wordList.addListSelectionListener(this);

    getContentPane().add(p, "Center");

    getContentPane().add(label, "North");
}

From source file:net.sf.jabref.gui.preftabs.PreferencesDialog.java

public PreferencesDialog(JabRefFrame parent) {
    super(parent, Localization.lang("JabRef preferences"), false);
    JabRefPreferences prefs = JabRefPreferences.getInstance();
    frame = parent;//from   w  ww. j a v a  2  s.  c  o  m

    main = new JPanel();
    JPanel mainPanel = new JPanel();
    JPanel lower = new JPanel();

    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(mainPanel, BorderLayout.CENTER);
    getContentPane().add(lower, BorderLayout.SOUTH);

    final CardLayout cardLayout = new CardLayout();
    main.setLayout(cardLayout);

    List<PrefsTab> tabs = new ArrayList<>();
    tabs.add(new GeneralTab(prefs));
    tabs.add(new NetworkTab(prefs));
    tabs.add(new FileTab(frame, prefs));
    tabs.add(new FileSortTab(prefs));
    tabs.add(new EntryEditorPrefsTab(frame, prefs));
    tabs.add(new GroupsPrefsTab(prefs));
    tabs.add(new AppearancePrefsTab(prefs));
    tabs.add(new ExternalTab(frame, this, prefs));
    tabs.add(new TablePrefsTab(prefs));
    tabs.add(new TableColumnsTab(prefs, parent));
    tabs.add(new LabelPatternPrefTab(prefs, parent.getCurrentBasePanel()));
    tabs.add(new PreviewPrefsTab(prefs));
    tabs.add(new NameFormatterTab(prefs));
    tabs.add(new ImportSettingsTab(prefs));
    tabs.add(new XmpPrefsTab(prefs));
    tabs.add(new AdvancedTab(prefs));

    // add all tabs
    tabs.forEach(tab -> main.add((Component) tab, tab.getTabName()));

    mainPanel.setBorder(BorderFactory.createEtchedBorder());

    String[] tabNames = tabs.stream().map(PrefsTab::getTabName).toArray(String[]::new);
    JList<String> chooser = new JList<>(tabNames);
    chooser.setBorder(BorderFactory.createEtchedBorder());
    // Set a prototype value to control the width of the list:
    chooser.setPrototypeCellValue("This should be wide enough");
    chooser.setSelectedIndex(0);
    chooser.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    // Add the selection listener that will show the correct panel when
    // selection changes:
    chooser.addListSelectionListener(e -> {
        if (e.getValueIsAdjusting()) {
            return;
        }
        String o = chooser.getSelectedValue();
        cardLayout.show(main, o);
    });

    JPanel buttons = new JPanel();
    buttons.setLayout(new GridLayout(4, 1));
    buttons.add(importPreferences, 0);
    buttons.add(exportPreferences, 1);
    buttons.add(showPreferences, 2);
    buttons.add(resetPreferences, 3);

    JPanel westPanel = new JPanel();
    westPanel.setLayout(new BorderLayout());
    westPanel.add(chooser, BorderLayout.CENTER);
    westPanel.add(buttons, BorderLayout.SOUTH);
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(main, BorderLayout.CENTER);
    mainPanel.add(westPanel, BorderLayout.WEST);

    JButton ok = new JButton(Localization.lang("OK"));
    JButton cancel = new JButton(Localization.lang("Cancel"));
    ok.addActionListener(new OkAction());
    CancelAction cancelAction = new CancelAction();
    cancel.addActionListener(cancelAction);
    lower.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    ButtonBarBuilder buttonBarBuilder = new ButtonBarBuilder(lower);
    buttonBarBuilder.addGlue();
    buttonBarBuilder.addButton(ok);
    buttonBarBuilder.addButton(cancel);
    buttonBarBuilder.addGlue();

    // Key bindings:
    KeyBinder.bindCloseDialogKeyToCancelAction(this.getRootPane(), cancelAction);

    // Import and export actions:
    exportPreferences.setToolTipText(Localization.lang("Export preferences to file"));
    exportPreferences.addActionListener(e -> {
        String filename = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")),
                Collections.singletonList(".xml"), JFileChooser.SAVE_DIALOG, false);
        if (filename == null) {
            return;
        }
        File file = new File(filename);
        if (!file.exists() || (JOptionPane.showConfirmDialog(PreferencesDialog.this,
                Localization.lang("'%0' exists. Overwrite file?", file.getName()),
                Localization.lang("Export preferences"),
                JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION)) {

            try {
                prefs.exportPreferences(filename);
            } catch (JabRefException ex) {
                LOGGER.warn(ex.getMessage(), ex);
                JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(),
                        Localization.lang("Export preferences"), JOptionPane.ERROR_MESSAGE);
            }
        }
    });

    importPreferences.setToolTipText(Localization.lang("Import preferences from file"));
    importPreferences.addActionListener(e -> {
        String filename = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")),
                Collections.singletonList(".xml"), JFileChooser.OPEN_DIALOG, false);
        if (filename != null) {
            try {
                prefs.importPreferences(filename);
                updateAfterPreferenceChanges();
                JOptionPane.showMessageDialog(PreferencesDialog.this,
                        Localization.lang("You must restart JabRef for this to come into effect."),
                        Localization.lang("Import preferences"), JOptionPane.WARNING_MESSAGE);
            } catch (JabRefException ex) {
                LOGGER.warn(ex.getMessage(), ex);
                JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(),
                        Localization.lang("Import preferences"), JOptionPane.ERROR_MESSAGE);
            }
        }
    });

    showPreferences.addActionListener(
            e -> new PreferencesFilterDialog(new JabRefPreferencesFilter(Globals.prefs), frame)
                    .setVisible(true));
    resetPreferences.addActionListener(e -> {
        if (JOptionPane.showConfirmDialog(PreferencesDialog.this,
                Localization.lang("Are you sure you want to reset all settings to default values?"),
                Localization.lang("Reset preferences"),
                JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
            try {
                prefs.clear();
                JOptionPane.showMessageDialog(PreferencesDialog.this,
                        Localization.lang("You must restart JabRef for this to come into effect."),
                        Localization.lang("Reset preferences"), JOptionPane.WARNING_MESSAGE);
            } catch (BackingStoreException ex) {
                LOGGER.warn(ex.getMessage(), ex);
                JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(),
                        Localization.lang("Reset preferences"), JOptionPane.ERROR_MESSAGE);
            }
            updateAfterPreferenceChanges();
        }
    });

    setValues();

    pack();

}

From source file:com.projity.pm.graphic.chart.ChartLegend.java

JList getListInstance(boolean cost) {
    final JList list = new JList() { // do not want to update the UI. see below also
        private static final long serialVersionUID = 1L;

        public void updateUI() {
            if (!Environment.isNewLook())
                super.updateUI();
        }//w  w  w .j av  a  2 s .co m
    };
    if (Environment.isNewLook()) // The PLAF can override the custom renderer. This avoids that
        list.setUI(new BasicListUI());
    list.setSelectionMode(DefaultListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    list.setCellRenderer(new ListRenderer());
    setListFields(list, cost);
    if (!simple) {
        list.setSelectedIndex(0); // start off with first choice selected         
        list.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (chartInfo.isRestoring()) // don't want to listen if updating from workspace
                    return;
                if (e.getValueIsAdjusting() == false) {
                    chartInfo.setTraces(list.getSelectedValues());
                }
            }
        });
    }

    return list;
}