Example usage for javax.swing JList setPrototypeCellValue

List of usage examples for javax.swing JList setPrototypeCellValue

Introduction

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

Prototype

@BeanProperty(visualUpdate = true, description = "The cell prototype value, used to compute cell width and height.")
public void setPrototypeCellValue(E prototypeCellValue) 

Source Link

Document

Sets the prototypeCellValue property, and then (if the new value is non-null ), computes the fixedCellWidth and fixedCellHeight properties by requesting the cell renderer component for the given value (and index 0) from the cell renderer, and using that component's preferred size.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);

    String protoCellValue = "My Sample Item Value";
    list.setPrototypeCellValue(protoCellValue);

}

From source file:FillViewportHeightDemo.java

public FillViewportHeightDemo() {
    super("Empty Table DnD Demo");

    tableModel = getDefaultTableModel();
    table = new JTable(tableModel);
    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    table.setDropMode(DropMode.INSERT_ROWS);

    table.setTransferHandler(new TransferHandler() {

        public boolean canImport(TransferSupport support) {
            // for the demo, we'll only support drops (not clipboard paste)
            if (!support.isDrop()) {
                return false;
            }/*from   w w  w. j a  va 2  s.  com*/

            // we only import Strings
            if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return false;
            }

            return true;
        }

        public boolean importData(TransferSupport support) {
            // if we can't handle the import, say so
            if (!canImport(support)) {
                return false;
            }

            // fetch the drop location
            JTable.DropLocation dl = (JTable.DropLocation) support.getDropLocation();

            int row = dl.getRow();

            // fetch the data and bail if this fails
            String data;
            try {
                data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
            } catch (UnsupportedFlavorException e) {
                return false;
            } catch (IOException e) {
                return false;
            }

            String[] rowData = data.split(",");
            tableModel.insertRow(row, rowData);

            Rectangle rect = table.getCellRect(row, 0, false);
            if (rect != null) {
                table.scrollRectToVisible(rect);
            }

            // demo stuff - remove for blog
            model.removeAllElements();
            model.insertElementAt(getNextString(count++), 0);
            // end demo stuff

            return true;
        }
    });

    JList dragFrom = new JList(model);
    dragFrom.setFocusable(false);
    dragFrom.setPrototypeCellValue(getNextString(100));
    model.insertElementAt(getNextString(count++), 0);
    dragFrom.setDragEnabled(true);
    dragFrom.setBorder(BorderFactory.createLoweredBevelBorder());

    dragFrom.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent me) {
            if (SwingUtilities.isLeftMouseButton(me) && me.getClickCount() % 2 == 0) {
                String text = (String) model.getElementAt(0);
                String[] rowData = text.split(",");
                tableModel.insertRow(table.getRowCount(), rowData);
                model.removeAllElements();
                model.insertElementAt(getNextString(count++), 0);
            }
        }
    });

    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
    JPanel wrap = new JPanel();
    wrap.add(new JLabel("Drag from here:"));
    wrap.add(dragFrom);
    p.add(Box.createHorizontalStrut(4));
    p.add(Box.createGlue());
    p.add(wrap);
    p.add(Box.createGlue());
    p.add(Box.createHorizontalStrut(4));
    getContentPane().add(p, BorderLayout.NORTH);

    JScrollPane sp = new JScrollPane(table);
    getContentPane().add(sp, BorderLayout.CENTER);
    fillBox = new JCheckBoxMenuItem("Fill Viewport Height");
    fillBox.addActionListener(this);

    JMenuBar mb = new JMenuBar();
    JMenu options = new JMenu("Options");
    mb.add(options);
    setJMenuBar(mb);

    JMenuItem clear = new JMenuItem("Reset");
    clear.addActionListener(this);
    options.add(clear);
    options.add(fillBox);

    getContentPane().setPreferredSize(new Dimension(260, 180));
}

From source file:LocationSensitiveDemo.java

