Example usage for javax.swing JTable JTable

List of usage examples for javax.swing JTable JTable

Introduction

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

Prototype

public JTable(TableModel dm) 

Source Link

Document

Constructs a JTable that is initialized with dm as the data model, a default column model, and a default selection model.

Usage

From source file:BasicDnD.java

public BasicDnD() {
    super(new BorderLayout());
    JPanel leftPanel = createVerticalBoxPanel();
    JPanel rightPanel = createVerticalBoxPanel();

    //Create a table model.
    DefaultTableModel tm = new DefaultTableModel();
    tm.addColumn("Column 0");
    tm.addColumn("Column 1");
    tm.addColumn("Column 2");
    tm.addColumn("Column 3");
    tm.addRow(new String[] { "Table 00", "Table 01", "Table 02", "Table 03" });
    tm.addRow(new String[] { "Table 10", "Table 11", "Table 12", "Table 13" });
    tm.addRow(new String[] { "Table 20", "Table 21", "Table 22", "Table 23" });
    tm.addRow(new String[] { "Table 30", "Table 31", "Table 32", "Table 33" });

    //LEFT COLUMN
    //Use the table model to create a table.
    table = new JTable(tm);
    leftPanel.add(createPanelForComponent(table, "JTable"));

    //Create a color chooser.
    colorChooser = new JColorChooser();
    leftPanel.add(createPanelForComponent(colorChooser, "JColorChooser"));

    //RIGHT COLUMN
    //Create a textfield.
    textField = new JTextField(30);
    textField.setText("Favorite foods:\nPizza, Moussaka, Pot roast");
    rightPanel.add(createPanelForComponent(textField, "JTextField"));

    //Create a scrolled text area.
    textArea = new JTextArea(5, 30);
    textArea.setText("Favorite shows:\nBuffy, Alias, Angel");
    JScrollPane scrollPane = new JScrollPane(textArea);
    rightPanel.add(createPanelForComponent(scrollPane, "JTextArea"));

    //Create a list model and a list.
    DefaultListModel listModel = new DefaultListModel();
    listModel.addElement("Martha Washington");
    listModel.addElement("Abigail Adams");
    listModel.addElement("Martha Randolph");
    listModel.addElement("Dolley Madison");
    listModel.addElement("Elizabeth Monroe");
    listModel.addElement("Louisa Adams");
    listModel.addElement("Emily Donelson");
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    JScrollPane listView = new JScrollPane(list);
    listView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(listView, "JList"));

    //Create a tree.
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Mia Familia");
    DefaultMutableTreeNode sharon = new DefaultMutableTreeNode("Sharon");
    rootNode.add(sharon);/*from ww w.  j a v a  2  s  . c  om*/
    DefaultMutableTreeNode maya = new DefaultMutableTreeNode("Maya");
    sharon.add(maya);
    DefaultMutableTreeNode anya = new DefaultMutableTreeNode("Anya");
    sharon.add(anya);
    sharon.add(new DefaultMutableTreeNode("Bongo"));
    maya.add(new DefaultMutableTreeNode("Muffin"));
    anya.add(new DefaultMutableTreeNode("Winky"));
    DefaultTreeModel model = new DefaultTreeModel(rootNode);
    tree = new JTree(model);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    JScrollPane treeView = new JScrollPane(tree);
    treeView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(treeView, "JTree"));

    //Create the toggle button.
    toggleDnD = new JCheckBox("Turn on Drag and Drop");
    toggleDnD.setActionCommand("toggleDnD");
    toggleDnD.addActionListener(this);

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
    splitPane.setOneTouchExpandable(true);

    add(splitPane, BorderLayout.CENTER);
    add(toggleDnD, BorderLayout.PAGE_END);
    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}

From source file:hr.fer.zemris.vhdllab.platform.ui.wizard.support.PortWizardPage.java

