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:table.TablePanel.java

public TablePanel(JPanel parent, GridBagConstraints c) {
    this.parent = parent;
    this.c = c;//from  w  ww  . j a  v a 2 s .c o  m
    dataHandler = null;
    data = new ArrayList<>();
    selectedRows = new ArrayList<>();
    tableModel = new MyTableModel(data);
    table = new JTable(tableModel);
    table.getColumnModel().getColumn(0).setResizable(false);
    table.getColumnModel().getColumn(0).setMaxWidth(60);
    table.getColumnModel().getColumn(1).setResizable(false);
    table.getColumnModel().getColumn(1).setMaxWidth(50);
    table.getColumnModel().getColumn(2).setMaxWidth(90);
    table.getColumnModel().getColumn(49).setMaxWidth(60);
    for (int i = 0; i < tableModel.getColumnCount(); i++) {
        if (i > 14 && i < 31) {
            table.getColumnModel().getColumn(i).setMaxWidth(70);
        } else if (tableModel.columnNamesTemp[i].contains("LEVEL")) {
            if (tableModel.columnNamesTemp[i].equals("QEC LEVEL")) {
                table.getColumnModel().getColumn(i).setMinWidth(90);
                table.getColumnModel().getColumn(i).setMaxWidth(200);
            } else {
                table.getColumnModel().getColumn(i).setMaxWidth(90);
            }
            if (tableModel.columnNamesTemp[i - 1].equals("Work Pace")) {
                table.getColumnModel().getColumn(i - 1).setMinWidth(90);
                table.getColumnModel().getColumn(i - 1).setMaxWidth(150);
            } else {
                table.getColumnModel().getColumn(i - 1).setMaxWidth(90);
            }
        } else {
            // table.getColumnModel().getColumn(i).setMinWidth(120);
            // table.getColumnModel().getColumn(i).setMaxWidth(250);
        }
    }
    table.getColumnModel().getColumn(table.getColumnCount() - 1).setMaxWidth(60);
    table.getColumnModel().getColumn(table.getColumnCount() - 1).setResizable(false);

    table.setRowSelectionAllowed(true);
    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    table.getModel().addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            if (!dataHandler.getDeleting() && (table.getSelectedRow() != -1)
                    && e.getColumn() != table.getColumnCount() - 1 && e.getColumn() != 1) {
                int row = table.getSelectedRow();
                int col = e.getColumn();

                if (col == 0 && (boolean) table.getValueAt(row, col) == true) {
                    if (!selectedRows.contains((Integer) row))
                        selectedRows.add(row);
                } else if (col == 0 && (boolean) table.getValueAt(row, col) == false) {
                    selectedRows.remove((Object) row);
                } else if (col != 0 && (boolean) table.getValueAt(row, table.getColumnCount() - 1)) {
                    dataHandler.dataEdited();
                }
            }
        }
    });

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        private int count = 0;

        @Override
        public void valueChanged(ListSelectionEvent arg0) {
            if (count > 1 && !arg0.getValueIsAdjusting()) {
                int[] draggedRows = table.getSelectedRows();
                for (int i = 0; i < draggedRows.length; i++)
                    if (selectedRows.contains((Integer) draggedRows[i])) {
                        selectedRows.remove((Integer) draggedRows[i]);
                        table.setValueAt(false, draggedRows[i], 0);
                    } else {
                        selectedRows.add((Integer) draggedRows[i]);
                        table.setValueAt(true, draggedRows[i], 0);
                    }
                // Finalize
                count = 0;
            } else if (arg0.getValueIsAdjusting())
                count++;
            else
                count = 0;
        }
    });

    // {
    //
    // @Override
    // public Component prepareRenderer(TableCellRenderer renderer,
    // int row, int column) {
    // JLabel label = (JLabel) super.prepareRenderer(renderer, row, column);
    // if ((boolean) table.getValueAt(row, table.getColumnCount() - 1) ==
    // false) {
    // if ((int) row % 2 == 0) {
    // label.setBackground(new Color(244, 226,215));
    // } else {
    // label.setBackground(new Color(241, 220,205));
    // }
    // } else {
    // if ((int) row% 2 == 0) {
    // label.setBackground(new Color(255, 255, 255));
    // } else {
    // label.setBackground(new Color(252, 252, 252));
    // }
    //
    // }
    // if(table.getSelectedRow()==row)
    // label.setBackground(Color.LIGHT_GRAY);
    // return label;
    // }
    // };
    // table.prepareRenderer(null, WIDTH, WIDTH);
    // table.setRowSelectionAllowed(true);
    // table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    table.setDefaultRenderer(Object.class, new MyTableCellRenderer());

    // {
    //
    // @Override
    // public Component getTableCellRendererComponent(JTable table, Object
    // value, boolean isSelected, boolean hasFocus, int row, int column) {
    // JLabel label = (JLabel) table.prepareRenderer(null, row, column);
    // if ((boolean) table.getValueAt(row, table.getColumnCount() - 1) ==
    // false) {
    // if ((int) row % 2 == 0) {
    // label.setBackground(new Color(244, 226,215));
    // } else {
    // label.setBackground(new Color(241, 220,205));
    // }
    // } else {
    // if ((int) row% 2 == 0) {
    // label.setBackground(new Color(255, 255, 255));
    // } else {
    // label.setBackground(new Color(252, 252, 252));
    // }
    //
    // }
    // if(table.getSelectedRow()==row)
    // label.setBackground(Color.LIGHT_GRAY);
    // return label;
    // }
    // });
    // {
    //
    // @Override
    // public Component getTableCellRendererComponent(JTable table, Object
    // value, boolean isSelected, boolean hasFocus, int row, int column) {
    // Component cell= table.getCellRenderer(row,
    // column).getTableCellRendererComponent(table, value, isSelected,
    // hasFocus, row, column);
    //
    //
    // for(int i=1;i<table.getRowCount();i++) {
    // if((boolean)table.getValueAt(i, table.getColumnCount()-1) ==false)
    // {
    // setForeground(Color.black);
    // setBackground(Color.red);
    // }
    // else
    // {
    // setBackground(Color.white);
    // setForeground(Color.black);
    // }
    // }
    // return cell;
    // }
    // });
    // DefaultTableCellRenderer rightRenderer = new
    // DefaultTableCellRenderer();
    // rightRenderer.setHorizontalAlignment(DefaultTableCellRenderer.RIGHT);
    for (int i = 0; i < tableModel.getColumnCount(); i++) {
        table.getTableHeader().getColumnModel().getColumn(i)
                .setHeaderRenderer(new HeaderRenderer(table, alignments[1]));
        // table.getColumnModel().getColumn(i).setCellRenderer(new
        // MyTableCellRenderer());
    }
    table.getTableHeader().setReorderingAllowed(false);
    table.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    table.setRowHeight(25);
    // table.setPreferredScrollableViewportSize(new Dimension(10000, 200));

    // Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //      JViewport tableView = new JViewport();
    //      tableView.add(table);
    //      scrollPane.setViewport(tableView);
    parent.setSize(table.getWidth(), table.getHeight());
    //      parent.setPreferredSize(new Dimension(70000,10000));
    //      scrollPane.setVerticalScrollBar(new JScrollBar(JScrollBar.VERTICAL));
    //      scrollPane.setHorizontalScrollBar(new JScrollBar(JScrollBar.HORIZONTAL));
    // Add the scroll pane to this panel.
    //      parent.add(table.getTableHeader());
    //      parent.add(table, c);
    // Add header in NORTH slot
    parent.add(table.getTableHeader(), BorderLayout.NORTH);

    // Add table itself to CENTER slot
    parent.add(table, BorderLayout.CENTER);
}

