Example usage for javax.swing Box createGlue

List of usage examples for javax.swing Box createGlue

Introduction

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

Prototype

public static Component createGlue() 

Source Link

Document

Creates an invisible "glue" component that can be useful in a Box whose visible components have a maximum width (for a horizontal box) or height (for a vertical box).

Usage

From source file:components.Converter.java

/**
 * Create the ConversionPanels (one for metric, another for U.S.).
 * I used "U.S." because although Imperial and U.S. distance
 * measurements are the same, this program could be extended to
 * include volume measurements, which aren't the same.
 *///www.  java2s .co  m
public Converter() {
    //Create Unit objects for metric distances, and then
    //instantiate a ConversionPanel with these Units.
    metricDistances[0] = new Unit("Centimeters", 0.01);
    metricDistances[1] = new Unit("Meters", 1.0);
    metricDistances[2] = new Unit("Kilometers", 1000.0);
    metricPanel = new ConversionPanel(this, "Metric System", metricDistances, dataModel);

    //Create Unit objects for U.S. distances, and then
    //instantiate a ConversionPanel with these Units.
    usaDistances[0] = new Unit("Inches", 0.0254);
    usaDistances[1] = new Unit("Feet", 0.305);
    usaDistances[2] = new Unit("Yards", 0.914);
    usaDistances[3] = new Unit("Miles", 1613.0);
    usaPanel = new ConversionPanel(this, "U.S. System", usaDistances, new FollowerRangeModel(dataModel));

    //Create a JPanel, and add the ConversionPanels to it.
    mainPane = new JPanel();
    mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.PAGE_AXIS));
    if (MULTICOLORED) {
        mainPane.setOpaque(true);
        mainPane.setBackground(new Color(255, 0, 0));
    }
    mainPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
    mainPane.add(metricPanel);
    mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
    mainPane.add(usaPanel);
    mainPane.add(Box.createGlue());
    resetMaxValues(true);
}

From source file:UndoableToggleApp4.java

public UndoableToggleApp4() {

    // Create some toggle buttons (and subclasses).
    tog = new JToggleButton("ToggleButton");
    cb = new JCheckBox("CheckBox");
    radio = new JRadioButton("RadioButton");

    // Add our listener to the buttons.
    SimpleListener sl = new SimpleListener();
    tog.addActionListener(sl);//  w  w w .j  a  v  a  2s . co  m
    cb.addActionListener(sl);
    radio.addActionListener(sl);

    // Lay out the buttons.
    Box buttonBox = new Box(BoxLayout.Y_AXIS);
    buttonBox.add(tog);
    buttonBox.add(cb);
    buttonBox.add(radio);

    // Create undo, redo, start, and end buttons.
    startButton = new JButton("Start");
    endButton = new JButton("End");
    undoButton = new JButton("Undo");
    redoButton = new JButton("Redo");
    startButton.setEnabled(true);
    endButton.setEnabled(false);
    undoButton.setEnabled(false);
    redoButton.setEnabled(false);

    // Add a listener to the start button. It creates a new StateEdit,
    // passing in this frame as the StateEditable.
    startButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            edit = new StateEdit(UndoableToggleApp4.this);
            startButton.setEnabled(false);
            endButton.setEnabled(true);
            //undoButton.setEnabled(edit.canUndo());
            //
            // NOTE: We really don't want to be able to undo until end() is
            // pressed,
            // but StateEdit does not enforce this for us!
            undoButton.setEnabled(false);
            redoButton.setEnabled(edit.canRedo());
        }
    });

    // Add a listener to the end button. It will call end() on the
    // StateEdit.
    endButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            edit.end();
            startButton.setEnabled(true);
            endButton.setEnabled(false);
            undoButton.setEnabled(edit.canUndo());
            redoButton.setEnabled(edit.canRedo());
        }
    });

    // Add a listener to the undo button. It attempts to call undo() on the
    // current edit, then enables/disables the undo/redo buttons as
    // appropriate.
    undoButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            try {
                edit.undo();
            } catch (CannotUndoException ex) {
                ex.printStackTrace();
            } finally {
                undoButton.setEnabled(edit.canUndo());
                redoButton.setEnabled(edit.canRedo());
            }
        }
    });

    // Add a redo listener: just like the undo listener.
    redoButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            try {
                edit.redo();
            } catch (CannotRedoException ex) {
                ex.printStackTrace();
            } finally {
                undoButton.setEnabled(edit.canUndo());
                redoButton.setEnabled(edit.canRedo());
            }
        }
    });

    // Lay out the state/end and undo/redo buttons.
    Box undoRedoBox = new Box(BoxLayout.X_AXIS);
    undoRedoBox.add(Box.createGlue());
    undoRedoBox.add(startButton);
    undoRedoBox.add(Box.createHorizontalStrut(2));
    undoRedoBox.add(endButton);
    undoRedoBox.add(Box.createHorizontalStrut(2));
    undoRedoBox.add(undoButton);
    undoRedoBox.add(Box.createHorizontalStrut(2));
    undoRedoBox.add(redoButton);
    undoRedoBox.add(Box.createGlue());

    // Lay out the main frame.
    Container content = getContentPane();
    content.setLayout(new BorderLayout());
    content.add(buttonBox, BorderLayout.CENTER);
    content.add(undoRedoBox, BorderLayout.SOUTH);
    setSize(400, 150);
}

