Example usage for javax.swing.table TableColumn setWidth

List of usage examples for javax.swing.table TableColumn setWidth

Introduction

In this page you can find the example usage for javax.swing.table TableColumn setWidth.

Prototype

@BeanProperty(description = "The width of the column.")
public void setWidth(int width) 

Source Link

Document

This method should not be used to set the widths of columns in the JTable, use setPreferredWidth instead.

Usage

From source file:com.diversityarrays.kdxplore.field.FieldViewDialog.java

public FieldViewDialog(Window owner, String title, SampleGroupChoice sgcSamples, Trial trial,
        SampleGroupChoice sgcNewMedia, KDSmartDatabase db) throws IOException {
    super(owner, title, ModalityType.MODELESS);

    advanceRetreatControls = Box.createHorizontalBox();
    advanceRetreatControls.add(new JButton(retreatAction));
    advanceRetreatControls.add(new JButton(advanceAction));

    autoAdvanceControls = Box.createHorizontalBox();
    autoAdvanceControls.add(new JButton(autoAdvanceAction));

    autoAdvanceOption.addActionListener(new ActionListener() {
        @Override// w  w w  .j a v a2 s  .  c o  m
        public void actionPerformed(ActionEvent e) {
            updateMovementControls();
        }
    });

    this.database = db;
    this.sampleGroupChoiceForSamples = sgcSamples;
    this.sampleGroupChoiceForNewMedia = sgcNewMedia;

    NumberSpinner fontSpinner = new NumberSpinner(new SpinnerNumberModel(), "0.00");

    this.fieldViewPanel = FieldViewPanel.create(database, trial, SeparatorVisibilityOption.VISIBLE, null,
            Box.createHorizontalGlue(), new JButton(showInfoAction), Box.createHorizontalGlue(),
            new JLabel("Font Size:"), fontSpinner, Box.createHorizontalGlue(), advanceRetreatControls,
            autoAdvanceOption, autoAdvanceControls);

    initialiseAction(advanceAction, "ic_object_advance_black.png", "Auto-Advance");

    this.xyProvider = fieldViewPanel.getXYprovider();
    this.traitMap = fieldViewPanel.getTraitMap();

    fieldLayoutTable = fieldViewPanel.getFieldLayoutTable();

    JScrollPane scrollPane = fieldViewPanel.getFieldTableScrollPane();
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    fieldLayoutTable.setTransferHandler(flth);
    fieldLayoutTable.setDropMode(DropMode.ON);

    fieldLayoutTable.addMouseListener(new MouseAdapter() {
        JPopupMenu popupMenu;

        @Override
        public void mouseClicked(MouseEvent e) {
            if (!SwingUtilities.isRightMouseButton(e) || 1 != e.getClickCount()) {
                return;
            }
            Point pt = e.getPoint();
            int row = fieldLayoutTable.rowAtPoint(pt);
            if (row >= 0) {
                int col = fieldLayoutTable.columnAtPoint(pt);
                if (col >= 0) {
                    Plot plot = fieldViewPanel.getPlotAt(col, row);
                    if (plot != null) {
                        if (popupMenu == null) {
                            popupMenu = new JPopupMenu("View Attachments");
                        }
                        popupMenu.removeAll();

                        Set<File> set = plot.getMediaFiles();
                        if (Check.isEmpty(set)) {
                            popupMenu.add(new JMenuItem("No Attachments available"));
                        } else {
                            for (File file : set) {
                                Action a = new AbstractAction(file.getName()) {
                                    @Override
                                    public void actionPerformed(ActionEvent e) {
                                        try {
                                            Desktop.getDesktop().browse(file.toURI());
                                        } catch (IOException e1) {
                                            MsgBox.warn(FieldViewDialog.this, e1, file.getName());
                                        }
                                    }
                                };
                                popupMenu.add(new JMenuItem(a));
                            }
                        }
                        popupMenu.show(fieldLayoutTable, pt.x, pt.y);
                    }
                }
            }
        }

    });
    Font font = fieldLayoutTable.getFont();
    float fontSize = font.getSize2D();

    fontSizeModel = new SpinnerNumberModel(fontSize, fontSize, 50.0, 1.0);
    fontSpinner.setModel(fontSizeModel);
    fontSizeModel.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            float fsize = fontSizeModel.getNumber().floatValue();
            System.out.println("Using fontSize=" + fsize);
            Font font = fieldLayoutTable.getFont().deriveFont(fsize);
            fieldLayoutTable.setFont(font);
            FontMetrics fm = fieldLayoutTable.getFontMetrics(font);
            int lineHeight = fm.getMaxAscent() + fm.getMaxDescent();
            fieldLayoutTable.setRowHeight(4 * lineHeight);

            //                GuiUtil.initialiseTableColumnWidths(fieldLayoutTable, false);

            fieldLayoutTable.repaint();
        }
    });

    fieldLayoutTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    fieldLayoutTable.setResizable(true, true);
    fieldLayoutTable.getTableColumnResizer().setResizeAllColumns(true);

    advanceAction.setEnabled(false);
    fieldLayoutTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                handlePlotSelection();
            }
        }
    });
    TableColumnModel columnModel = fieldLayoutTable.getColumnModel();
    columnModel.addColumnModelListener(new TableColumnModelListener() {
        @Override
        public void columnSelectionChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                handlePlotSelection();
            }
        }

        @Override
        public void columnRemoved(TableColumnModelEvent e) {
        }

        @Override
        public void columnMoved(TableColumnModelEvent e) {
        }

        @Override
        public void columnMarginChanged(ChangeEvent e) {
        }

        @Override
        public void columnAdded(TableColumnModelEvent e) {
        }
    });

    PropertyChangeListener listener = new PropertyChangeListener() {
        // Use a timer and redisplay other columns when delay is GT 100 ms

        Timer timer = new Timer(true);
        TimerTask timerTask;
        long lastActive;
        boolean busy = false;
        private int eventColumnWidth;
        private TableColumn eventColumn;

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (busy) {
                return;
            }

            if (evt.getSource() instanceof TableColumn && "width".equals(evt.getPropertyName())) {

                eventColumn = (TableColumn) evt.getSource();
                eventColumnWidth = eventColumn.getWidth();

                lastActive = System.currentTimeMillis();
                if (timerTask == null) {
                    timerTask = new TimerTask() {
                        @Override
                        public void run() {
                            if (System.currentTimeMillis() - lastActive > 200) {
                                timerTask.cancel();
                                timerTask = null;

                                busy = true;
                                try {
                                    for (Enumeration<TableColumn> en = columnModel.getColumns(); en
                                            .hasMoreElements();) {
                                        TableColumn tc = en.nextElement();
                                        if (tc != eventColumn) {
                                            tc.setWidth(eventColumnWidth);
                                        }
                                    }
                                } finally {
                                    busy = false;
                                }
                            }
                        }
                    };
                    timer.scheduleAtFixedRate(timerTask, 100, 150);
                }
            }
        }
    };
    for (Enumeration<TableColumn> en = columnModel.getColumns(); en.hasMoreElements();) {
        TableColumn tc = en.nextElement();
        tc.addPropertyChangeListener(listener);
    }

    Map<Integer, Plot> plotById = new HashMap<>();
    for (Plot plot : fieldViewPanel.getFieldLayout()) {
        plotById.put(plot.getPlotId(), plot);
    }

    TrialItemVisitor<Sample> sampleVisitor = new TrialItemVisitor<Sample>() {
        @Override
        public void setExpectedItemCount(int count) {
        }

        @Override
        public boolean consumeItem(Sample sample) throws IOException {

            Plot plot = plotById.get(sample.getPlotId());
            if (plot == null) {
                throw new IOException("Missing plot for plotId=" + sample.getPlotId() + " sampleIdent="
                        + Util.createUniqueSampleKey(sample));
            }
            plot.addSample(sample);

            SampleCounts counts = countsByTraitId.get(sample.getTraitId());
            if (counts == null) {
                counts = new SampleCounts();
                countsByTraitId.put(sample.getTraitId(), counts);
            }
            if (sample.hasBeenScored()) {
                ++counts.scored;
            } else {
                ++counts.unscored;
            }
            return true;
        }
    };
    database.visitSamplesForTrial(sampleGroupChoiceForSamples, trial.getTrialId(),
            SampleOrder.ALL_BY_PLOT_ID_THEN_TRAIT_ID_THEN_INSTANCE_NUMBER_ORDER_THEN_SPECIMEN_NUMBER,
            sampleVisitor);

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    this.trial = trial;

    KDClientUtils.initAction(ImageId.SETTINGS_24, showInfoAction, "Trial Summary");

    Action clear = new AbstractAction("Clear") {
        @Override
        public void actionPerformed(ActionEvent e) {
            infoTextArea.setText("");
        }
    };
    JPanel bottom = new JPanel(new BorderLayout());
    bottom.add(GuiUtil.createLabelSeparator("Plot Details", new JButton(clear)), BorderLayout.NORTH);
    bottom.add(new JScrollPane(infoTextArea), BorderLayout.CENTER);
    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, fieldViewPanel,
            new JScrollPane(infoTextArea));
    splitPane.setResizeWeight(0.0);
    splitPane.setOneTouchExpandable(true);

    setContentPane(splitPane);

    updateMovementControls();
    pack();
}

