Example usage for javax.swing JTable getColumn

List of usage examples for javax.swing JTable getColumn

Introduction

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

Prototype

public TableColumn getColumn(Object identifier) 

Source Link

Document

Returns the TableColumn object for the column in the table whose identifier is equal to identifier, when compared using equals.

Usage

From source file:logdruid.ui.mainpanel.EventRecordingSelectorPanel.java

private void initColumnSizes(JTable theTable) {
    TableColumn column = null;/*from ww w. j  a v a 2 s . c  o  m*/
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    TableCellRenderer headerRenderer = theTable.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < 4; i++) {
        column = theTable.getColumnModel().getColumn(i);
        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;
        cellWidth = comp.getPreferredSize().width;
        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.singlecell.SingleCellStatisticsController.java

/**
 * Show Summary Statistics in correspondent table
 *
 * @param analysisGroup/*from w w  w  . ja v a2s  .c om*/
 */
private void showSummary(SingleCellAnalysisGroup singleCellAnalysisGroup) {
    singleCellAnalysisController.getAnalysisPanel().getCurrentGroupName()
            .setText(singleCellAnalysisGroup.getGroupName());
    // set model and cell renderer for statistics summary table
    SingleCellStatSummaryTableModel statisticalSummaryTableModel = new SingleCellStatSummaryTableModel(
            singleCellAnalysisGroup);
    JTable statisticalSummaryTable = singleCellAnalysisController.getAnalysisPanel().getStatTable();
    statisticalSummaryTable.setModel(statisticalSummaryTableModel);
    for (int i = 1; i < statisticalSummaryTable.getColumnCount(); i++) {
        statisticalSummaryTable.getColumnModel().getColumn(i)
                .setCellRenderer(new FormatRenderer(new DecimalFormat("#.####"), SwingConstants.CENTER));
    }
    statisticalSummaryTable.getTableHeader().setDefaultRenderer(new TableHeaderRenderer(SwingConstants.RIGHT));
}

From source file:com.limegroup.gnutella.gui.GUIUtils.java

/**
 * It will adjust the column width to match the widest element.
 * (You might not want to use this for every column, consider some columns might be really long)
 * @param model/*from   ww  w . j av a2 s  . c o  m*/
 * @param columnIndex
 * @param table
 * @return
 */
public static void adjustColumnWidth(TableModel model, int columnIndex, int maxWidth, int rightPadding,
        JTable table) {

    if (columnIndex > model.getColumnCount() - 1) {
        //invalid column index
        return;
    }

    if (!model.getColumnClass(columnIndex).equals(String.class)) {
        return;
    }

    String longestValue = "";
    for (int row = 0; row < model.getRowCount(); row++) {
        String strValue = (String) model.getValueAt(row, columnIndex);
        if (strValue != null && strValue.length() > longestValue.length()) {
            longestValue = strValue;
        }
    }

    Graphics g = table.getGraphics();

    try {
        int suggestedWidth = (int) g.getFontMetrics(table.getFont()).getStringBounds(longestValue, g)
                .getWidth();
        table.getColumnModel().getColumn(columnIndex)
                .setPreferredWidth(((suggestedWidth > maxWidth) ? maxWidth : suggestedWidth) + rightPadding);
    } catch (Exception e) {
        table.getColumnModel().getColumn(columnIndex).setPreferredWidth(maxWidth);
        e.printStackTrace();
    }

}

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);//  w w w .  j a va 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:ngat.opsgui.xcomp.SeeingPanel2.java

private JTable createSeeingHistoryTable() {
    shtm = new SeeingHistoryTableModel();
    shtr = new SeeingHistoryTableRenderer();

    JTable table = new JTable(shtm);

    int nc = table.getColumnModel().getColumnCount();
    for (int ic = 0; ic < nc; ic++) {
        table.getColumnModel().getColumn(ic).setCellRenderer(shtr);
    }//from   w  ww .j  av a 2 s.  c  o m

    return table;
}

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.singlecell.SingleCellStatisticsController.java

/**
 * Initialize main view./*from   w w  w . j av a  2s  .c  o  m*/
 */