From source file:IconDemoApp.java

/**
 * Default constructor for the demo./*w w  w .  j  a v a  2 s . c  o m*/
 */
public IconDemoApp() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("Icon Demo: Please Select an Image");

    // A label for displaying the pictures
    photographLabel.setVerticalTextPosition(JLabel.BOTTOM);
    photographLabel.setHorizontalTextPosition(JLabel.CENTER);
    photographLabel.setHorizontalAlignment(JLabel.CENTER);
    photographLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    // We add two glue components. Later in process() we will add thumbnail
    // buttons
    // to the toolbar inbetween thease glue compoents. This will center the
    // buttons in the toolbar.
    buttonBar.add(Box.createGlue());
    buttonBar.add(Box.createGlue());

    add(buttonBar, BorderLayout.SOUTH);
    add(photographLabel, BorderLayout.CENTER);

    setSize(400, 300);

    // this centers the frame on the screen
    setLocationRelativeTo(null);

    // start the image loading SwingWorker in a background thread
    loadimages.execute();
}

From source file:components.IconDemoApp.java

/**
 * Default constructor for the demo./*from   w ww .j a v  a 2  s  .  co  m*/
 */
public IconDemoApp() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("Icon Demo: Please Select an Image");

    // A label for displaying the pictures
    photographLabel.setVerticalTextPosition(JLabel.BOTTOM);
    photographLabel.setHorizontalTextPosition(JLabel.CENTER);
    photographLabel.setHorizontalAlignment(JLabel.CENTER);
    photographLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    // We add two glue components. Later in process() we will add thumbnail buttons
    // to the toolbar inbetween thease glue compoents. This will center the
    // buttons in the toolbar.
    buttonBar.add(Box.createGlue());
    buttonBar.add(Box.createGlue());

    add(buttonBar, BorderLayout.SOUTH);
    add(photographLabel, BorderLayout.CENTER);

    setSize(400, 300);

    // this centers the frame on the screen
    setLocationRelativeTo(null);

    // start the image loading SwingWorker in a background thread
    loadimages.execute();
}

From source file:Converter.java

/**
 * Create the ConversionPanels (one for metric, another for U.S.). I used
 * "U.S." because although Imperial and U.S. distance measurements are the
 * same, this program could be extended to include volume measurements, which
 * aren't the same.//from  w  ww .  j av  a  2 s.co  m
 */
public Converter() {
    // Create Unit objects for metric distances, and then
    // instantiate a ConversionPanel with these Units.
    metricDistances[0] = new Unit("Centimeters", 0.01);
    metricDistances[1] = new Unit("Meters", 1.0);
    metricDistances[2] = new Unit("Kilometers", 1000.0);
    metricPanel = new ConversionPanel(this, "Metric System", metricDistances, dataModel);

    // Create Unit objects for U.S. distances, and then
    // instantiate a ConversionPanel with these Units.
    usaDistances[0] = new Unit("Inches", 0.0254);
    usaDistances[1] = new Unit("Feet", 0.305);
    usaDistances[2] = new Unit("Yards", 0.914);
    usaDistances[3] = new Unit("Miles", 1613.0);
    usaPanel = new ConversionPanel(this, "U.S. System", usaDistances, new FollowerRangeModel(dataModel));

    // Create a JPanel, and add the ConversionPanels to it.
    mainPane = new JPanel();
    mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.PAGE_AXIS));
    if (MULTICOLORED) {
        mainPane.setOpaque(true);
        mainPane.setBackground(new Color(255, 0, 0));
    }
    mainPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
    mainPane.add(metricPanel);
    mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
    mainPane.add(usaPanel);
    mainPane.add(Box.createGlue());
    resetMaxValues(true);
}

