Example usage for javax.swing JTable setPreferredScrollableViewportSize

List of usage examples for javax.swing JTable setPreferredScrollableViewportSize

Introduction

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

Prototype

@BeanProperty(bound = false, description = "The preferred size of the viewport.")
public void setPreferredScrollableViewportSize(Dimension size) 

Source Link

Document

Sets the preferred size of the viewport for this table.

Usage

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()/*from  w w  w .  j a  v  a2  s.  co  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:SimpleTableSelectionDemo.java

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

    final String[] columnNames = { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian" };

    final Object[][] data = { { "Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false) },
            { "Alison", "Huml", "Rowing", new Integer(3), new Boolean(true) },
            { "Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false) },
            { "Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true) },
            { "Philip", "Milne", "Pool", new Integer(10), new Boolean(false) } };

    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));

    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    if (ALLOW_ROW_SELECTION) { // true by default
        ListSelectionModel rowSM = table.getSelectionModel();
        rowSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                //Ignore extra messages.
                if (e.getValueIsAdjusting())
                    return;

                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                if (lsm.isSelectionEmpty()) {
                    System.out.println("No rows are selected.");
                } else {
                    int selectedRow = lsm.getMinSelectionIndex();
                    System.out.println("Row " + selectedRow + " is now selected.");
                }/*from   w  w w.j  av a2  s.  c  o  m*/
            }
        });
    } else {
        table.setRowSelectionAllowed(false);
    }

    if (ALLOW_COLUMN_SELECTION) { // false by default
        if (ALLOW_ROW_SELECTION) {
            //We allow both row and column selection, which
            //implies that we *really* want to allow individual
            //cell selection.
            table.setCellSelectionEnabled(true);
        }
        table.setColumnSelectionAllowed(true);
        ListSelectionModel colSM = table.getColumnModel().getSelectionModel();
        colSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                //Ignore extra messages.
                if (e.getValueIsAdjusting())
                    return;

                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                if (lsm.isSelectionEmpty()) {
                    System.out.println("No columns are selected.");
                } else {
                    int selectedCol = lsm.getMinSelectionIndex();
                    System.out.println("Column " + selectedCol + " is now selected.");
                }
            }
        });
    }

    if (DEBUG) {
        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                printDebugData(table);
            }
        });
    }

    //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:integratedprogressdemo.WeatherData.java

private WeatherData(boolean displayProgress) {
    setBackground(Color.WHITE);/*from w w w .java  2s . c  om*/
    setLayout(new BorderLayout());
    JLabel lbl = new JLabel("World-Wide Weather Data");
    lbl.setFont(new Font("Serif", Font.PLAIN, 18));

    add(lbl, BorderLayout.PAGE_START);
    lbl = new JLabel("Weather information from over 50 cities");
    add(lbl, BorderLayout.LINE_START);

    if (displayProgress) {
        progressPanel = new JPanel();
        progressPanel.setBackground(Color.WHITE);
        progressPanel.setLayout(new BorderLayout(20, 20));

        String lblText = "<html>Stuck in the mud? Make progress with...<br /><font color=red><em>JDK Documentation</em></font><br/></html>";
        lbl = new JLabel(lblText);
        progressPanel.add(lbl, BorderLayout.NORTH);

        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);
        progressPanel.add(progressBar, BorderLayout.SOUTH);

        add(progressPanel, BorderLayout.LINE_END);
    }

    String[] columnNames = { "City", "Temperature" };
    JTable table = new JTable(getData(), columnNames);

    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setFillsViewportHeight(true);

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

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

From source file:TableDialogEditDemo.java

public TableDialogEditDemo() {
    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);

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

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);//  ww w . j a  v  a  2  s  .c  om
}

From source file:edu.ku.brc.specify.plugins.sgr.SGRResultsDisplay.java