public LocationSensitiveDemo() {
    super("Location Sensitive Drag and Drop Demo");

    treeModel = getDefaultTreeModel();//from   ww w. j a  va  2 s .  c o m
    tree = new JTree(treeModel);
    tree.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    tree.setDropMode(DropMode.ON);
    namesPath = tree.getPathForRow(2);
    tree.expandRow(2);
    tree.expandRow(1);
    tree.setRowHeight(0);

    tree.setTransferHandler(new TransferHandler() {

        public boolean canImport(TransferHandler.TransferSupport info) {
            // for the demo, we'll only support drops (not clipboard paste)
            if (!info.isDrop()) {
                return false;
            }

            String item = (String) indicateCombo.getSelectedItem();

            if (item.equals("Always")) {
                info.setShowDropLocation(true);
            } else if (item.equals("Never")) {
                info.setShowDropLocation(false);
            }

            // we only import Strings
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return false;
            }

            // fetch the drop location
            JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation();

            TreePath path = dl.getPath();

            // we don't support invalid paths or descendants of the names folder
            if (path == null || namesPath.isDescendant(path)) {
                return false;
            }

            return true;
        }

        public boolean importData(TransferHandler.TransferSupport info) {
            // if we can't handle the import, say so
            if (!canImport(info)) {
                return false;
            }

            // fetch the drop location
            JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation();

            // fetch the path and child index from the drop location
            TreePath path = dl.getPath();
            int childIndex = dl.getChildIndex();

            // fetch the data and bail if this fails
            String data;
            try {
                data = (String) info.getTransferable().getTransferData(DataFlavor.stringFlavor);
            } catch (UnsupportedFlavorException e) {
                return false;
            } catch (IOException e) {
                return false;
            }

            // if child index is -1, the drop was on top of the path, so we'll
            // treat it as inserting at the end of that path's list of children
            if (childIndex == -1) {
                childIndex = tree.getModel().getChildCount(path.getLastPathComponent());
            }

            // create a new node to represent the data and insert it into the model
            DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(data);
            DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) path.getLastPathComponent();
            treeModel.insertNodeInto(newNode, parentNode, childIndex);

            // make the new node visible and scroll so that it's visible
            tree.makeVisible(path.pathByAddingChild(newNode));
            tree.scrollRectToVisible(tree.getPathBounds(path.pathByAddingChild(newNode)));

            // demo stuff - remove for blog
            model.removeAllElements();
            model.insertElementAt("String " + (++count), 0);
            // end demo stuff

            return true;
        }
    });

    JList dragFrom = new JList(model);
    dragFrom.setFocusable(false);
    dragFrom.setPrototypeCellValue("String 0123456789");
    model.insertElementAt("String " + count, 0);
    dragFrom.setDragEnabled(true);
    dragFrom.setBorder(BorderFactory.createLoweredBevelBorder());

    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
    JPanel wrap = new JPanel();
    wrap.add(new JLabel("Drag from here:"));
    wrap.add(dragFrom);
    p.add(Box.createHorizontalStrut(4));
    p.add(Box.createGlue());
    p.add(wrap);
    p.add(Box.createGlue());
    p.add(Box.createHorizontalStrut(4));
    getContentPane().add(p, BorderLayout.NORTH);

    getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER);
    indicateCombo = new JComboBox(new String[] { "Default", "Always", "Never" });
    indicateCombo.setSelectedItem("INSERT");

    p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
    wrap = new JPanel();
    wrap.add(new JLabel("Show drop location:"));
    wrap.add(indicateCombo);
    p.add(Box.createHorizontalStrut(4));
    p.add(Box.createGlue());
    p.add(wrap);
    p.add(Box.createGlue());
    p.add(Box.createHorizontalStrut(4));
    getContentPane().add(p, BorderLayout.SOUTH);

    getContentPane().setPreferredSize(new Dimension(400, 450));
}

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;//w w  w . ja va 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();

}