From source file:org.jfree.chart.demo.selection.SelectionDemo6Pie.java

public SelectionDemo6Pie(String title) {
    super(title);
    JPanel chartPanel = createDemoPanel();
    chartPanel.setPreferredSize(new java.awt.Dimension(700, 500));

    JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    split.add(chartPanel);/*from   w  w  w .j  av  a 2 s .  co m*/

    this.model = new DefaultTableModel(new String[] { "section", "value:" }, 0);
    this.table = new JTable(this.model);
    TableColumnModel tcm = this.table.getColumnModel();
    JPanel p = new JPanel(new BorderLayout());
    JScrollPane scroller = new JScrollPane(this.table);
    p.add(scroller);
    p.setBorder(BorderFactory.createCompoundBorder(new TitledBorder("Selected Items: "),
            new EmptyBorder(4, 4, 4, 4)));
    split.add(p);
    setContentPane(split);
}

From source file:TableDemo.java

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

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

    //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  w  w.  j  ava2 s . com
}

From source file:components.TableSorterDemo.java

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

    TableSorter sorter = new TableSorter(new MyTableModel()); //ADDED THIS
    //JTable table = new JTable(new MyTableModel());         //OLD
    JTable table = new JTable(sorter); //NEW
    sorter.setTableHeader(table.getTableHeader()); //ADDED THIS
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));

    //Set up tool tips for column headers.
    table.getTableHeader()/* w w  w  .  j a va  2  s . c  o  m*/
            .setToolTipText("Click to specify sorting; Control-Click to specify secondary sorting");

    //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 source file:components.TableDialogEditDemo.java

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

    JTable table = new JTable(new MyTableModel());
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setFillsViewportHeight(true);/*from  w  w w  .j  a va2  s.  co m*/

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

    //Set up renderer and editor for the Favorite Color column.
    table.setDefaultRenderer(Color.class, new ColorRenderer(true));
    table.setDefaultEditor(Color.class, new ColorEditor());

    //Add the scroll pane to this panel.
    add(scrollPane);
}