public SGRResultsDisplay(int width, MatchResults results) {
    if (Main.m_settings == null) {
        Main.m_settings = new JSettings(true);
        Main.m_settings.load(//from  ww w  .  j  a v  a  2 s  .  c o m
                JPathHelper.addSeparator(System.getProperty("user.home")) + JSettings.SETTINGS_FILE, "1.8");

        Main.m_sysLocale = Locale.getDefault();
        if (Main.m_settings.getLocale().length() > 0) {
            Locale.setDefault(new Locale(Main.m_settings.getLocale()));
        }
    }

    SGRColumnOrdering columns = SGRColumnOrdering.getInstance();
    String[] fields = columns.getFields();

    DefaultTableModel resultsTableModel = new DefaultTableModel(columns.getHeadings(), 0);

    final List<List<Color>> rowColors = new LinkedList<List<Color>>();

    for (Match result : results) {
        SGRRecord match = result.match;
        float score = result.score;
        float maxScore = 22.0f; //results.maxScore;

        List<Color> cellColors = new LinkedList<Color>();

        List<String> data = new LinkedList<String>();
        for (String field : fields) {
            if (field.equals("id")) {
                data.add(match.id);
                cellColors.add(SGRColors.colorForScore(score, maxScore));
            } else if (field.equals("score")) {
                data.add(((Float) score).toString());
                cellColors.add(SGRColors.colorForScore(score, maxScore));
            } else {
                data.add(StringUtils.join(match.getFieldValues(field).toArray(), ';'));

                Float fieldContribution = result.fieldScoreContributions().get(field);
                Color color = SGRColors.colorForScore(score, maxScore, fieldContribution);
                cellColors.add(color);
            }
        }
        resultsTableModel.addRow(data.toArray());
        rowColors.add(cellColors);
    }

    JTable table = createTable(resultsTableModel, rowColors);
    Dimension preferredSize = table.getPreferredSize();
    preferredSize.width = Math.min((int) (0.9 * width), preferredSize.width);
    table.setPreferredScrollableViewportSize(preferredSize);
    table.getColumnModel().addColumnModelListener(this);

    add(new JScrollPane(table));
}

From source file:kg.apc.jmeter.vizualizers.SynthesisReportGui.java

/**
 * Main visualizer setup.//  w  w w .j av  a2s. co m
 */
private void init() {
    this.setLayout(new BorderLayout());

    // MAIN PANEL
    JPanel mainPanel = new JPanel();
    Border margin = new EmptyBorder(10, 10, 5, 10);

    mainPanel.setBorder(margin);
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

    mainPanel.add(JMeterPluginsUtils.addHelpLinkToPanel(makeTitlePanel(), WIKIPAGE));

    // SortFilterModel mySortedModel =
    // new SortFilterModel(myStatTableModel);
    JTable myJTable = new JTable(model);
    myJTable.getTableHeader().setDefaultRenderer(new JMeterHeaderAsPropertyRenderer(COLUMNS_MSG_PARAMETERS));
    myJTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
    RendererUtils.applyRenderers(myJTable, RENDERERS);
    JScrollPane myScrollPane = new JScrollPane(myJTable);
    this.add(mainPanel, BorderLayout.NORTH);
    this.add(myScrollPane, BorderLayout.CENTER);
    saveTable.addActionListener(this);
    JPanel opts = new JPanel();
    opts.add(useGroupName, BorderLayout.WEST);
    opts.add(saveTable, BorderLayout.CENTER);
    opts.add(saveHeaders, BorderLayout.EAST);
    this.add(opts, BorderLayout.SOUTH);
}

From source file:net.sf.jabref.importer.ZipFileChooser.java

/**
 * New Zip file chooser./*from   ww  w.ja v a 2 s.com*/
 *
 * @param owner  Owner of the file chooser
 * @param zipFile  Zip-Fle to choose from, must be readable
 */