private void initMainView() {
    // the view is kept in the parent controllers
    AnalysisPanel analysisPanel = singleCellAnalysisController.getAnalysisPanel();
    analysisPanel.getConditionList().setModel(new DefaultListModel());
    // customize tables
    analysisPanel.getStatTable().getTableHeader().setReorderingAllowed(false);
    analysisPanel.getStatTable().getTableHeader().setReorderingAllowed(false);
    analysisPanel.getComparisonTable().setFillsViewportHeight(true);
    analysisPanel.getComparisonTable().setFillsViewportHeight(true);

    // init binding
    groupsBindingList = ObservableCollections.observableList(new ArrayList<SingleCellAnalysisGroup>());
    JListBinding jListBinding = SwingBindings.createJListBinding(AutoBinding.UpdateStrategy.READ_WRITE,
            groupsBindingList, analysisPanel.getAnalysisGroupList());
    bindingGroup.addBinding(jListBinding);

    // fill in combo box
    List<Double> significanceLevels = new ArrayList<>();
    for (SignificanceLevel significanceLevel : SignificanceLevel.values()) {
        significanceLevels.add(significanceLevel.getValue());
    }
    ObservableList<Double> significanceLevelsBindingList = ObservableCollections
            .observableList(significanceLevels);
    JComboBoxBinding jComboBoxBinding = SwingBindings.createJComboBoxBinding(
            AutoBinding.UpdateStrategy.READ_WRITE, significanceLevelsBindingList,
            analysisPanel.getSignLevelComboBox());
    bindingGroup.addBinding(jComboBoxBinding);
    bindingGroup.bind();
    // add the NONE (default) correction method
    // when the none is selected, CellMissy does not correct for multiple hypotheses
    analysisPanel.getCorrectionComboBox().addItem("none");
    // fill in combo box: get all the correction methods from the factory
    Set<String> correctionBeanNames = MultipleComparisonsCorrectionFactory.getInstance()
            .getCorrectionBeanNames();
    correctionBeanNames.stream().forEach((correctionBeanName) -> {
        analysisPanel.getCorrectionComboBox().addItem(correctionBeanName);
    });
    // do the same for the statistical tests
    Set<String> statisticsCalculatorBeanNames = StatisticsTestFactory.getInstance()
            .getStatisticsCalculatorBeanNames();
    statisticsCalculatorBeanNames.stream().forEach((testName) -> {
        analysisPanel.getStatTestComboBox().addItem(testName);
    });
    //significance level to 0.05
    analysisPanel.getSignLevelComboBox().setSelectedIndex(1);
    // add parameters to perform analysis on
    analysisPanel.getParameterComboBox().addItem("cell speed");
    analysisPanel.getParameterComboBox().addItem("cell direct");

    /**
     * Add a group to analysis
     */
    analysisPanel.getAddGroupButton().addActionListener((ActionEvent e) -> {
        // from selected conditions make a new group and add it to the list
        addGroupToAnalysis();
    });

    /**
     * Remove a Group from analysis
     */
    analysisPanel.getRemoveGroupButton().addActionListener((ActionEvent e) -> {
        // remove the selected group from list
        removeGroupFromAnalysis();
    });
    /**
     * Execute a Mann Whitney Test on selected Analysis Group
     */
    analysisPanel.getPerformStatButton().addActionListener((ActionEvent e) -> {
        int selectedIndex = analysisPanel.getAnalysisGroupList().getSelectedIndex();
        String statisticalTestName = analysisPanel.getStatTestComboBox().getSelectedItem().toString();
        String param = analysisPanel.getParameterComboBox().getSelectedItem().toString();
        // check that an analysis group is being selected
        if (selectedIndex != -1) {
            SingleCellAnalysisGroup selectedGroup = groupsBindingList.get(selectedIndex);
            // compute statistics
            computeStatistics(selectedGroup, statisticalTestName, param);
            // show statistics in tables
            showSummary(selectedGroup);
            // set the correction combobox to the one already chosen
            analysisPanel.getCorrectionComboBox().setSelectedItem(selectedGroup.getCorrectionMethodName());
            if (selectedGroup.getCorrectionMethodName().equals("none")) {
                // by default show p-values without adjustment
                showPValues(selectedGroup, false);
            } else {
                // show p values with adjustement
                showPValues(selectedGroup, true);
            }
        } else {
            // ask user to select a group
            singleCellAnalysisController.showMessage("Please select a group to perform analysis on.",
                    "You must select a group first", JOptionPane.INFORMATION_MESSAGE);
        }
    });

    /**
     * Refresh p value table with current selected significance of level
     */
    analysisPanel.getSignLevelComboBox().addActionListener((ActionEvent e) -> {
        if (analysisPanel.getSignLevelComboBox().getSelectedIndex() != -1) {
            String statisticalTest = analysisPanel.getStatTestComboBox().getSelectedItem().toString();
            Double selectedSignLevel = (Double) analysisPanel.getSignLevelComboBox().getSelectedItem();
            SingleCellAnalysisGroup selectedGroup = groupsBindingList
                    .get(analysisPanel.getAnalysisGroupList().getSelectedIndex());
            boolean isAdjusted = !selectedGroup.getCorrectionMethodName().equals("none");
            singleCellStatisticsAnalyzer.detectSignificance(selectedGroup, statisticalTest, selectedSignLevel,
                    isAdjusted);
            boolean[][] significances = selectedGroup.getSignificances();
            JTable pValuesTable = analysisPanel.getComparisonTable();
            for (int i = 1; i < pValuesTable.getColumnCount(); i++) {
                pValuesTable.getColumnModel().getColumn(i)
                        .setCellRenderer(new PValuesTableRenderer(new DecimalFormat("#.####"), significances));
            }
            pValuesTable.repaint();
        }
    });

    /**
     * Apply correction for multiple comparisons: choose the algorithm!
     */
    analysisPanel.getCorrectionComboBox().addActionListener((ActionEvent e) -> {
        int selectedIndex = analysisPanel.getAnalysisGroupList().getSelectedIndex();
        if (selectedIndex != -1) {
            SingleCellAnalysisGroup selectedGroup = groupsBindingList.get(selectedIndex);
            String correctionMethod = analysisPanel.getCorrectionComboBox().getSelectedItem().toString();

            // if the correction method is not "NONE"
            if (!correctionMethod.equals("none")) {
                // adjust p values
                singleCellStatisticsAnalyzer.correctForMultipleComparisons(selectedGroup, correctionMethod);
                // show p - values with the applied correction
                showPValues(selectedGroup, true);
            } else {
                // if selected correction method is "NONE", do not apply correction and only show normal p-values
                showPValues(selectedGroup, false);
            }
        }
    });

    /**
     * Perform statistical test: choose the test!!
     */
    analysisPanel.getPerformStatButton().addActionListener((ActionEvent e) -> {
        // get the selected test to be executed
        String selectedTest = analysisPanel.getStatTestComboBox().getSelectedItem().toString();
        String param = analysisPanel.getParameterComboBox().getSelectedItem().toString();
        // analysis group
        int selectedIndex = analysisPanel.getAnalysisGroupList().getSelectedIndex();
        if (selectedIndex != -1) {
            SingleCellAnalysisGroup selectedGroup = groupsBindingList.get(selectedIndex);
            computeStatistics(selectedGroup, selectedTest, param);
        }
    });

    //multiple comparison correction: set the default correction to none
    analysisPanel.getCorrectionComboBox().setSelectedIndex(0);
    analysisPanel.getStatTestComboBox().setSelectedIndex(0);
    analysisPanel.getParameterComboBox().setSelectedIndex(0);
}