From source file:com.vgi.mafscaling.ClosedLoop.java

private JTable createAfrDataTable(JPanel panel, String tableName, int gridy) {
    final JTable afrTable = new JTable() {
        private static final long serialVersionUID = 6526901361175099297L;

        public boolean isCellEditable(int row, int column) {
            return false;
        };//from   w ww. ja v  a  2s .  com
    };
    DefaultTableColumnModel afrModel = new DefaultTableColumnModel();
    final TableColumn afrColumn = new TableColumn(0, 250);
    afrColumn.setHeaderValue(tableName);
    afrModel.addColumn(afrColumn);
    JTableHeader lblAfrTableName = afrTable.getTableHeader();
    lblAfrTableName.setColumnModel(afrModel);
    lblAfrTableName.setReorderingAllowed(false);
    DefaultTableCellRenderer headerRenderer = (DefaultTableCellRenderer) lblAfrTableName.getDefaultRenderer();
    headerRenderer.setHorizontalAlignment(SwingConstants.LEFT);

    GridBagConstraints gbc_lblAfrTableName = new GridBagConstraints();
    gbc_lblAfrTableName.insets = new Insets((gridy == 0 ? 0 : 5), 0, 0, 0);
    gbc_lblAfrTableName.anchor = GridBagConstraints.PAGE_START;
    gbc_lblAfrTableName.fill = GridBagConstraints.HORIZONTAL;
    gbc_lblAfrTableName.gridx = 0;
    gbc_lblAfrTableName.gridy = gridy;
    panel.add(lblAfrTableName, gbc_lblAfrTableName);

    afrTable.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            afrColumn.setWidth(afrTable.getWidth());
        }
    });
    afrTable.getTableHeader().setReorderingAllowed(false);
    afrTable.setColumnSelectionAllowed(true);
    afrTable.setCellSelectionEnabled(true);
    afrTable.setBorder(new LineBorder(new Color(0, 0, 0)));
    afrTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    afrTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    afrTable.setModel(new DefaultTableModel(AfrTableRowCount, AfrTableColumnCount));
    Utils.initializeTable(afrTable, ColumnWidth);

    if (tableName.equals(Afr1TableName)) {
        Format[][] formatMatrix = { { new DecimalFormat("#"), new DecimalFormat("0.00") } };
        NumberFormatRenderer renderer = (NumberFormatRenderer) afrTable.getDefaultRenderer(Object.class);
        renderer.setFormats(formatMatrix);
    } else if (tableName.equals(Afr2TableName)) {
        Format[][] formatMatrix = { { new DecimalFormat("#"), new DecimalFormat("0.00") },
                { new DecimalFormat("#"), new DecimalFormat("#") } };
        NumberFormatRenderer renderer = (NumberFormatRenderer) afrTable.getDefaultRenderer(Object.class);
        renderer.setFormats(formatMatrix);
    }

    GridBagConstraints gbc_afrTable = new GridBagConstraints();
    gbc_afrTable.insets = new Insets(0, 0, 0, 0);
    gbc_afrTable.anchor = GridBagConstraints.PAGE_START;
    gbc_afrTable.gridx = 0;
    gbc_afrTable.gridy = gridy + 1;
    panel.add(afrTable, gbc_afrTable);

    excelAdapter.addTable(afrTable, true, false);

    return afrTable;
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopAbstractTable.java

