Example usage for javax.swing JList setBorder

List of usage examples for javax.swing JList setBorder

Introduction

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

Prototype

@BeanProperty(preferred = true, visualUpdate = true, description = "The component's border.")
public void setBorder(Border border) 

Source Link

Document

Sets the border of this component.

Usage

From source file:Main.java

public static void main(String[] args) {
    final DefaultListModel<String> model = new DefaultListModel<>();
    final JList<String> list = new JList<>(model);
    JFrame f = new JFrame();

    model.addElement("A");
    model.addElement("B");
    model.addElement("C");
    model.addElement("D");
    model.addElement("E");

    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

    JPanel leftPanel = new JPanel();
    JPanel rightPanel = new JPanel();

    leftPanel.setLayout(new BorderLayout());
    rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));

    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));

    list.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                int index = list.locationToIndex(e.getPoint());
                Object item = model.getElementAt(index);
                String text = JOptionPane.showInputDialog("Rename item", item);
                String newitem = "";
                if (text != null)
                    newitem = text.trim();
                else
                    return;

                if (!newitem.isEmpty()) {
                    model.remove(index);
                    model.add(index, newitem);
                    ListSelectionModel selmodel = list.getSelectionModel();
                    selmodel.setLeadSelectionIndex(index);
                }//from  w ww. j  av  a2s.  c  o m
            }
        }
    });
    leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    leftPanel.add(new JScrollPane(list));

    JButton removeall = new JButton("Remove All");
    JButton add = new JButton("Add");
    JButton rename = new JButton("Rename");
    JButton delete = new JButton("Delete");

    add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String text = JOptionPane.showInputDialog("Add a new item");
            String item = null;

            if (text != null)
                item = text.trim();
            else
                return;

            if (!item.isEmpty())
                model.addElement(item);
        }
    });

    delete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            ListSelectionModel selmodel = list.getSelectionModel();
            int index = selmodel.getMinSelectionIndex();
            if (index >= 0)
                model.remove(index);
        }

    });

    rename.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ListSelectionModel selmodel = list.getSelectionModel();
            int index = selmodel.getMinSelectionIndex();
            if (index == -1)
                return;
            Object item = model.getElementAt(index);
            String text = JOptionPane.showInputDialog("Rename item", item);
            String newitem = null;

            if (text != null) {
                newitem = text.trim();
            } else
                return;

            if (!newitem.isEmpty()) {
                model.remove(index);
                model.add(index, newitem);
            }
        }
    });

    removeall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            model.clear();
        }
    });

    rightPanel.add(add);
    rightPanel.add(rename);
    rightPanel.add(delete);
    rightPanel.add(removeall);

    rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20));

    panel.add(leftPanel);
    panel.add(rightPanel);

    f.add(panel);

    f.setSize(350, 250);
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);

}

From source file:List.java

public static void main(String[] args) {
    final DefaultListModel model = new DefaultListModel();
    final JList list = new JList(model);
    JFrame f = new JFrame();
    f.setTitle("JList models");

    model.addElement("A");
    model.addElement("B");
    model.addElement("C");
    model.addElement("D");
    model.addElement("E");

    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

    JPanel leftPanel = new JPanel();
    JPanel rightPanel = new JPanel();

    leftPanel.setLayout(new BorderLayout());
    rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));

    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));

    list.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                int index = list.locationToIndex(e.getPoint());
                Object item = model.getElementAt(index);
                String text = JOptionPane.showInputDialog("Rename item", item);
                String newitem = "";
                if (text != null)
                    newitem = text.trim();
                else
                    return;

                if (!newitem.isEmpty()) {
                    model.remove(index);
                    model.add(index, newitem);
                    ListSelectionModel selmodel = list.getSelectionModel();
                    selmodel.setLeadSelectionIndex(index);
                }/*from www .j a v  a2  s. c o  m*/
            }
        }
    });
    leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    leftPanel.add(new JScrollPane(list));

    JButton removeall = new JButton("Remove All");
    JButton add = new JButton("Add");
    JButton rename = new JButton("Rename");
    JButton delete = new JButton("Delete");

    add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String text = JOptionPane.showInputDialog("Add a new item");
            String item = null;

            if (text != null)
                item = text.trim();
            else
                return;

            if (!item.isEmpty())
                model.addElement(item);
        }
    });

    delete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            ListSelectionModel selmodel = list.getSelectionModel();
            int index = selmodel.getMinSelectionIndex();
            if (index >= 0)
                model.remove(index);
        }

    });

    rename.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ListSelectionModel selmodel = list.getSelectionModel();
            int index = selmodel.getMinSelectionIndex();
            if (index == -1)
                return;
            Object item = model.getElementAt(index);
            String text = JOptionPane.showInputDialog("Rename item", item);
            String newitem = null;

            if (text != null) {
                newitem = text.trim();
            } else
                return;

            if (!newitem.isEmpty()) {
                model.remove(index);
                model.add(index, newitem);
            }
        }
    });

    removeall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            model.clear();
        }
    });

    rightPanel.add(add);
    rightPanel.add(rename);
    rightPanel.add(delete);
    rightPanel.add(removeall);

    rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20));

    panel.add(leftPanel);
    panel.add(rightPanel);

    f.add(panel);

    f.setSize(350, 250);
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);

}