From source file:com.intel.stl.ui.common.view.DistributionPiePanel.java

public void setLabels(String[] itemNames, ImageIcon[] icons, int labelColumns) {
    if (icons.length != itemNames.length) {
        throw new IllegalArgumentException(
                "Inconsistent number of items. " + " itemNames=" + itemNames.length + " icons=" + icons.length);
    }// w  w  w .j a v a 2s .c o  m

    labels = new JLabel[icons.length];
    for (int i = 0; i < icons.length; i++) {
        labels[i] = new JLabel(itemNames[i], icons[i], JLabel.LEFT);
    }

    int rows = 1;
    if (labelColumns <= 0) {
        labelPanel.setLayout(new FlowLayout());
        for (JLabel label : labels) {
            labelPanel.add(label);
        }
    } else {
        BoxLayout layout = new BoxLayout(labelPanel, BoxLayout.X_AXIS);
        labelPanel.setLayout(layout);
        JPanel[] columns = new JPanel[labelColumns];
        for (int i = 0; i < columns.length; i++) {
            labelPanel.add(Box.createHorizontalGlue());
            columns[i] = new JPanel();
            columns[i].setOpaque(false);
            columns[i].setBorder(BorderFactory.createEmptyBorder(2, 3, 2, 3));
            BoxLayout cLayout = new BoxLayout(columns[i], BoxLayout.Y_AXIS);
            columns[i].setLayout(cLayout);
            labelPanel.add(columns[i]);
        }
        labelPanel.add(Box.createHorizontalGlue());
        rows = (int) Math.ceil((double) labels.length / labelColumns);
        int index = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < labelColumns; j++) {
                columns[i].add(index < labels.length ? labels[index] : Box.createGlue());
                index += 1;
            }
        }
    }
}

From source file:com.igormaznitsa.sciareto.ui.MainFrame.java