From source file:au.org.ala.delta.editor.ui.ActionSetsDialog.java

private void configureWidths(JTable table) {
    table.getColumnModel().getColumn(0).setPreferredWidth(FILE_DESCRIPTION_COLUMN_WIDTH);
    table.getColumnModel().getColumn(1).setPreferredWidth(FILE_NAME_COLUMN_WIDTH);
    table.getColumnModel().getColumn(2).setPreferredWidth(TIME_COLUMN_WIDTH);
}

From source file:gov.llnl.lc.infiniband.opensm.plugin.gui.chart.AdvancedXY_PlotPanel.java

private void initChart(XY_PlotPanel pPanel) {
    this.plotPanel = pPanel;
    this.chartPanel = pPanel.getChartPanel();
    if (pPanel instanceof SimpleXY_PlotPanel) {
        this.setTitle(((SimpleXY_PlotPanel) pPanel).getTitle());
    }//from  w w  w. j  av  a 2  s. c  o  m

    JFreeChart chart = chartPanel.getChart();
    XYPlot plot = (XYPlot) chart.getPlot();

    // how many data sets will there be (may not exist yet, cause swing worker may still be constructing them)
    int numRows = 2; // enough for counts, and delta counts
    if ((XY_PlotType.ADV_PORT_UTIL_PLUS.equals(getType())))
        numRows = 4;
    boolean includeExtra = numRows > MAX_DATASETS / 2 ? true : false;

    int rowSize = includeExtra ? MAX_DS_SIZE : MAX_DS_SIZE / 2 + 19; // extra for padding
    NumDataSets = numRows;

    // build the table model from the data sets, then build the table and slider

    // see "chartProgress()" method
    chart.addProgressListener(this);

    this.chartPanel.setPreferredSize(new java.awt.Dimension(750, 300));
    this.chartPanel.setDomainZoomable(true);
    this.chartPanel.setRangeZoomable(true);
    Border border = BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
            BorderFactory.createEtchedBorder());
    this.chartPanel.setBorder(border);
    add(this.chartPanel);

    JPanel dashboard = new JPanel(new BorderLayout());
    dashboard.setPreferredSize(new Dimension(400, rowSize));
    dashboard.setBorder(BorderFactory.createEmptyBorder(0, 4, 4, 4));

    this.model = new XY_PlotTableModel(numRows);

    // initialize the model, and table, here
    //    this.model.setValueAt("name", 0, 1);
    this.model.setValueAt(new Double("0.00"), 0, 1);
    this.model.setValueAt(new Double("0.00"), 0, 2);
    //    this.model.setValueAt("units", 0, 3);
    JTable table = new JTable(this.model);

    // the columns are name, time, value, units.  both name and units are strings
    // so need special renderers for time and value

    TableCellRenderer renderer1 = new DateCellRenderer(new SimpleDateFormat("HH:mm:ss"));
    TableCellRenderer renderer2 = new NumberCellRenderer();
    table.getColumnModel().getColumn(1).setCellRenderer(renderer1);
    table.getColumnModel().getColumn(2).setCellRenderer(renderer2);
    JScrollPane scroller = new JScrollPane(table);
    dashboard.add(scroller);

    this.slider = new JSlider(0, 100, 10);
    this.slider.addChangeListener(this);
    dashboard.add(this.slider, BorderLayout.SOUTH);
    add(dashboard, BorderLayout.SOUTH);

    //     XYPlot plot = (XYPlot) chart.getPlot();

    plot.setDomainCrosshairLockedOnData(true);
    plot.setRangeCrosshairVisible(false);
    plot.setDomainCrosshairVisible(true);
}

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