From source file:JListBackground.java

public static void addComponentsToPane(Container pane) {
    String[] bruteForceCode = { "int count = 0", "int m = mPattern.length();", "int n = mSource .length();",
            "outer:", " ++count;", " }", " return count;", "}" };
    JList list = new JList(bruteForceCode);
    Border etch = BorderFactory.createEtchedBorder();
    list.setBorder(BorderFactory.createTitledBorder(etch, "Brute Force Code"));
    JPanel listPanel = new JPanel();
    listPanel.add(list);//from  w w  w  . ja  v  a 2 s.  c  o  m
    listPanel.setBackground(lightBlue);
    list.setBackground(lightBlue);

    pane.add(listPanel, BorderLayout.CENTER);
    pane.setBackground(lightBlue);
}

From source file:net.sf.jabref.exporter.ExportToClipboardAction.java

@Override
public void run() {
    BasePanel panel = frame.getCurrentBasePanel();
    if (panel == null) {
        return;/*  w  ww .j  ava 2 s.c  o  m*/
    }
    if (panel.getSelectedEntries().isEmpty()) {
        message = Localization.lang("This operation requires one or more entries to be selected.");
        getCallBack().update();
        return;
    }

    List<IExportFormat> exportFormats = new LinkedList<>(ExportFormats.getExportFormats().values());
    Collections.sort(exportFormats, (e1, e2) -> e1.getDisplayName().compareTo(e2.getDisplayName()));
    String[] exportFormatDisplayNames = new String[exportFormats.size()];
    for (int i = 0; i < exportFormats.size(); i++) {
        IExportFormat exportFormat = exportFormats.get(i);
        exportFormatDisplayNames[i] = exportFormat.getDisplayName();
    }

    JList<String> list = new JList<>(exportFormatDisplayNames);
    list.setBorder(BorderFactory.createEtchedBorder());
    list.setSelectionInterval(0, 0);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    int answer = JOptionPane.showOptionDialog(frame, list, Localization.lang("Select export format"),
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] {
                    Localization.lang("Export with selected format"), Localization.lang("Return to JabRef") },
            Localization.lang("Export with selected format"));
    if (answer == JOptionPane.NO_OPTION) {
        return;
    }

    IExportFormat format = exportFormats.get(list.getSelectedIndex());

    // Set the global variable for this database's file directory before exporting,
    // so formatters can resolve linked files correctly.
    // (This is an ugly hack!)
    Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectory();

    File tmp = null;
    try {
        // To simplify the exporter API we simply do a normal export to a temporary
        // file, and read the contents afterwards:
        tmp = File.createTempFile("jabrefCb", ".tmp");
        tmp.deleteOnExit();
        List<BibEntry> entries = panel.getSelectedEntries();

        // Write to file:
        format.performExport(panel.getBibDatabaseContext(), tmp.getPath(), panel.getEncoding(), entries);
        // Read the file and put the contents on the clipboard:
        StringBuilder sb = new StringBuilder();
        try (Reader reader = new InputStreamReader(new FileInputStream(tmp), panel.getEncoding())) {
            int s;
            while ((s = reader.read()) != -1) {
                sb.append((char) s);
            }
        }
        ClipboardOwner owner = (clipboard, content) -> {
            // Do nothing
        };
        RtfSelection rs = new RtfSelection(sb.toString());
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(rs, owner);
        message = Localization.lang("Entries exported to clipboard") + ": " + entries.size();

    } catch (Exception e) {
        LOGGER.error("Error exporting to clipboard", e); //To change body of catch statement use File | Settings | File Templates.
        message = Localization.lang("Error exporting to clipboard");
    } finally {
        // Clean up:
        if ((tmp != null) && !tmp.delete()) {
            LOGGER.info("Cannot delete temporary clipboard file");
        }
    }
}