public MainFrame(@Nonnull @MustNotContainNull final String... args) {
    super();/* w w  w.jav a 2 s. c om*/
    initComponents();

    this.stackPanel = new JPanel();
    this.stackPanel.setFocusable(false);
    this.stackPanel.setOpaque(false);
    this.stackPanel.setBorder(BorderFactory.createEmptyBorder(32, 32, 16, 32));
    this.stackPanel.setLayout(new BoxLayout(this.stackPanel, BoxLayout.Y_AXIS));

    final JPanel glassPanel = (JPanel) this.getGlassPane();
    glassPanel.setOpaque(false);

    this.setGlassPane(glassPanel);

    glassPanel.setLayout(new BorderLayout(8, 8));
    glassPanel.add(Box.createGlue(), BorderLayout.CENTER);

    final JPanel ppanel = new JPanel(new BorderLayout(0, 0));
    ppanel.setFocusable(false);
    ppanel.setOpaque(false);
    ppanel.setCursor(null);
    ppanel.add(this.stackPanel, BorderLayout.SOUTH);

    glassPanel.add(ppanel, BorderLayout.EAST);

    this.stackPanel.add(Box.createGlue());

    glassPanel.setVisible(false);

    this.setTitle("Scia Reto");

    setIconImage(UiUtils.loadImage("logo256x256.png"));

    this.stateless = args.length > 0;

    final MainFrame theInstance = this;

    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(@Nonnull final WindowEvent e) {
            if (doClosing()) {
                dispose();
            }
        }
    });

    this.tabPane = new EditorTabPane(this);

    this.explorerTree = new ExplorerTree(this);

    final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(250);
    splitPane.setResizeWeight(0.0d);
    splitPane.setLeftComponent(this.explorerTree);
    splitPane.setRightComponent(this.tabPane);

    add(splitPane, BorderLayout.CENTER);

    this.menuOpenRecentProject.addMenuListener(new MenuListener() {
        @Override
        public void menuSelected(MenuEvent e) {
            final File[] lastOpenedProjects = FileHistoryManager.getInstance().getLastOpenedProjects();
            if (lastOpenedProjects.length > 0) {
                for (final File folder : lastOpenedProjects) {
                    final JMenuItem item = new JMenuItem(folder.getName());
                    item.setToolTipText(folder.getAbsolutePath());
                    item.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            openProject(folder, false);
                        }
                    });
                    menuOpenRecentProject.add(item);
                }
            }
        }

        @Override
        public void menuDeselected(MenuEvent e) {
            menuOpenRecentProject.removeAll();
        }

        @Override
        public void menuCanceled(MenuEvent e) {
        }
    });

    this.menuOpenRecentFile.addMenuListener(new MenuListener() {
        @Override
        public void menuSelected(MenuEvent e) {
            final File[] lastOpenedFiles = FileHistoryManager.getInstance().getLastOpenedFiles();
            if (lastOpenedFiles.length > 0) {
                for (final File file : lastOpenedFiles) {
                    final JMenuItem item = new JMenuItem(file.getName());
                    item.setToolTipText(file.getAbsolutePath());
                    item.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            openFileAsTab(file);
                        }
                    });
                    menuOpenRecentFile.add(item);
                }
            }
        }

        @Override
        public void menuDeselected(MenuEvent e) {
            menuOpenRecentFile.removeAll();
        }

        @Override
        public void menuCanceled(MenuEvent e) {
        }
    });

    if (!this.stateless) {
        restoreState();
    } else {
        boolean openedProject = false;
        for (final String filePath : args) {
            final File file = new File(filePath);
            if (file.isDirectory()) {
                openedProject = true;
                openProject(file, true);
            } else if (file.isFile()) {
                openFileAsTab(file);
            }
        }
        if (!openedProject) {
            //TODO try to hide project panel!
        }
    }

    final LookAndFeel current = UIManager.getLookAndFeel();
    final ButtonGroup lfGroup = new ButtonGroup();
    final String currentLFClassName = current.getClass().getName();
    for (final UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
        final JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem(info.getName());
        lfGroup.add(menuItem);
        if (currentLFClassName.equals(info.getClassName())) {
            menuItem.setSelected(true);
        }
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(@Nonnull final ActionEvent e) {
                try {
                    UIManager.setLookAndFeel(info.getClassName());
                    SwingUtilities.updateComponentTreeUI(theInstance);
                    PreferencesManager.getInstance().getPreferences().put(Main.PROPERTY_LOOKANDFEEL,
                            info.getClassName());
                    PreferencesManager.getInstance().flush();
                } catch (Exception ex) {
                    LOGGER.error("Can't change LF", ex);
                }
            }
        });
        this.menuLookAndFeel.add(menuItem);
    }
}

From source file:edu.gmu.cs.sim.util.media.chart.XYChartGenerator.java

protected void buildGlobalAttributes(LabelledList list) {

    // create the chart
    ((XYPlot) (chart.getPlot())).setDomainGridlinesVisible(false);
    ((XYPlot) (chart.getPlot())).setRangeGridlinesVisible(false);
    ((XYPlot) (chart.getPlot())).setDomainGridlinePaint(new Color(200, 200, 200));
    ((XYPlot) (chart.getPlot())).setRangeGridlinePaint(new Color(200, 200, 200));

    xLabel = new PropertyField() {
        public String newValue(String newValue) {
            setXAxisLabel(newValue);/*from  www.  j a  v a  2s .c  o  m*/
            getChartPanel().repaint();
            return newValue;
        }
    };
    xLabel.setValue(getXAxisLabel());

    list.add(new JLabel("X Label"), xLabel);

    yLabel = new PropertyField() {
        public String newValue(String newValue) {
            setYAxisLabel(newValue);
            getChartPanel().repaint();
            return newValue;
        }
    };
    yLabel.setValue(getYAxisLabel());

    list.add(new JLabel("Y Label"), yLabel);

    xLog = new JCheckBox();
    xLog.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            if (xLog.isSelected()) {
                LogarithmicAxis logAxis = new LogarithmicAxis(xLabel.getValue());
                logAxis.setStrictValuesFlag(false);
                chart.getXYPlot().setDomainAxis(logAxis);
            } else {
                chart.getXYPlot().setDomainAxis(new NumberAxis(xLabel.getValue()));
            }
        }
    });

    yLog = new JCheckBox();
    yLog.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            if (yLog.isSelected()) {
                LogarithmicAxis logAxis = new LogarithmicAxis(yLabel.getValue());
                logAxis.setStrictValuesFlag(false);
                chart.getXYPlot().setRangeAxis(logAxis);
            } else {
                chart.getXYPlot().setRangeAxis(new NumberAxis(yLabel.getValue()));
            }
        }
    });

    Box box = Box.createHorizontalBox();
    box.add(new JLabel("X"));
    box.add(xLog);
    box.add(new JLabel(" Y"));
    box.add(yLog);
    box.add(Box.createGlue());
    list.add(new JLabel("Log Axis"), box);

    final JCheckBox xgridlines = new JCheckBox();
    xgridlines.setSelected(false);
    ItemListener il = new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                chart.getXYPlot().setDomainGridlinesVisible(true);
            } else {
                chart.getXYPlot().setDomainGridlinesVisible(false);
            }
        }
    };
    xgridlines.addItemListener(il);

    final JCheckBox ygridlines = new JCheckBox();
    ygridlines.setSelected(false);
    il = new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                chart.getXYPlot().setRangeGridlinesVisible(true);
            } else {
                chart.getXYPlot().setRangeGridlinesVisible(false);
            }
        }
    };
    ygridlines.addItemListener(il);

    box = Box.createHorizontalBox();
    box.add(new JLabel("X"));
    box.add(xgridlines);
    box.add(new JLabel(" Y"));
    box.add(ygridlines);
    box.add(Box.createGlue());
    list.add(new JLabel("Grid Lines"), box);
}