public ZipFileChooser(ImportCustomizationDialog importCustomizationDialog, ZipFile zipFile) {
    super(importCustomizationDialog, Localization.lang("Select file from ZIP-archive"), false);

    ZipFileChooserTableModel tableModel = new ZipFileChooserTableModel(zipFile,
            getSelectableZipEntries(zipFile));
    JTable table = new JTable(tableModel);
    TableColumnModel cm = table.getColumnModel();
    cm.getColumn(0).setPreferredWidth(200);
    cm.getColumn(1).setPreferredWidth(150);
    cm.getColumn(2).setPreferredWidth(100);
    JScrollPane sp = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setPreferredScrollableViewportSize(new Dimension(500, 150));
    if (table.getRowCount() > 0) {
        table.setRowSelectionInterval(0, 0);
    }

    // cancel: no entry is selected
    JButton cancelButton = new JButton(Localization.lang("Cancel"));
    cancelButton.addActionListener(e -> dispose());
    // ok: get selected class and check if it is instantiable as an importer
    JButton okButton = new JButton(Localization.lang("OK"));
    okButton.addActionListener(e -> {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, Localization.lang("Please select an importer."));
        } else {
            ZipFileChooserTableModel model = (ZipFileChooserTableModel) table.getModel();
            ZipEntry tempZipEntry = model.getZipEntry(row);
            CustomImporter importer = new CustomImporter();
            importer.setBasePath(model.getZipFile().getName());
            String className = tempZipEntry.getName().substring(0, tempZipEntry.getName().lastIndexOf('.'))
                    .replace("/", ".");
            importer.setClassName(className);
            try {
                ImportFormat importFormat = importer.getInstance();
                importer.setName(importFormat.getFormatName());
                importer.setCliId(importFormat.getId());
                importCustomizationDialog.addOrReplaceImporter(importer);
                dispose();
            } catch (IOException | ClassNotFoundException | InstantiationException
                    | IllegalAccessException exc) {
                LOGGER.warn("Could not instantiate importer: " + importer.getName(), exc);
                JOptionPane.showMessageDialog(this, Localization.lang("Could not instantiate %0 %1",
                        importer.getName() + ":\n", exc.getMessage()));
            }
        }
    });

    // Key bindings:
    JPanel mainPanel = new JPanel();
    //ActionMap am = mainPanel.getActionMap();
    //InputMap im = mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    //im.put(Globals.getKeyPrefs().getKey(KeyBinds.CLOSE_DIALOG), "close");
    //am.put("close", closeAction);
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(sp, BorderLayout.CENTER);

    JPanel optionsPanel = new JPanel();
    optionsPanel.add(okButton);
    optionsPanel.add(cancelButton);
    optionsPanel.add(Box.createHorizontalStrut(5));

    getContentPane().add(mainPanel, BorderLayout.CENTER);
    getContentPane().add(optionsPanel, BorderLayout.SOUTH);
    this.setSize(getSize());
    pack();
    this.setLocationRelativeTo(importCustomizationDialog);
    new FocusRequester(table);
}

From source file:edu.ku.brc.stats.StatGroupTable.java

/**
 * Calculates and sets the each column to it preferred size
 * @param table the table to fix ups/*from ww w . j a  v a2 s .  c om*/
 */
public static void calcColumnWidths(JTable table) {
    JTableHeader header = table.getTableHeader();

    TableCellRenderer defaultHeaderRenderer = null;

    if (header != null) {
        defaultHeaderRenderer = header.getDefaultRenderer();
    }

    TableColumnModel columns = table.getColumnModel();
    TableModel data = table.getModel();

    int margin = columns.getColumnMargin(); // only JDK1.3

    int rowCount = data.getRowCount();

    int totalWidth = 0;

    for (int i = columns.getColumnCount() - 1; i >= 0; --i) {
        TableColumn column = columns.getColumn(i);

        int columnIndex = column.getModelIndex();

        int width = -1;

        TableCellRenderer h = column.getHeaderRenderer();

        if (h == null)
            h = defaultHeaderRenderer;

        if (h != null) // Not explicitly impossible
        {
            Component c = h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1, i);

            width = c.getPreferredSize().width;
        }

        for (int row = rowCount - 1; row >= 0; --row) {
            TableCellRenderer r = table.getCellRenderer(row, i);

            Component c = r.getTableCellRendererComponent(table, data.getValueAt(row, columnIndex), false,
                    false, row, i);

            width = Math.max(width, c.getPreferredSize().width + 10); // adding an arbitray 10 pixels to make it look nicer
        }

        if (width >= 0) {
            column.setPreferredWidth(width + margin); // <1.3: without margin
        }

        totalWidth += column.getPreferredWidth();
    }

    // If you like; This does not make sense for two many columns!
    Dimension size = table.getPreferredScrollableViewportSize();
    //if (totalWidth > size.width)
    {
        size.height = Math.min(size.height, table.getRowHeight() * visibleRows);
        size.width = totalWidth;
        table.setPreferredScrollableViewportSize(size);
    }

}