protected void adjustColumnHeaders() {
    List<TableColumn> notInited = new LinkedList<>();
    int summaryWidth = 0;
    int componentWidth = impl.getParent().getWidth();

    // take into account only visible columns
    Enumeration<TableColumn> columnEnumeration = impl.getColumnModel().getColumns();
    while (columnEnumeration.hasMoreElements()) {
        TableColumn tableColumn = columnEnumeration.nextElement();
        Column column = (Column) tableColumn.getIdentifier();

        Integer width = column.getWidth();
        if (width != null) {
            tableColumn.setPreferredWidth(width);
            tableColumn.setWidth(width);
            summaryWidth += width;//from  w  ww .jav a2s. co m
        } else {
            notInited.add(tableColumn);
        }
    }

    if (notInited.size() != impl.getColumnCount()) {
        impl.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        if (!notInited.isEmpty() && (componentWidth > summaryWidth)) {
            int defaultWidth = (componentWidth - summaryWidth) / notInited.size();
            for (TableColumn column : notInited) {
                column.setPreferredWidth(Math.max(defaultWidth, column.getWidth()));
            }
        }
    }
}

From source file:nz.govt.natlib.ndha.manualdeposit.bulkupload.BulkUploadPresenter.java

private void setupColumns() {
    final TableRenderer renderer = new TableRenderer();
    final int width = 50;
    for (int i = 0; i < theJobListTable.getColumnCount(); i++) {
        final TableColumn col = theJobListTable.getColumnModel().getColumn(i);
        col.setCellRenderer(renderer);//from  www.j a  v a 2s . c  o m
        col.setResizable(true);
        if (i < (theJobListTable.getColumnCount() - 1)) {
            col.setPreferredWidth(width);
            col.setWidth(width);
        }
    }
}