From source file:net.sf.jabref.gui.exporter.ExportToClipboardAction.java

@Override
public void run() {
    BasePanel panel = frame.getCurrentBasePanel();
    if (panel == null) {
        return;// w  w w  .j  a v a 2  s .c  om
    }
    if (panel.getSelectedEntries().isEmpty()) {
        message = Localization.lang("This operation requires one or more entries to be selected.");
        getCallBack().update();
        return;
    }

    List<IExportFormat> exportFormats = new LinkedList<>(ExportFormats.getExportFormats().values());
    Collections.sort(exportFormats, (e1, e2) -> e1.getDisplayName().compareTo(e2.getDisplayName()));
    String[] exportFormatDisplayNames = new String[exportFormats.size()];
    for (int i = 0; i < exportFormats.size(); i++) {
        IExportFormat exportFormat = exportFormats.get(i);
        exportFormatDisplayNames[i] = exportFormat.getDisplayName();
    }

    JList<String> list = new JList<>(exportFormatDisplayNames);
    list.setBorder(BorderFactory.createEtchedBorder());
    list.setSelectionInterval(0, 0);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    int answer = JOptionPane.showOptionDialog(frame, list, Localization.lang("Select export format"),
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] {
                    Localization.lang("Export with selected format"), Localization.lang("Return to JabRef") },
            Localization.lang("Export with selected format"));
    if (answer == JOptionPane.NO_OPTION) {
        return;
    }

    IExportFormat format = exportFormats.get(list.getSelectedIndex());

    // Set the global variable for this database's file directory before exporting,
    // so formatters can resolve linked files correctly.
    // (This is an ugly hack!)
    Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectory();

    File tmp = null;
    try {
        // To simplify the exporter API we simply do a normal export to a temporary
        // file, and read the contents afterwards:
        tmp = File.createTempFile("jabrefCb", ".tmp");
        tmp.deleteOnExit();
        List<BibEntry> entries = panel.getSelectedEntries();

        // Write to file:
        format.performExport(panel.getBibDatabaseContext(), tmp.getPath(),
                panel.getBibDatabaseContext().getMetaData().getEncoding(), entries);
        // Read the file and put the contents on the clipboard:
        StringBuilder sb = new StringBuilder();
        try (Reader reader = new InputStreamReader(new FileInputStream(tmp),
                panel.getBibDatabaseContext().getMetaData().getEncoding())) {
            int s;
            while ((s = reader.read()) != -1) {
                sb.append((char) s);
            }
        }
        ClipboardOwner owner = (clipboard, content) -> {
            // Do nothing
        };
        RtfSelection rs = new RtfSelection(sb.toString());
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(rs, owner);
        message = Localization.lang("Entries exported to clipboard") + ": " + entries.size();

    } catch (Exception e) {
        LOGGER.error("Error exporting to clipboard", e); //To change body of catch statement use File | Settings | File Templates.
        message = Localization.lang("Error exporting to clipboard");
    } finally {
        // Clean up:
        if ((tmp != null) && !tmp.delete()) {
            LOGGER.info("Cannot delete temporary clipboard file");
        }
    }
}

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 www  .  jav  a 2 s  . co 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: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;
            }//  w  ww  .j a  v  a 2s  . co m

            // 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();//w  w  w .j av a2 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:lu.lippmann.cdb.ext.hydviga.ui.GapFillingFrame.java

/**
 * Constructor./*  w w  w .j  ava2  s. com*/
 */