From source file:components.TableSelectionDemo.java

public TableSelectionDemo() {
    super();/*from  w  w  w.j a va  2  s . c  o m*/
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    table = new JTable(new MyTableModel());
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setFillsViewportHeight(true);
    table.getSelectionModel().addListSelectionListener(new RowListener());
    table.getColumnModel().getSelectionModel().addListSelectionListener(new ColumnListener());
    add(new JScrollPane(table));

    add(new JLabel("Selection Mode"));
    buttonGroup = new ButtonGroup();
    addRadio("Multiple Interval Selection").setSelected(true);
    addRadio("Single Selection");
    addRadio("Single Interval Selection");

    add(new JLabel("Selection Options"));
    rowCheck = addCheckBox("Row Selection");
    rowCheck.setSelected(true);
    columnCheck = addCheckBox("Column Selection");
    cellCheck = addCheckBox("Cell Selection");
    cellCheck.setEnabled(false);

    output = new JTextArea(5, 40);
    output.setEditable(false);
    add(new JScrollPane(output));
}

From source file:components.TableFilterDemo.java

public TableFilterDemo() {
    super();// w  w  w . j a  va 2 s  .com
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    //Create a table with a sorter.
    MyTableModel model = new MyTableModel();
    sorter = new TableRowSorter<MyTableModel>(model);
    table = new JTable(model);
    table.setRowSorter(sorter);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setFillsViewportHeight(true);

    //For the purposes of this example, better to have a single
    //selection.
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    //When selection changes, provide user with row numbers for
    //both view and model.
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent event) {
            int viewRow = table.getSelectedRow();
            if (viewRow < 0) {
                //Selection got filtered away.
                statusText.setText("");
            } else {
                int modelRow = table.convertRowIndexToModel(viewRow);
                statusText.setText(String.format("Selected Row in view: %d. " + "Selected Row in model: %d.",
                        viewRow, modelRow));
            }
        }
    });

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

    //Add the scroll pane to this panel.
    add(scrollPane);

    //Create a separate form for filterText and statusText
    JPanel form = new JPanel(new SpringLayout());
    JLabel l1 = new JLabel("Filter Text:", SwingConstants.TRAILING);
    form.add(l1);
    filterText = new JTextField();
    //Whenever filterText changes, invoke newFilter.
    filterText.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            newFilter();
        }

        public void insertUpdate(DocumentEvent e) {
            newFilter();
        }

        public void removeUpdate(DocumentEvent e) {
            newFilter();
        }
    });
    l1.setLabelFor(filterText);
    form.add(filterText);
    JLabel l2 = new JLabel("Status:", SwingConstants.TRAILING);
    form.add(l2);
    statusText = new JTextField();
    l2.setLabelFor(statusText);
    form.add(statusText);
    SpringUtilities.makeCompactGrid(form, 2, 2, 6, 6, 6, 6);
    add(form);
}