From source file:nz.govt.natlib.ndha.manualdeposit.CMSSearchResults.java

@SuppressWarnings("serial")
private void formWindowOpened(java.awt.event.WindowEvent evt) { // NOPMD
    try {//from  w w  w .  ja  va  2s  .c  o  m
        theFormControl = new FormControl(this, theSettingsPath);
    } catch (Exception ex) {
        LOG.error("Error loading form parameters", ex);
    }
    if (theFormControl != null) {
        final Action updateDividersAction = new AbstractAction() {
            public void actionPerformed(final ActionEvent e) {
                Timer t = (Timer) e.getSource();
                t.stop();
                splitMain.setDividerLocation(theFormControl.getExtra(SPLIT_NAME, 320));
                splitMain.repaint();
                for (int i = 0; i < tblResults.getColumnModel().getColumnCount(); i++) {
                    TableColumn col = tblResults.getColumnModel().getColumn(i);
                    String colName = "Col" + i;
                    int width = theFormControl.getExtra(colName, 150);
                    col.setPreferredWidth(width);
                    col.setWidth(width);
                }
            }
        };
        new Timer(200, updateDividersAction).start();
    }
    thePresenter.showResults();
}

From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositPresenter.java

private void setJobQueueTableDefaults(JTable jobQueueTable, JobQueueTableModel jobQueueTableModel) {
    jobQueueTableModel.addTableModelListener(new JobQueueTableModelListener());
    jobQueueTable.setModel(jobQueueTableModel);
    jobQueueTable.setSurrendersFocusOnKeystroke(true);
    jobQueueTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    jobQueueTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    jobQueueTable.setColumnSelectionAllowed(true);
    jobQueueTable.setRowSelectionAllowed(true);
    TableRenderer renderer = new TableRenderer();
    TableColumn col = jobQueueTable.getColumnModel().getColumn(0);
    int width = 200;
    col.setPreferredWidth(width);//from   w  ww .ja va  2 s  . c o m
    col.setWidth(width);
    col.setCellRenderer(renderer);

    col = jobQueueTable.getColumnModel().getColumn(1);
    width = 1400;
    col.setPreferredWidth(width);
    col.setWidth(width);
    col.setCellRenderer(renderer);
}