@SuppressWarnings("unchecked")
@Override/* w ww.  ja v  a  2  s  . c  om*/
protected JComponent createControl() {
    model = new BeanTableModel(Port.class, new ArrayList<Port>(), getMessageSource()) {
        private static final long serialVersionUID = 1L;

        @Override
        protected String[] createColumnPropertyNames() {
            return new String[] { "name", "direction", "from", "to" };
        }

        @Override
        protected Class[] createColumnClasses() {
            return new Class[] { String.class, PortDirection.class, Integer.class, Integer.class };
        }

    };
    reporter = new PortValidationReporter(model, this, minimumPortCount, maximumPortCount);
    table = new JTable(model);
    table.setCellSelectionEnabled(true);
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            removeAction.setEnabled(!table.getSelectionModel().isSelectionEmpty());
        }
    });

    final JComboBox inComboBox = new JComboBox(new EnumComboBoxModel(PortDirection.class));
    JTextField portName = new JTextField();

    new ComboBoxAutoCompletion(inComboBox);

    table.getColumnModel().getColumn(0).setPreferredWidth(7);
    table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(portName));
    table.getColumnModel().getColumn(1).setPreferredWidth(120);
    table.getColumnModel().getColumn(2).setCellEditor(new ComboBoxCellEditor(inComboBox));
    table.getColumnModel().getColumn(3).setCellEditor(new NumberEditorExt());
    table.getColumnModel().getColumn(4).setCellEditor(new NumberEditorExt());
    table.setPreferredScrollableViewportSize(new Dimension(300, 200));

    table.addKeyListener(new EditComboBoxKeyHandler());

    JScrollPane scrollPane = new JScrollPane(table);
    JPanel control = new JPanel(new BorderLayout());
    control.add(createButtons(), BorderLayout.NORTH);
    control.add(scrollPane, BorderLayout.CENTER);
    return control;
}

From source file:BasicDnD.java