From source file:TableCellRenderTest.java

public TableCellRenderFrame() {
    setTitle("TableCellRenderTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    TableModel model = new PlanetTableModel();
    JTable table = new JTable(model);
    table.setRowSelectionAllowed(false);

    // set up renderers and editors

    table.setDefaultRenderer(Color.class, new ColorTableCellRenderer());
    table.setDefaultEditor(Color.class, new ColorTableCellEditor());

    JComboBox moonCombo = new JComboBox();
    for (int i = 0; i <= 20; i++)
        moonCombo.addItem(i);/*from  w  ww. j  av  a 2  s .co m*/

    TableColumnModel columnModel = table.getColumnModel();
    TableColumn moonColumn = columnModel.getColumn(PlanetTableModel.MOONS_COLUMN);
    moonColumn.setCellEditor(new DefaultCellEditor(moonCombo));
    moonColumn.setHeaderRenderer(table.getDefaultRenderer(ImageIcon.class));
    moonColumn.setHeaderValue(new ImageIcon("Moons.gif"));

    // show table

    table.setRowHeight(100);
    add(new JScrollPane(table), BorderLayout.CENTER);
}

From source file:components.TableRenderDemo.java

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

    JTable table = new JTable(new MyTableModel());
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setFillsViewportHeight(true);//from   w w  w .j  a  v  a  2 s .c o  m

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

    //Set up column sizes.
    initColumnSizes(table);

    //Fiddle with the Sport column's cell editors/renderers.
    setUpSportColumn(table, table.getColumnModel().getColumn(2));

    //Add the scroll pane to this panel.
    add(scrollPane);
}

From source file:org.jfree.chart.demo.selection.SelectionDemo8.java

/**
 * A demonstration application showing how to create a simple time series
 * chart. This example uses monthly data.
 *
 * @param title  the frame title.//w  w  w  .  jav  a  2 s  . com
 */
public SelectionDemo8(String title) {
    super(title);
    ChartPanel chartPanel = (ChartPanel) createDemoPanel();
    chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
    chartPanel.setRangeZoomable(false);

    JFreeChart chart = chartPanel.getChart();
    XYPlot plot = (XYPlot) chart.getPlot();
    this.dataset = (TimeSeriesCollection) plot.getDataset();
    JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    split.add(chartPanel);

    this.model = new DefaultTableModel(new String[] { "Series:", "Item:", "Period:", "Value:" }, 0);
    this.table = new JTable(this.model);
    TableColumnModel tcm = this.table.getColumnModel();
    tcm.getColumn(3).setCellRenderer(new NumberCellRenderer());
    JPanel p = new JPanel(new BorderLayout());
    JScrollPane scroller = new JScrollPane(this.table);
    p.add(scroller);
    p.setBorder(BorderFactory.createCompoundBorder(new TitledBorder("Selected Items: "),
            new EmptyBorder(4, 4, 4, 4)));
    split.add(p);
    setContentPane(split);

}