From source file:org.executequery.gui.resultset.ResultSetTable.java

public void setTableColumnWidth(int columnWidth) {

    TableColumnModel tcm = getColumnModel();
    if (columnWidth != 75) {

        TableColumn col = null;
        for (Enumeration<TableColumn> i = tcm.getColumns(); i.hasMoreElements();) {
            col = i.nextElement();/*from w  w  w  .  ja v  a2  s  .  c  o  m*/
            col.setWidth(columnWidth);
            col.setPreferredWidth(columnWidth);
        }

    }
}

From source file:org.nuclos.client.ui.collect.SubForm.java

/**
 * sets all column widths to user preferences; set optimal width if no preferences yet saved
 * @param tableColumnWidthsFromPreferences
 */// w  w  w .j a va  2  s . c  o  m
public final void setColumnWidths(List<Integer> tableColumnWidthsFromPreferences) {
    useCustomColumnWidths = !tableColumnWidthsFromPreferences.isEmpty()
            && tableColumnWidthsFromPreferences.size() <= subformtbl.getColumnCount();
    if (useCustomColumnWidths) {
        assert (tableColumnWidthsFromPreferences.size() <= subformtbl.getColumnCount());
        final Enumeration<TableColumn> enumeration = subformtbl.getColumnModel().getColumns();
        int iColumn = 0;
        while (enumeration.hasMoreElements()) {
            final TableColumn column = enumeration.nextElement();
            final int iPreferredCellWidth;
            if (iColumn < tableColumnWidthsFromPreferences.size()) {
                // known column
                iPreferredCellWidth = tableColumnWidthsFromPreferences.get(iColumn++);
            } else {
                // new column
                iPreferredCellWidth = getDefaultColumnWidth(column, iColumn++);
            }
            column.setPreferredWidth(iPreferredCellWidth);
            column.setWidth(iPreferredCellWidth);
        }
    } else {
        resetDefaultColumnWidths();
    }
}

From source file:org.nuclos.client.ui.collect.SubForm.java

public final void resetDefaultColumnWidths() {
    if (subformtbl != null) {
        for (int iColumn = 0; iColumn < subformtbl.getColumnCount(); iColumn++) {
            final TableColumn tableColumn = subformtbl.getColumnModel().getColumn(iColumn);
            final int width = getDefaultColumnWidth(tableColumn, iColumn);
            tableColumn.setPreferredWidth(width);
            tableColumn.setWidth(width);
        }/*  ww w.  ja v  a2  s.  c o  m*/
        useCustomColumnWidths = false;
        subformtbl.revalidate();
    }
}

From source file:org.openflexo.technologyadapter.excel.view.ExcelSheetView.java