public BasicDnD() {
    super(new BorderLayout());
    JPanel leftPanel = createVerticalBoxPanel();
    JPanel rightPanel = createVerticalBoxPanel();

    // Create a table model.
    DefaultTableModel tm = new DefaultTableModel();
    tm.addColumn("Column 0");
    tm.addColumn("Column 1");
    tm.addColumn("Column 2");
    tm.addColumn("Column 3");
    tm.addRow(new String[] { "Table 00", "Table 01", "Table 02", "Table 03" });
    tm.addRow(new String[] { "Table 10", "Table 11", "Table 12", "Table 13" });
    tm.addRow(new String[] { "Table 20", "Table 21", "Table 22", "Table 23" });
    tm.addRow(new String[] { "Table 30", "Table 31", "Table 32", "Table 33" });

    // LEFT COLUMN
    // Use the table model to create a table.
    table = new JTable(tm);
    leftPanel.add(createPanelForComponent(table, "JTable"));

    // Create a color chooser.
    colorChooser = new JColorChooser();
    leftPanel.add(createPanelForComponent(colorChooser, "JColorChooser"));

    // RIGHT COLUMN
    // Create a textfield.
    textField = new JTextField(30);
    textField.setText("Favorite foods:\nPizza, Moussaka, Pot roast");
    rightPanel.add(createPanelForComponent(textField, "JTextField"));

    // Create a scrolled text area.
    textArea = new JTextArea(5, 30);
    textArea.setText("Favorite shows:\nBuffy, Alias, Angel");
    JScrollPane scrollPane = new JScrollPane(textArea);
    rightPanel.add(createPanelForComponent(scrollPane, "JTextArea"));

    // Create a list model and a list.
    DefaultListModel listModel = new DefaultListModel();
    listModel.addElement("Martha Washington");
    listModel.addElement("Abigail Adams");
    listModel.addElement("Martha Randolph");
    listModel.addElement("Dolley Madison");
    listModel.addElement("Elizabeth Monroe");
    listModel.addElement("Louisa Adams");
    listModel.addElement("Emily Donelson");
    list = new JList(listModel);
    list.setVisibleRowCount(-1);/*  w  ww  .  j  av  a 2  s.  com*/
    list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    list.setTransferHandler(new TransferHandler() {

        public boolean canImport(TransferHandler.TransferSupport info) {
            // we only import Strings
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            if (dl.getIndex() == -1) {
                return false;
            }
            return true;
        }

        public boolean importData(TransferHandler.TransferSupport info) {
            if (!info.isDrop()) {
                return false;
            }

            // Check for String flavor
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                displayDropLocation("List doesn't accept a drop of this type.");
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            DefaultListModel listModel = (DefaultListModel) list.getModel();
            int index = dl.getIndex();
            boolean insert = dl.isInsert();
            // Get the current string under the drop.
            String value = (String) listModel.getElementAt(index);

            // Get the string that is being dropped.
            Transferable t = info.getTransferable();
            String data;
            try {
                data = (String) t.getTransferData(DataFlavor.stringFlavor);
            } catch (Exception e) {
                return false;
            }

            // Display a dialog with the drop information.
            String dropValue = "\"" + data + "\" dropped ";
            if (dl.isInsert()) {
                if (dl.getIndex() == 0) {
                    displayDropLocation(dropValue + "at beginning of list");
                } else if (dl.getIndex() >= list.getModel().getSize()) {
                    displayDropLocation(dropValue + "at end of list");
                } else {
                    String value1 = (String) list.getModel().getElementAt(dl.getIndex() - 1);
                    String value2 = (String) list.getModel().getElementAt(dl.getIndex());
                    displayDropLocation(dropValue + "between \"" + value1 + "\" and \"" + value2 + "\"");
                }
            } else {
                displayDropLocation(dropValue + "on top of " + "\"" + value + "\"");
            }

            /**
             * This is commented out for the basicdemo.html tutorial page. * If you
             * add this code snippet back and delete the * "return false;" line, the
             * list will accept drops * of type string. // Perform the actual
             * import. if (insert) { listModel.add(index, data); } else {
             * listModel.set(index, data); } return true;
             */
            return false;
        }

        public int getSourceActions(JComponent c) {
            return COPY;
        }

        protected Transferable createTransferable(JComponent c) {
            JList list = (JList) c;
            Object[] values = list.getSelectedValues();

            StringBuffer buff = new StringBuffer();

            for (int i = 0; i < values.length; i++) {
                Object val = values[i];
                buff.append(val == null ? "" : val.toString());
                if (i != values.length - 1) {
                    buff.append("\n");
                }
            }
            return new StringSelection(buff.toString());
        }
    });
    list.setDropMode(DropMode.ON_OR_INSERT);

    JScrollPane listView = new JScrollPane(list);
    listView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(listView, "JList"));

    // Create a tree.
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Mia Familia");
    DefaultMutableTreeNode sharon = new DefaultMutableTreeNode("Sharon");
    rootNode.add(sharon);
    DefaultMutableTreeNode maya = new DefaultMutableTreeNode("Maya");
    sharon.add(maya);
    DefaultMutableTreeNode anya = new DefaultMutableTreeNode("Anya");
    sharon.add(anya);
    sharon.add(new DefaultMutableTreeNode("Bongo"));
    maya.add(new DefaultMutableTreeNode("Muffin"));
    anya.add(new DefaultMutableTreeNode("Winky"));
    DefaultTreeModel model = new DefaultTreeModel(rootNode);
    tree = new JTree(model);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    JScrollPane treeView = new JScrollPane(tree);
    treeView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(treeView, "JTree"));

    // Create the toggle button.
    toggleDnD = new JCheckBox("Turn on Drag and Drop");
    toggleDnD.setActionCommand("toggleDnD");
    toggleDnD.addActionListener(this);

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
    splitPane.setOneTouchExpandable(true);

    add(splitPane, BorderLayout.CENTER);
    add(toggleDnD, BorderLayout.PAGE_END);
    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}

From source file:edu.ku.brc.specify.utilapps.sp5utils.SchemaLocaleUpdater.java

@Override
public void createUI() {
    super.createUI();

    CellConstraints cc = new CellConstraints();

    PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "p,2px,f:p:g,4px,p"));

    table = new JTable(tblModel = new FieldsModel());

    pb.add(UIHelper.createScrollPane(table), cc.xy(1, 3));

    PanelBuilder pbBtn = new PanelBuilder(new FormLayout("f:p:g,p,4px,p,4px,p", "p"));
    pbBtn.add(hideAll = UIHelper.createButton("Hide All"), cc.xy(2, 1));
    pbBtn.add(showAll = UIHelper.createButton("Show All"), cc.xy(4, 1));
    pbBtn.add(showSp5Items = UIHelper.createButton("Show Sp5 Fields"), cc.xy(6, 1));
    pb.add(pbBtn.getPanel(), cc.xy(1, 5));

    pb.setDefaultDialogBorder();/* ww  w.  j  a  v a  2s.  c  o m*/

    contentPanel = pb.getPanel();
    mainPanel.add(contentPanel, BorderLayout.CENTER);

    hideAll.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            for (FormFieldInfo ffi : fields) {
                ffi.setIsHidden(true);
            }
            tblModel.fireTableDataChanged();
        }
    });

    showAll.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            for (FormFieldInfo ffi : fields) {
                ffi.setIsHidden(false);
            }
            tblModel.fireTableDataChanged();
        }
    });

    showSp5Items.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            for (FormFieldInfo ffi : fields) {
                if (ffi.getSp5FieldName() != null) {
                    ffi.setIsHidden(false);
                }
            }
            tblModel.fireTableDataChanged();
        }
    });
}