From source file:edu.ku.brc.specify.tasks.subpane.wb.DataImportDialog.java

/**
 * Parses the given import xls file according to the users selection and creates/updates the
 * Preview table, showing the user how the import options effect the way the data will be
 * imported into the spreadsheet./*from w  ww. ja v  a  2 s.  c  om*/
 * 
 * @param table - the table to display the data
 * @return JTable - the table to display the data
 */
private JTable setXLSTableData(final JTable table) {
    int numRows = 0;
    int numCols = 0;
    String[] headers = {};
    Vector<Vector<String>> tableDataVector = new Vector<Vector<String>>();
    Vector<String> rowData = new Vector<String>();
    Vector<String> headerVector = new Vector<String>();
    DateWrapper scrDateFormat = AppPrefsCache.getDateWrapper("ui", "formatting", "scrdateformat");
    try {
        log.debug("setXLSTableData - file - " + configXLS.getFile().toString());

        InputStream input = new FileInputStream(configXLS.getFile());
        POIFSFileSystem fs = new POIFSFileSystem(input);
        HSSFWorkbook workBook = new HSSFWorkbook(fs);
        HSSFSheet sheet = workBook.getSheetAt(0);

        Vector<Integer> badHeads = new Vector<Integer>();
        Vector<Integer> emptyCols = new Vector<Integer>();
        ((ConfigureXLS) config).checkHeadsAndCols(sheet, badHeads, emptyCols);
        if (badHeads.size() > 0 && doesFirstRowHaveHeaders) {
            if (table != null) {
                ((ConfigureXLS) config).showBadHeadingsMsg(badHeads, emptyCols, getTitle());
            }
            this.doesFirstRowHaveHeaders = false;
            try {
                ignoreActions = true;
                this.containsHeaders.setSelected(false);
            } finally {
                ignoreActions = false;
            }
            if (table != null) {
                return table;
            }
        }
        boolean firstRow = true;

        //quick fix to prevent ".0" at end of catalog numbers etc
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(0);
        nf.setMaximumFractionDigits(20);
        nf.setGroupingUsed(false); //gets rid of commas

        int maxCols = 0;

        // Iterate over each row in the sheet
        Iterator<?> rows = sheet.rowIterator();
        while (rows.hasNext()) {
            numCols = 0;
            rowData = new Vector<String>();
            HSSFRow row = (HSSFRow) rows.next();
            //log.debug(row.getLastCellNum()+"  "+row.getPhysicalNumberOfCells());
            int maxSize = Math.max(row.getPhysicalNumberOfCells(), row.getLastCellNum());
            if (maxSize > maxCols) {
                maxCols = maxSize;
            }
            while (numCols < maxSize) {
                if (emptyCols.indexOf(new Integer(numCols)) == -1) {
                    HSSFCell cell = row.getCell(numCols);
                    String value = null;
                    // if cell is blank, set value to ""
                    if (cell == null) {
                        value = "";
                    } else {
                        int type = cell.getCellType();

                        switch (type) {
                        case HSSFCell.CELL_TYPE_NUMERIC:
                            // The best I can do at this point in the app is to guess if a
                            // cell is a date.
                            // Handle dates carefully while using HSSF. Excel stores all
                            // dates as numbers, internally.
                            // The only way to distinguish a date is by the formatting of
                            // the cell. (If you
                            // have ever formatted a cell containing a date in Excel, you
                            // will know what I mean.)
                            // Therefore, for a cell containing a date, cell.getCellType()
                            // will return
                            // HSSFCell.CELL_TYPE_NUMERIC. However, you can use a utility
                            // function,
                            // HSSFDateUtil.isCellDateFormatted(cell), to check if the cell
                            // can be a date.
                            // This function checks the format against a few internal
                            // formats to decide the issue,
                            // but by its very nature it is prone to false negatives.
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue());
                                //value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue());
                            } else {
                                double numeric = cell.getNumericCellValue();
                                value = nf.format(numeric);
                            }
                            break;

                        case HSSFCell.CELL_TYPE_STRING:
                            value = cell.getRichStringCellValue().getString();
                            break;

                        case HSSFCell.CELL_TYPE_BLANK:
                            value = "";
                            break;

                        case HSSFCell.CELL_TYPE_BOOLEAN:
                            value = Boolean.toString(cell.getBooleanCellValue());
                            break;

                        case HSSFCell.CELL_TYPE_FORMULA:
                            value = UIRegistry.getResourceString("WB_FORMULA_IMPORT_NO_PREVIEW");
                            break;

                        default:
                            value = "";
                            log.error("unsuported cell type");
                            break;
                        }
                    }
                    if (firstRow && doesFirstRowHaveHeaders) {
                        checkUserColInfo(value, numCols);
                    }
                    if (isUserCol(numCols)) {
                        rowData.add(value.toString());
                    }
                }
                numCols++;
            }
            if (doesFirstRowHaveHeaders && firstRow) {
                headerVector = rowData;
                headers = new String[rowData.size()];
            } else if (!doesFirstRowHaveHeaders && firstRow) {
                //headers = createDummyHeaders(rowData.size());
                tableDataVector.add(rowData);
            } else {
                tableDataVector.add(rowData);
            }
            firstRow = false;
            numRows++;
        }
        maxCols -= emptyCols.size();
        if (!doesFirstRowHaveHeaders) {
            headerVector = createDummyHeadersAsVector(maxCols);
            headers = new String[maxCols];
        }
        for (int i = 0; i < headerVector.size(); i++) {
            headers[i] = headerVector.elementAt(i);
        }
        printArray(headers);

        String[][] tableData = new String[tableDataVector.size()][maxCols];
        for (int i = 0; i < tableDataVector.size(); i++) {
            Vector<String> v = tableDataVector.get(i);
            for (int j = 0; j < v.size(); j++) {
                tableData[i][j] = v.get(j).toString();
            }

        }
        if (checkForErrors(headers, tableData)) {
            errorPanel.showDataImportStatusPanel(true);
        } else {
            errorPanel.showDataImportStatusPanel(false);
        }

        if ((doesFirstRowHaveHeaders ? numRows - 1 : numRows) > WorkbenchTask.MAX_ROWS) {
            hasTooManyRows = true;
            showTooManyRowsErrorDialog();
        } else {
            hasTooManyRows = false;
        }
        log.debug(headers);
        log.debug(tableData);
        model = new PreviewTableModel(headers, tableData);
        JTable result = null;
        if (table == null) {
            result = new JTable();
            result.setColumnSelectionAllowed(false);
            result.setRowSelectionAllowed(false);
            result.setCellSelectionEnabled(false);
            result.getTableHeader().setReorderingAllowed(false);
            result.setPreferredScrollableViewportSize(new Dimension(500, 100));
            result.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        } else {
            result = table;
        }
        result.setModel(model);
        result.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false));
        model.fireTableDataChanged();
        model.fireTableStructureChanged();
        return result;
    } catch (Exception ex) {
        UIRegistry.displayErrorDlgLocalized(UIRegistry.getResourceString("WB_ERROR_READING_IMPORT_FILE"));
        if (table != null) {
            String[] columnNames = {};
            String[][] blankData = { {} };
            model = new PreviewTableModel(columnNames, blankData);
            table.setModel(model);
            table.setColumnSelectionAllowed(false);
            table.setRowSelectionAllowed(false);
            table.setCellSelectionEnabled(false);
            table.getTableHeader().setReorderingAllowed(false);
            table.setPreferredScrollableViewportSize(new Dimension(500, 100));
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            table.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false));
            model.fireTableDataChanged();
            model.fireTableStructureChanged();
            return table;
        }
        //log.error("Error attempting to parse input xls file:" + ex);
        //ex.printStackTrace();
    }

    return null;
}