public ExcelSheetView(ExcelSheet sheet, FlexoController controller) {
    super(new BorderLayout());
    this.sheet = sheet;
    this.controller = controller;
    tableModel = new ExcelSheetTableModel();
    table = new MultiSpanCellTable(tableModel);
    table.setBackground(Color.WHITE);
    table.setShowGrid(true);//from   www .j a v  a 2 s .c  o m
    table.setGridColor(Color.LIGHT_GRAY);
    table.setRowMargin(0);
    table.getColumnModel().setColumnMargin(0);

    for (int i = 0; i < tableModel.getColumnCount(); i++) {
        TableColumn col = table.getColumnModel().getColumn(i);
        if (i == 0) {
            col.setWidth(25);
            col.setPreferredWidth(25);
            col.setMinWidth(25);
            col.setMaxWidth(100);
            // col.setResizable(false);
            col.setHeaderValue(null);
        } else {
            col.setWidth(sheet.getSheet().getColumnWidth(i - 1) / 40);
            col.setPreferredWidth(sheet.getSheet().getColumnWidth(i - 1) / 40);
            col.setHeaderValue("" + Character.toChars(i + 64)[0]);
        }
    }
    table.setDefaultRenderer(Object.class, new ExcelSheetCellRenderer());
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    add(new JScrollPane(table), BorderLayout.CENTER);

    cellIdentifier = new JTextField(6);
    cellIdentifier.setEditable(false);
    cellIdentifier.setHorizontalAlignment(SwingConstants.CENTER);
    cellValue = new JTextField();
    cellValue.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            valueEditedForSelectedCell(cellValue.getText());
        }
    });
    /*cellValue.getDocument().addDocumentListener(new DocumentListener() {
       @Override
       public void removeUpdate(DocumentEvent e) {
    valueEditedForSelectedCell(cellValue.getText());
       }
            
       @Override
       public void insertUpdate(DocumentEvent e) {
    valueEditedForSelectedCell(cellValue.getText());
       }
            
       @Override
       public void changedUpdate(DocumentEvent e) {
    valueEditedForSelectedCell(cellValue.getText());
       }
    });*/
    JPanel topPanel = new JPanel(new BorderLayout());
    topPanel.add(cellIdentifier, BorderLayout.WEST);
    topPanel.add(cellValue, BorderLayout.CENTER);
    add(topPanel, BorderLayout.NORTH);

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            selectionChanged();
        }
    });
    table.getColumnModel().addColumnModelListener(new TableColumnModelListener() {

        @Override
        public void columnSelectionChanged(ListSelectionEvent e) {
            selectionChanged();
        }

        @Override
        public void columnRemoved(TableColumnModelEvent e) {
        }

        @Override
        public void columnMoved(TableColumnModelEvent e) {
        }

        @Override
        public void columnMarginChanged(ChangeEvent e) {
        }

        @Override
        public void columnAdded(TableColumnModelEvent e) {
        }
    });

    updateRowHeights();

    validate();

    /*for (Object p : sheet.getSheet().getWorkbook().getAllPictures()) {
       System.out.println("Picture: " + p);
    }
            
    System.out.println("class = " + sheet.getSheet().getClass());
            
    if (sheet.getSheet() instanceof HSSFSheet) {
            
       List<HSSFShape> shapes = ((HSSFSheet) sheet.getSheet()).getDrawingPatriarch().getChildren();
       System.out.println("Prout=" + shapes);
       for (int i = 0; i < shapes.size(); i++) {
    System.out.println("hop avec " + shapes.get(i));
    if (shapes.get(i) instanceof HSSFPicture) {
       HSSFPicture pic = (HSSFPicture) shapes.get(i);
       HSSFPictureData picdata = ((HSSFSheet) sheet.getSheet()).getWorkbook().getAllPictures().get(pic.getPictureIndex());
            
       System.out.println("New picture found : " + pic);
       System.out.println("Anchor : " + pic.getAnchor());
       System.out.println("file extension " + picdata.suggestFileExtension());
            
       // int pictureIndex = this.newSheet.getWorkbook().addPicture( picdata.getData(), picdata.getFormat());
            
       // this.newSheet.createDrawingPatriarch().createPicture((HSSFClientAnchor)pic.getAnchor()r, pictureIndex);
            
    }
            
       }
    }*/
}