From source file:com.att.aro.ui.view.menu.file.BPVideoWarnFailPanel.java

private JTable getTable() {
    if (table == null) {
        model = new VideoPreferenceTableModel(loadPrefs());
        table = new JTable(model);
        table.setGridColor(Color.LIGHT_GRAY);
        table.setFocusable(false);/* ww  w  . j  a  v a2  s .  c  o m*/
        table.setRowSelectionAllowed(false);
        table.setShowGrid(true);
        table.getTableHeader().setFont(new Font("SansSerif", Font.BOLD, 12));
        table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
        table.getColumnModel().getColumn(0).setPreferredWidth(225);
        table.getColumnModel().getColumn(1).setPreferredWidth(50);
        table.getColumnModel().getColumn(2).setPreferredWidth(50);
        table.getModel().addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                sError = model.getValidationError();
                if (!sError.toString().isEmpty()) {
                    compileResultsField.setVisible(true);
                    compileResultsField.setForeground(Color.red);
                    compileResultsField.setText(String.format("ERROR : %s", sError.toString()));
                } else {
                    compileResultsField.setText("");
                    compileResultsField.setVisible(false);
                }
            }
        });
    } else {
        model.setData(loadPrefs());
        table.setModel(model);
    }
    return table;
}

From source file:logdruid.ui.table.StatRecordingEditorTable.java

public StatRecordingEditorTable(Repository repo, Recording re, JTextPane textPane) {
    super(new GridLayout(1, 0));
    this.examplePane = textPane;
    model = new MyTableModel(data, header);
    table = new JTable(model);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setFillsViewportHeight(true);/*from w ww.j ava  2  s.c o  m*/
    rep = repo;
    this.theLine = textPane.getText();
    recording = re;
    // Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    // Set up column sizes.
    initColumnSizes(table);
    // Fiddle with the Type column's cell editors/renderers.
    setUpTypeColumn(table, table.getColumnModel().getColumn(2));
    // Add the scroll pane to this panel.
    add(scrollPane);

    if (re.getClass() == EventRecording.class) {
        records = ((EventRecording) re).getRecordingItem();
    } else if (re.getClass() == StatRecording.class) {
        records = ((StatRecording) re).getRecordingItem();
    } else if (re.getClass() == MetadataRecording.class) {
        records = ((MetadataRecording) re).getRecordingItem();
    }
    // Collections.sort(records);
    if (records != null) {
        Iterator it = records.iterator();

        while (it.hasNext()) {
            RecordingItem rI = (RecordingItem) it.next();
            data.add(new Object[] { rI.getName(), rI.getBefore(), rI.getType(), rI.getAfter(), rI.isSelected(),
                    "" });
        }
        FixValues();
    }
}

From source file:JTop.java

public JTop() {
    super(new GridLayout(1, 0));

    tmodel = new MyTableModel();
    JTable table = new JTable(tmodel);
    table.setPreferredScrollableViewportSize(new Dimension(500, 300));

    // Set the renderer to format Double
    table.setDefaultRenderer(Double.class, new DoubleRenderer());
    // Add some space
    table.setIntercellSpacing(new Dimension(6, 3));
    table.setRowHeight(table.getRowHeight() + 4);

    // Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);

    // Add the scroll pane to this panel.
    add(scrollPane);/*from   w  ww. j  av a2 s  .  c o  m*/
}

From source file:joinery.impl.Display.java