From source file:sim.util.media.chart.XYChartGenerator.java

protected void buildGlobalAttributes(LabelledList list) {

    // create the chart
    ((XYPlot) (chart.getPlot())).setDomainGridlinesVisible(false);
    ((XYPlot) (chart.getPlot())).setRangeGridlinesVisible(false);
    ((XYPlot) (chart.getPlot())).setDomainGridlinePaint(new Color(200, 200, 200));
    ((XYPlot) (chart.getPlot())).setRangeGridlinePaint(new Color(200, 200, 200));

    xLabel = new PropertyField() {
        public String newValue(String newValue) {
            setXAxisLabel(newValue);/*  ww  w .  j av a2 s .c o m*/
            getChartPanel().repaint();
            return newValue;
        }
    };
    xLabel.setValue(getXAxisLabel());

    list.add(new JLabel("X Label"), xLabel);

    yLabel = new PropertyField() {
        public String newValue(String newValue) {
            setYAxisLabel(newValue);
            getChartPanel().repaint();
            return newValue;
        }
    };
    yLabel.setValue(getYAxisLabel());

    list.add(new JLabel("Y Label"), yLabel);

    xLog = new JCheckBox();
    xLog.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            if (xLog.isSelected()) {
                LogarithmicAxis logAxis = new LogarithmicAxis(xLabel.getValue());
                logAxis.setStrictValuesFlag(false);
                chart.getXYPlot().setDomainAxis(logAxis);
            } else
                chart.getXYPlot().setDomainAxis(new NumberAxis(xLabel.getValue()));
        }
    });

    yLog = new JCheckBox();
    yLog.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            if (yLog.isSelected()) {
                LogarithmicAxis logAxis = new LogarithmicAxis(yLabel.getValue());
                logAxis.setStrictValuesFlag(false);
                chart.getXYPlot().setRangeAxis(logAxis);
            } else
                chart.getXYPlot().setRangeAxis(new NumberAxis(yLabel.getValue()));
        }
    });

    Box box = Box.createHorizontalBox();
    box.add(new JLabel("X"));
    box.add(xLog);
    box.add(new JLabel(" Y"));
    box.add(yLog);
    box.add(Box.createGlue());
    list.add(new JLabel("Log Axis"), box);

    final JCheckBox xgridlines = new JCheckBox();
    xgridlines.setSelected(false);
    ItemListener il = new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                chart.getXYPlot().setDomainGridlinesVisible(true);
            } else {
                chart.getXYPlot().setDomainGridlinesVisible(false);
            }
        }
    };
    xgridlines.addItemListener(il);

    final JCheckBox ygridlines = new JCheckBox();
    ygridlines.setSelected(false);
    il = new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                chart.getXYPlot().setRangeGridlinesVisible(true);
            } else {
                chart.getXYPlot().setRangeGridlinesVisible(false);
            }
        }
    };
    ygridlines.addItemListener(il);

    box = Box.createHorizontalBox();
    box.add(new JLabel("X"));
    box.add(xgridlines);
    box.add(new JLabel(" Y"));
    box.add(ygridlines);
    box.add(Box.createGlue());
    list.add(new JLabel("Grid Lines"), box);
}

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  ww w . ja  v  a  2 s.  c  o 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));
}