private void initColumnSizes(JTable theTable) {
    MyTableModel model = (MyTableModel) theTable.getModel();
    TableColumn column = null;/*from w  w  w  .jav  a  2 s. c o m*/
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    TableCellRenderer headerRenderer = theTable.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < 6; i++) {
        column = theTable.getColumnModel().getColumn(i);

        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;

        cellWidth = comp.getPreferredSize().width;

        if (DEBUG) {
            logger.info("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth
                    + "; cellWidth = " + cellWidth);
        }

        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

From source file:Visuals.BarChart.java

public JPanel addCharts() {
    ChartPanel barPanel = drawBarChart();
    barPanel.setDomainZoomable(true);//from   w w w.  j  av  a2  s. c  om
    JPanel thisBarPanel = new JPanel();
    thisBarPanel.setLayout(new BorderLayout());

    String[][] finalRisks = new String[riskCount][4];
    for (int i = 0; i < riskCount; i++) {
        finalRisks[i][0] = risks[i][0];
        finalRisks[i][1] = risks[i][1];
        finalRisks[i][2] = risks[i][2];
        finalRisks[i][3] = risks[i][3];
    }

    JTable table = new JTable(finalRisks, columns);
    //table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    TableRowSorter<TableModel> sorter = new TableRowSorter<>(table.getModel());
    table.setRowSorter(sorter);
    List<RowSorter.SortKey> sortKeys = new ArrayList<>();

    int columnIndexToSort = 2;
    sortKeys.add(new RowSorter.SortKey(columnIndexToSort, SortOrder.ASCENDING));

    sorter.setSortKeys(sortKeys);
    sorter.sort();

    TableColumn tcol = table.getColumnModel().getColumn(2);
    table.removeColumn(tcol);

    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    table.getColumnModel().getColumn(1).setPreferredWidth(600);
    table.getColumnModel().getColumn(2).setPreferredWidth(600);

    table.setShowHorizontalLines(true);
    table.setRowHeight(40);
    table.setEnabled(false);

    JScrollPane tableScrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    Dimension d = table.getPreferredSize();
    tableScrollPane
            .setPreferredSize(new Dimension((d.width - 400), (table.getRowHeight() + 1) * (riskCount + 1)));

    JLabel right = new JLabel(
            "                                                                                                    ");
    thisBarPanel.add(right, BorderLayout.EAST);
    thisBarPanel.add(barPanel, BorderLayout.CENTER);
    thisBarPanel.add(tableScrollPane, BorderLayout.SOUTH);
    return thisBarPanel;
}