public static <V> void show(final DataFrame<V> df) {
    final List<Object> columns = new ArrayList<>(df.columns());
    final List<Class<?>> types = df.types();
    SwingUtilities.invokeLater(new Runnable() {
        @Override/*from w w  w .j a  v a  2  s  .com*/
        public void run() {
            final JFrame frame = new JFrame(title(df));
            final JTable table = new JTable(new AbstractTableModel() {
                private static final long serialVersionUID = 1L;

                @Override
                public int getRowCount() {
                    return df.length();
                }

                @Override
                public int getColumnCount() {
                    return df.size();
                }

                @Override
                public Object getValueAt(final int row, final int col) {
                    return df.get(row, col);
                }

                @Override
                public String getColumnName(final int col) {
                    return String.valueOf(columns.get(col));
                }

                @Override
                public Class<?> getColumnClass(final int col) {
                    return types.get(col);
                }
            });
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.add(new JScrollPane(table));
            frame.pack();
            frame.setVisible(true);
        }
    });
}

From source file:edu.ku.brc.af.ui.forms.formatters.DataObjFieldFormatMultiplePanel.java

protected void buildUI() {
    CellConstraints cc = new CellConstraints();
    PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "10px,f:130px:g,10px,p,15px"), this);

    formatSwitchTbl = new JTable(new DefaultTableModel());
    formatSwitchTbl.getSelectionModel().addListSelectionListener(new RowListener());
    addTableModelListener((DefaultTableModel) formatSwitchTbl.getModel());
    fillWithObjFormatter(null);/*  ww  w  .ja  va  2  s .  c  om*/

    // tool bar to host the add and delete buttons
    createToolbar();

    // lay out components on main panel
    JScrollPane sp = UIHelper.createScrollPane(formatSwitchTbl);
    // set minimum and preferred sizes so that table shrinks with the dialog
    sp.setMinimumSize(new Dimension(50, 5));
    sp.setPreferredSize(new Dimension(50, 5));

    pb.add(sp, cc.xy(1, 2));
    pb.add(controlPanel, cc.xy(1, 4));
    this.mainPanelBuilder = pb;
}

From source file:org.angnysa.yaba.swing.BudgetFrame.java

private void buildTransactionTable() {
    transactionModel = new TransactionTableModel(service);
    transactionTable = new JTable(transactionModel);
    transactionTable.setRowHeight((int) (transactionTable.getRowHeight() * 1.2));
    transactionTable.getColumnModel().getColumn(TransactionTableModel.COL_END)
            .setCellEditor(new CustomCellEditor(
                    new JFormattedTextField(new OptionalValueFormatter(new JodaLocalDateFormat()))));
    transactionTable.setDefaultEditor(LocalDate.class,
            new CustomCellEditor(new JFormattedTextField(new JodaLocalDateFormat())));
    transactionTable.setDefaultEditor(ReadablePeriod.class,
            new CustomCellEditor(new JFormattedTextField(new OptionalValueFormatter(new JodaPeriodFormat()))));
    transactionTable.setDefaultEditor(Double.class,
            new CustomCellEditor(new JFormattedTextField(NumberFormat.getNumberInstance())));
    transactionTable.setDefaultRenderer(LocalDate.class,
            new FormattedTableCellRenderer(new JodaLocalDateFormat()));
    transactionTable.setDefaultRenderer(ReadablePeriod.class,
            new FormattedTableCellRenderer(new JodaPeriodFormat()));
    transactionTable.setDefaultRenderer(Double.class,
            new FormattedTableCellRenderer(TransactionAmountFormatFactory.getFormat()));
    transactionTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    transactionTable.setAutoCreateRowSorter(true);
    transactionTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
            .put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete"); //$NON-NLS-1$
    transactionTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
            .put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); //$NON-NLS-1$
    transactionTable.getActionMap().put("delete", new AbstractAction() { //$NON-NLS-1$
        private static final long serialVersionUID = 1L;

        @Override//w ww .j  a va  2  s.  co  m
        public void actionPerformed(ActionEvent e) {

            int row = transactionTable.getSelectedRow();
            if (row >= 0) {
                row = transactionTable.getRowSorter().convertRowIndexToModel(row);
                transactionModel.deleteRow(row);
            }
        }
    });
}