public GapFillingFrame(final AbstractTabView atv, final Instances dataSet, final Attribute attr,
        final int dateIdx, final int valuesBeforeAndAfter, final int position, final int gapsize,
        final StationsDataProvider gcp, final boolean inBatchMode) {
    super();

    setTitle("Gap filling for " + attr.name() + " ("
            + dataSet.attribute(dateIdx).formatDate(dataSet.instance(position).value(dateIdx)) + " -> "
            + dataSet.attribute(dateIdx).formatDate(dataSet.instance(position + gapsize).value(dateIdx)) + ")");
    LogoHelper.setLogo(this);

    this.atv = atv;

    this.dataSet = dataSet;
    this.attr = attr;
    this.dateIdx = dateIdx;
    this.valuesBeforeAndAfter = valuesBeforeAndAfter;
    this.position = position;
    this.gapsize = gapsize;

    this.gcp = gcp;

    final Instances testds = WekaDataProcessingUtil.buildFilteredDataSet(dataSet, 0,
            dataSet.numAttributes() - 1, Math.max(0, position - valuesBeforeAndAfter),
            Math.min(position + gapsize + valuesBeforeAndAfter, dataSet.numInstances() - 1));

    this.attrNames = WekaTimeSeriesUtil.getNamesOfAttributesWithoutGap(testds);

    this.isGapSimulated = (this.attrNames.contains(attr.name()));
    this.originaldataSet = new Instances(dataSet);
    if (this.isGapSimulated) {
        setTitle(getTitle() + " [SIMULATED GAP]");
        /*final JXLabel fictiveGapLabel=new JXLabel("                                                                        FICTIVE GAP");
        fictiveGapLabel.setForeground(Color.RED);
        fictiveGapLabel.setFont(new Font(fictiveGapLabel.getFont().getName(), Font.PLAIN,fictiveGapLabel.getFont().getSize()*2));
        final JXPanel fictiveGapPanel=new JXPanel();
        fictiveGapPanel.setLayout(new BorderLayout());
        fictiveGapPanel.add(fictiveGapLabel,BorderLayout.CENTER);
        getContentPane().add(fictiveGapPanel,BorderLayout.NORTH);*/
        this.attrNames.remove(attr.name());
        this.originalDataBeforeGapSimulation = dataSet.attributeToDoubleArray(attr.index());
        for (int i = position; i < position + gapsize; i++)
            dataSet.instance(i).setMissing(attr);
    }

    final Object[] attrNamesObj = this.attrNames.toArray();

    this.centerPanel = new JXPanel();
    this.centerPanel.setLayout(new BorderLayout());
    getContentPane().add(this.centerPanel, BorderLayout.CENTER);

    //final JXPanel algoPanel=new JXPanel();
    //getContentPane().add(algoPanel,BorderLayout.NORTH);
    final JXPanel filterPanel = new JXPanel();
    //filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.Y_AXIS));      
    filterPanel.setLayout(new GridBagLayout());
    final GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.weightx = 1;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.insets = new Insets(10, 10, 10, 10);
    getContentPane().add(filterPanel, BorderLayout.WEST);

    final JXComboBox algoCombo = new JXComboBox(Algo.values());
    algoCombo.setBorder(new TitledBorder("Algorithm"));
    filterPanel.add(algoCombo, gbc);
    gbc.gridy++;

    final JXLabel infoLabel = new JXLabel("Usable = with no missing values on the period");
    //infoLabel.setBorder(new TitledBorder(""));
    filterPanel.add(infoLabel, gbc);
    gbc.gridy++;

    final JList<Object> timeSeriesList = new JList<Object>(attrNamesObj);
    timeSeriesList.setBorder(new TitledBorder("Usable time series"));
    timeSeriesList.setSelectionMode(DefaultListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    final JScrollPane jcpMap = new JScrollPane(timeSeriesList);
    jcpMap.setPreferredSize(new Dimension(225, 150));
    jcpMap.setMinimumSize(new Dimension(225, 150));
    filterPanel.add(jcpMap, gbc);
    gbc.gridy++;

    final JXPanel mapPanel = new JXPanel();
    mapPanel.setBorder(new TitledBorder(""));
    mapPanel.setLayout(new BorderLayout());
    mapPanel.add(gcp.getMapPanel(Arrays.asList(attr.name()), this.attrNames, true), BorderLayout.CENTER);
    filterPanel.add(mapPanel, gbc);
    gbc.gridy++;

    final JXLabel mssLabel = new JXLabel(
            "<html>Most similar usable serie: <i>[... computation ...]</i></html>");
    mssLabel.setBorder(new TitledBorder(""));
    filterPanel.add(mssLabel, gbc);
    gbc.gridy++;

    final JXLabel nsLabel = new JXLabel("<html>Nearest usable serie: <i>[... computation ...]</i></html>");
    nsLabel.setBorder(new TitledBorder(""));
    filterPanel.add(nsLabel, gbc);
    gbc.gridy++;

    final JXLabel ussLabel = new JXLabel("<html>Upstream serie: <i>[... computation ...]</i></html>");
    ussLabel.setBorder(new TitledBorder(""));
    filterPanel.add(ussLabel, gbc);
    gbc.gridy++;

    final JXLabel dssLabel = new JXLabel("<html>Downstream serie: <i>[... computation ...]</i></html>");
    dssLabel.setBorder(new TitledBorder(""));
    filterPanel.add(dssLabel, gbc);
    gbc.gridy++;

    final JCheckBox hideOtherSeriesCB = new JCheckBox("Hide the others series");
    hideOtherSeriesCB.setSelected(DEFAULT_HIDE_OTHER_SERIES_OPTION);
    filterPanel.add(hideOtherSeriesCB, gbc);
    gbc.gridy++;

    final JCheckBox showErrorCB = new JCheckBox("Show error on plot");
    filterPanel.add(showErrorCB, gbc);
    gbc.gridy++;

    final JCheckBox zoomCB = new JCheckBox("Auto-adjusted size");
    zoomCB.setSelected(DEFAULT_ZOOM_OPTION);
    filterPanel.add(zoomCB, gbc);
    gbc.gridy++;

    final JCheckBox multAxisCB = new JCheckBox("Multiple axis");
    filterPanel.add(multAxisCB, gbc);
    gbc.gridy++;

    final JCheckBox showEnvelopeCB = new JCheckBox("Show envelope (all algorithms, SLOW)");
    filterPanel.add(showEnvelopeCB, gbc);
    gbc.gridy++;

    final JXButton showModelButton = new JXButton("Show the model");
    filterPanel.add(showModelButton, gbc);
    gbc.gridy++;

    showModelButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            final JXFrame dialog = new JXFrame();
            dialog.setTitle("Model");
            LogoHelper.setLogo(dialog);
            dialog.getContentPane().removeAll();
            dialog.getContentPane().setLayout(new BorderLayout());
            final JTextPane modelTxtPane = new JTextPane();
            modelTxtPane.setText(gapFiller.getModel());
            modelTxtPane.setBackground(Color.WHITE);
            modelTxtPane.setEditable(false);
            final JScrollPane jsp = new JScrollPane(modelTxtPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            jsp.setSize(new Dimension(400 - 20, 400 - 20));
            dialog.getContentPane().add(jsp, BorderLayout.CENTER);
            dialog.setSize(new Dimension(400, 400));
            dialog.setLocationRelativeTo(centerPanel);
            dialog.pack();
            dialog.setVisible(true);
        }
    });

    algoCombo.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
                showModelButton.setEnabled(gapFiller.hasExplicitModel());
            } catch (final Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    timeSeriesList.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(final ListSelectionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
                mapPanel.removeAll();
                final List<String> currentlySelected = new ArrayList<String>();
                currentlySelected.add(attr.name());
                for (final Object sel : timeSeriesList.getSelectedValues())
                    currentlySelected.add(sel.toString());
                mapPanel.add(gcp.getMapPanel(currentlySelected, attrNames, true), BorderLayout.CENTER);
            } catch (final Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    hideOtherSeriesCB.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
            } catch (final Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    showErrorCB.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    zoomCB.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    showEnvelopeCB.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    multAxisCB.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            try {
                refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()),
                        timeSeriesList.getSelectedIndices(), hideOtherSeriesCB.isSelected(),
                        showErrorCB.isSelected(), zoomCB.isSelected(), showEnvelopeCB.isSelected(),
                        multAxisCB.isSelected());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    this.inBatchMode = inBatchMode;

    if (!inBatchMode) {
        try {
            refresh(Algo.valueOf(algoCombo.getSelectedItem().toString()), new int[0],
                    DEFAULT_HIDE_OTHER_SERIES_OPTION, false, DEFAULT_ZOOM_OPTION, false, false);
            showModelButton.setEnabled(gapFiller.hasExplicitModel());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    if (!inBatchMode) {
        /* automatically select computed series */
        new AbstractSimpleAsync<Void>(true) {
            @Override
            public Void execute() throws Exception {
                mostSimilar = WekaTimeSeriesSimilarityUtil.findMostSimilarTimeSerie(testds, attr, attrNames,
                        false);
                mssLabel.setText("<html>Most similar usable serie: <b>" + mostSimilar + "</b></html>");

                nearest = gcp.findNearestStation(attr.name(), attrNames);
                nsLabel.setText("<html>Nearest usable serie: <b>" + nearest + "</b></html>");

                upstream = gcp.findUpstreamStation(attr.name(), attrNames);
                if (upstream != null) {
                    ussLabel.setText("<html>Upstream usable serie: <b>" + upstream + "</b></html>");
                } else {
                    ussLabel.setText("<html>Upstream usable serie: <b>N/A</b></html>");
                }

                downstream = gcp.findDownstreamStation(attr.name(), attrNames);
                if (downstream != null) {
                    dssLabel.setText("<html>Downstream usable serie: <b>" + downstream + "</b></html>");
                } else {
                    dssLabel.setText("<html>Downstream usable serie: <b>N/A</b></html>");
                }

                timeSeriesList.setSelectedIndices(
                        new int[] { attrNames.indexOf(mostSimilar), attrNames.indexOf(nearest),
                                attrNames.indexOf(upstream), attrNames.indexOf(downstream) });

                return null;
            }

            @Override
            public void onSuccess(final Void result) {
            }

            @Override
            public void onFailure(final Throwable caught) {
                caught.printStackTrace();
            }
        }.start();
    } else {
        try {
            mostSimilar = WekaTimeSeriesSimilarityUtil.findMostSimilarTimeSerie(testds, attr, attrNames, false);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        nearest = gcp.findNearestStation(attr.name(), attrNames);
        upstream = gcp.findUpstreamStation(attr.name(), attrNames);
        downstream = gcp.findDownstreamStation(attr.name(), attrNames);
    }
}

From source file:edu.ku.brc.specify.datamodel.busrules.CollectionObjectBusRules.java

/**
 * Show objects that were not added to the batch
 *///from  w  w  w  .j av  a2  s  . c  o  m
@SuppressWarnings("rawtypes")
protected void showBatchErrorObjects(final Vector<String> badObjects, final String TitleKey,
        final String MsgKey) {
    JPanel pane = new JPanel(new BorderLayout());
    JLabel lbl = createLabel(getResourceString(MsgKey));
    lbl.setBorder(new EmptyBorder(3, 1, 2, 0));
    pane.add(lbl, BorderLayout.NORTH);
    JPanel lstPane = new JPanel(new BorderLayout());
    JList lst = UIHelper.createList(badObjects);
    lst.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
    lstPane.setBorder(new EmptyBorder(1, 1, 10, 1));
    lstPane.add(lst, BorderLayout.CENTER);
    JScrollPane sp = new JScrollPane(lstPane);
    //pane.add(lstPane, BorderLayout.CENTER);
    pane.add(sp, BorderLayout.CENTER);
    //pane.setPreferredSize(new Dimension((int )lbl.getPreferredSize().getWidth() + 5, (int )lst.getPreferredScrollableViewportSize().getHeight() + 5));
    //pane.setPreferredSize(new Dimension((int )lbl.getPreferredSize().getWidth() + 5, (int )lst.getPreferredScrollableViewportSize().getHeight() + 5));
    CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getTopWindow(),
            UIRegistry.getResourceString(TitleKey), true, CustomDialog.OKHELP, pane);
    UIHelper.centerAndShow(dlg);
    dlg.dispose();
}