List of usage examples for javax.swing JTable setAutoResizeMode
@BeanProperty(enumerationValues = { "JTable.AUTO_RESIZE_OFF", "JTable.AUTO_RESIZE_NEXT_COLUMN", "JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS", "JTable.AUTO_RESIZE_LAST_COLUMN", "JTable.AUTO_RESIZE_ALL_COLUMNS" }, description = "Whether the columns should adjust themselves automatically.") public void setAutoResizeMode(int mode)
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 va 2 s . 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:fs.MainWindow.java
public void GenerateTable(Object[][] data, String title, String subtitle, final String[] titles) { JFrame window = new JFrame(title); window.setLayout(new java.awt.BorderLayout(5, 5)); JLabel label = new JLabel(subtitle); label.setFont(new java.awt.Font("Tahoma", 1, 12)); label.setForeground(new java.awt.Color(0, 0, 255)); label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label.setOpaque(true);/* ww w . j a va 2s .c o m*/ label.setPreferredSize(new java.awt.Dimension(50, 30)); ListModel lm = new AbstractListModel() { String headers[] = titles; @Override public int getSize() { return headers.length; } @Override public Object getElementAt(int index) { return headers[index]; } }; // String[] titles = getClasses(); JList rowHeader = new JList(lm); rowHeader.setFixedCellWidth(50); JTable jTable = new JTable(data, titles); rowHeader.setFixedCellHeight(jTable.getRowHeight()); rowHeader.setCellRenderer(new RowHeaderRenderer(jTable)); JScrollPane scroll = new JScrollPane(jTable); scroll.setRowHeaderView(rowHeader); getContentPane().add(scroll, BorderLayout.CENTER); jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); jTable.setAlignmentX(JTable.CENTER_ALIGNMENT); window.add(label, java.awt.BorderLayout.NORTH); window.add(scroll, java.awt.BorderLayout.CENTER); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); window.setBounds((screenSize.width - 800) / 2, (screenSize.height - 270) / 2, 800, 270); window.setVisible(true); }
From source file:captureplugin.CapturePlugin.java
/** * Check the programs after data update. *//*from www . jav a 2 s. c o m*/ public void handleTvDataUpdateFinished() { mNeedsUpdate = true; if (mAllowedToShowDialog) { mNeedsUpdate = false; DeviceIf[] devices = mConfig.getDeviceArray(); final DefaultTableModel model = new DefaultTableModel() { public boolean isCellEditable(int row, int column) { return false; } }; model.setColumnCount(5); model.setColumnIdentifiers(new String[] { mLocalizer.msg("device", "Device"), Localizer.getLocalization(Localizer.I18N_CHANNEL), mLocalizer.msg("date", "Date"), ProgramFieldType.START_TIME_TYPE.getLocalizedName(), ProgramFieldType.TITLE_TYPE.getLocalizedName() }); JTable table = new JTable(model); table.getTableHeader().setReorderingAllowed(false); table.getTableHeader().setResizingAllowed(false); table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() { public Component getTableCellRendererComponent(JTable renderTable, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = super.getTableCellRendererComponent(renderTable, value, isSelected, hasFocus, row, column); if (value instanceof DeviceIf) { if (((DeviceIf) value).getDeleteRemovedProgramsAutomatically() && !isSelected) { c.setForeground(Color.red); } } return c; } }); int[] columnWidth = new int[5]; for (int i = 0; i < columnWidth.length; i++) { columnWidth[i] = UiUtilities.getStringWidth(table.getFont(), model.getColumnName(i)) + 10; } for (DeviceIf device : devices) { Program[] deleted = device.checkProgramsAfterDataUpdateAndGetDeleted(); if (deleted != null && deleted.length > 0) { for (Program p : deleted) { if (device.getDeleteRemovedProgramsAutomatically() && !p.isExpired() && !p.isOnAir()) { device.remove(UiUtilities.getLastModalChildOf(getParentFrame()), p); } else { device.removeProgramWithoutExecution(p); } if (!p.isExpired()) { Object[] o = new Object[] { device, p.getChannel().getName(), p.getDateString(), p.getTimeString(), p.getTitle() }; for (int i = 0; i < columnWidth.length; i++) { columnWidth[i] = Math.max(columnWidth[i], UiUtilities.getStringWidth(table.getFont(), o[i].toString()) + 10); } model.addRow(o); } } } device.getProgramList(); } if (model.getRowCount() > 0) { int sum = 0; for (int i = 0; i < columnWidth.length; i++) { table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth[i]); if (i < columnWidth.length - 1) { table.getColumnModel().getColumn(i).setMaxWidth(columnWidth[i]); } sum += columnWidth[i]; } JScrollPane scrollPane = new JScrollPane(table); scrollPane.setPreferredSize(new Dimension(450, 250)); if (sum > 500) { table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); scrollPane.getViewport().setPreferredSize( new Dimension(sum, scrollPane.getViewport().getPreferredSize().height)); } JButton export = new JButton(mLocalizer.msg("exportList", "Export list")); export.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setDialogType(JFileChooser.SAVE_DIALOG); chooser.setFileFilter(new FileFilter() { public boolean accept(File f) { return f.isDirectory() || f.toString().toLowerCase().endsWith(".txt"); } public String getDescription() { return "*.txt"; } }); chooser.setSelectedFile(new File("RemovedPrograms.txt")); if (chooser.showSaveDialog( UiUtilities.getLastModalChildOf(getParentFrame())) == JFileChooser.APPROVE_OPTION) { if (chooser.getSelectedFile() != null) { String file = chooser.getSelectedFile().getAbsolutePath(); if (!file.toLowerCase().endsWith(".txt") && file.indexOf('.') == -1) { file = file + ".txt"; } if (file.indexOf('.') != -1) { try { RandomAccessFile write = new RandomAccessFile(file, "rw"); write.setLength(0); String eolStyle = File.separator.equals("/") ? "\n" : "\r\n"; for (int i = 0; i < model.getRowCount(); i++) { StringBuilder line = new StringBuilder(); for (int j = 0; j < model.getColumnCount(); j++) { line.append(model.getValueAt(i, j)).append(' '); } line.append(eolStyle); write.writeBytes(line.toString()); } write.close(); } catch (Exception ee) { } } } } } }); Object[] message = { mLocalizer.msg("deletedText", "The data was changed and the following programs were deleted:"), scrollPane, export }; JOptionPane pane = new JOptionPane(); pane.setMessage(message); pane.setMessageType(JOptionPane.PLAIN_MESSAGE); final JDialog d = pane.createDialog(UiUtilities.getLastModalChildOf(getParentFrame()), mLocalizer.msg("CapturePlugin", "CapturePlugin") + " - " + mLocalizer.msg("deletedTitle", "Deleted programs")); d.setResizable(true); d.setModal(false); SwingUtilities.invokeLater(new Runnable() { public void run() { d.setVisible(true); } }); } } }
From source file:edu.ku.brc.specify.tasks.subpane.wb.DataImportDialog.java
/** * Parses the given import 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. * @param table - the table to display the data * @return/*from w w w. j a va 2 s . c o m*/ * JTable - the table to display the data */ private JTable setCSVTableData(final JTable table) { try { log.debug("setTableData - file - " + configCSV.getFile().toString()); CsvReader csv = new CsvReader(new FileInputStream(configCSV.getFile()), configCSV.getDelimiter(), configCSV.getCharset()); csv.setEscapeMode(configCSV.getEscapeMode()); csv.setTextQualifier(configCSV.getTextQualifier()); String[] headers = {}; Vector<String[]> tableDataVector = new Vector<String[]>(); highestColumnCount = getLargestColumnCountFromCSV(); if (configCSV.getFirstRowHasHeaders()) { csv.readHeaders(); headers = csv.getHeaders(); } int rowColumnCount = 0; while (csv.readRecord()) { //how many columns does this row of data contain rowColumnCount = csv.getColumnCount(); //create an array that contains teh row data String[] rowData = new String[csv.getColumnCount()]; for (int col = 0; col < csv.getColumnCount(); col++) { rowData[col] = csv.get(col); } //if the column count in this row of data is not as large //as the column header count, then "insert" blank string into the cells String[] newArray = padArray(highestColumnCount, rowData, false); //stick the row data into a vector because we do not know how many //rows of data there are tableDataVector.add(newArray); } if (!configCSV.getFirstRowHasHeaders() || headers == null) { //create headers with names Column1, Column2... headers = createDummyHeaders(rowColumnCount); } //if the header count is not as large as the longest column count in the data set //create dummy headers and append to end of table. headers = padArray(highestColumnCount, headers, true); log.debug("---------------------------------------------------"); printArray(headers); log.debug("---------------------------------------------------"); //pull row data out of vector and stick into an array for table model. String[][] tableData = new String[tableDataVector.size()][rowColumnCount]; for (int i = 0; i < tableData.length; i++) { tableData[i] = tableDataVector.elementAt(i); printArray(tableData[i]); } if (checkForErrors(headers, tableData)) { errorPanel.showDataImportStatusPanel(true); } else { errorPanel.showDataImportStatusPanel(false); } if ((doesFirstRowHaveHeaders ? tableDataVector.size() - 1 : tableDataVector.size()) > WorkbenchTask.MAX_ROWS) { hasTooManyRows = true; showTooManyRowsErrorDialog(); } else { hasTooManyRows = false; } model = new PreviewTableModel(headers, tableData); 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; } catch (IOException ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataImportDialog.class, ex); log.error("Error attempting to parse input csv file:" + ex); } return null; }
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 ww w .ja v a 2 s .co 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.apache.oodt.cas.workflow.gui.perspective.view.impl.DefaultPropView.java
private JTable createTable(final ViewState state) { JTable table; final ModelGraph selected = state.getSelected(); if (selected != null) { final Vector<Vector<String>> rows = new Vector<Vector<String>>(); ConcurrentHashMap<String, String> keyToGroupMap = new ConcurrentHashMap<String, String>(); Metadata staticMet = selected.getModel().getStaticMetadata(); Metadata inheritedMet = selected.getInheritedStaticMetadata(state); Metadata completeMet = new Metadata(); if (staticMet != null) { completeMet.replaceMetadata(staticMet.getSubMetadata(state.getCurrentMetGroup())); }/*ww w . java 2 s .c o m*/ if (selected.getModel().getExtendsConfig() != null) { for (String configGroup : selected.getModel().getExtendsConfig()) { Metadata extendsMetadata = state.getGlobalConfigGroups().get(configGroup).getMetadata() .getSubMetadata(state.getCurrentMetGroup()); for (String key : extendsMetadata.getAllKeys()) { if (!completeMet.containsKey(key)) { keyToGroupMap.put(key, configGroup); completeMet.replaceMetadata(key, extendsMetadata.getAllMetadata(key)); } } } } if (inheritedMet != null) { Metadata inheritedMetadata = inheritedMet.getSubMetadata(state.getCurrentMetGroup()); for (String key : inheritedMetadata.getAllKeys()) { if (!completeMet.containsKey(key)) { keyToGroupMap.put(key, "__inherited__"); completeMet.replaceMetadata(key, inheritedMetadata.getAllMetadata(key)); } } } List<String> keys = completeMet.getAllKeys(); Collections.sort(keys); for (String key : keys) { if (key.endsWith("/envReplace")) { continue; } String values = StringUtils.join(completeMet.getAllMetadata(key), ","); Vector<String> row = new Vector<String>(); row.add(keyToGroupMap.get(key)); row.add(key); row.add(values); row.add(Boolean.toString(Boolean.parseBoolean(completeMet.getMetadata(key + "/envReplace")))); rows.add(row); } table = new JTable();// rows, new Vector<String>(Arrays.asList(new // String[] { "key", "values", "envReplace" }))); table.setModel(new AbstractTableModel() { public String getColumnName(int col) { switch (col) { case 0: return "group"; case 1: return "key"; case 2: return "values"; case 3: return "envReplace"; default: return null; } } public int getRowCount() { return rows.size() + 1; } public int getColumnCount() { return 4; } public Object getValueAt(int row, int col) { if (row >= rows.size()) { return null; } String value = rows.get(row).get(col); if (value == null && col == 3) { return "false"; } if (value == null && col == 0) { return "__local__"; } return value; } public boolean isCellEditable(int row, int col) { if (row >= rows.size()) { return selected.getModel().getStaticMetadata().containsGroup(state.getCurrentMetGroup()); } if (col == 0) { return false; } String key = rows.get(row).get(1); return key == null || (selected.getModel().getStaticMetadata() != null && selected.getModel().getStaticMetadata().containsKey(getKey(key, state))); } public void setValueAt(Object value, int row, int col) { if (row >= rows.size()) { Vector<String> newRow = new Vector<String>( Arrays.asList(new String[] { null, null, null, null })); newRow.add(col, (String) value); rows.add(newRow); } else { Vector<String> rowValues = rows.get(row); rowValues.add(col, (String) value); rowValues.remove(col + 1); } this.fireTableCellUpdated(row, col); } }); MyTableListener tableListener = new MyTableListener(state); table.getModel().addTableModelListener(tableListener); table.getSelectionModel().addListSelectionListener(tableListener); } else { table = new JTable(new Vector<Vector<String>>(), new Vector<String>(Arrays.asList(new String[] { "key", "values", "envReplace" }))); } // table.setFillsViewportHeight(true); table.setSelectionBackground(Color.cyan); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); TableCellRenderer cellRenderer = new TableCellRenderer() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel field = new JLabel((String) value); if (column == 0) { field.setForeground(Color.gray); } else { if (isSelected) { field.setBorder(new EtchedBorder(1)); } if (table.isCellEditable(row, 1)) { field.setForeground(Color.black); } else { field.setForeground(Color.gray); } } return field; } }; TableColumn groupCol = table.getColumnModel().getColumn(0); groupCol.setPreferredWidth(75); groupCol.setCellRenderer(cellRenderer); TableColumn keyCol = table.getColumnModel().getColumn(1); keyCol.setPreferredWidth(200); keyCol.setCellRenderer(cellRenderer); TableColumn valuesCol = table.getColumnModel().getColumn(2); valuesCol.setPreferredWidth(300); valuesCol.setCellRenderer(cellRenderer); TableColumn envReplaceCol = table.getColumnModel().getColumn(3); envReplaceCol.setPreferredWidth(75); envReplaceCol.setCellRenderer(cellRenderer); table.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3 && DefaultPropView.this.table.getSelectedRow() != -1) { int row = DefaultPropView.this.table.getSelectedRow();// rowAtPoint(DefaultPropView.this.table.getMousePosition()); String key = getKey((String) DefaultPropView.this.table.getValueAt(row, 1), state); Metadata staticMet = state.getSelected().getModel().getStaticMetadata(); override.setVisible(staticMet == null || !staticMet.containsKey(key)); delete.setVisible(staticMet != null && staticMet.containsKey(key)); tableMenu.show(DefaultPropView.this.table, e.getX(), e.getY()); } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } }); return table; }
From source file:org.executequery.gui.browser.TableDataTab.java
private Object setTableResultsPanel(DatabaseObject databaseObject) { tableDataChanges.clear();//from ww w. ja v a2s . c o m primaryKeyColumns.clear(); foreignKeyColumns.clear(); this.databaseObject = databaseObject; try { initialiseModel(); tableModel.setCellsEditable(false); tableModel.removeTableModelListener(this); if (isDatabaseTable()) { DatabaseTable databaseTable = asDatabaseTable(); if (databaseTable.hasPrimaryKey()) { primaryKeyColumns = databaseTable.getPrimaryKeyColumnNames(); canEditTableLabel.setText("This table has a primary key(s) and data may be edited here"); } if (databaseTable.hasForeignKey()) { foreignKeyColumns = databaseTable.getForeignKeyColumnNames(); } if (primaryKeyColumns.isEmpty()) { canEditTableLabel.setText("This table has no primary keys defined and is not editable here"); } canEditTableNotePanel.setVisible(alwaysShowCanEditNotePanel); } if (!isDatabaseTable()) { canEditTableNotePanel.setVisible(false); } Log.debug("Retrieving data for table - " + databaseObject.getName()); ResultSet resultSet = databaseObject.getData(true); tableModel.createTable(resultSet); if (table == null) { createResultSetTable(); } tableModel.setNonEditableColumns(primaryKeyColumns); TableSorter sorter = new TableSorter(tableModel); table.setModel(sorter); sorter.setTableHeader(table.getTableHeader()); if (isDatabaseTable()) { SortableHeaderRenderer renderer = new SortableHeaderRenderer(sorter) { private ImageIcon primaryKeyIcon = GUIUtilities .loadIcon(BrowserConstants.PRIMARY_COLUMNS_IMAGE); private ImageIcon foreignKeyIcon = GUIUtilities .loadIcon(BrowserConstants.FOREIGN_COLUMNS_IMAGE); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { DefaultTableCellRenderer renderer = (DefaultTableCellRenderer) super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); Icon keyIcon = iconForValue(value); if (keyIcon != null) { Icon icon = renderer.getIcon(); if (icon != null) { BufferedImage image = new BufferedImage( icon.getIconWidth() + keyIcon.getIconWidth() + 2, Math.max(keyIcon.getIconHeight(), icon.getIconHeight()), BufferedImage.TYPE_INT_ARGB); Graphics graphics = image.getGraphics(); keyIcon.paintIcon(null, graphics, 0, 0); icon.paintIcon(null, graphics, keyIcon.getIconWidth() + 2, 5); setIcon(new ImageIcon(image)); } else { setIcon(keyIcon); } } return renderer; } private ImageIcon iconForValue(Object value) { if (value != null) { String name = value.toString(); if (primaryKeyColumns.contains(name)) { return primaryKeyIcon; } else if (foreignKeyColumns.contains(name)) { return foreignKeyIcon; } } return null; } }; sorter.setTableHeaderRenderer(renderer); } table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); scroller.getViewport().add(table); removeAll(); add(canEditTableNotePanel, canEditTableNoteConstraints); add(scroller, scrollerConstraints); if (displayRowCount && SystemProperties.getBooleanProperty("user", "browser.query.row.count")) { add(rowCountPanel, rowCountPanelConstraints); rowCountField.setText(String.valueOf(sorter.getRowCount())); } } catch (DataSourceException e) { if (!cancelled) { addErrorLabel(e); } else { addCancelledLabel(); } } finally { tableModel.addTableModelListener(this); } setTableProperties(); validate(); repaint(); return "done"; }
From source file:org.formic.wizard.step.gui.FeatureListStep.java
/** * {@inheritDoc}/*from www. ja va 2 s . c o m*/ * @see org.formic.wizard.step.GuiStep#init() */ public Component init() { featureInfo = new JEditorPane("text/html", StringUtils.EMPTY); featureInfo.setEditable(false); featureInfo.addHyperlinkListener(new HyperlinkListener()); Feature[] features = provider.getFeatures(); JTable table = new JTable(features.length, 1) { private static final long serialVersionUID = 1L; public Class getColumnClass(int column) { return getValueAt(0, column).getClass(); } public boolean isCellEditable(int row, int column) { return false; } }; table.setBackground(new javax.swing.JList().getBackground()); GuiForm form = createForm(); for (int ii = 0; ii < features.length; ii++) { final Feature feature = (Feature) features[ii]; final JCheckBox box = new JCheckBox(); String name = getName() + '.' + feature.getKey(); form.bind(name, box); box.putClientProperty("feature", feature); featureMap.put(feature.getKey(), box); if (feature.getInfo() == null) { feature.setInfo(Installer.getString(getName() + "." + feature.getKey() + ".html")); } feature.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { if (Feature.ENABLED_PROPERTY.equals(event.getPropertyName())) { if (box.isSelected() != feature.isEnabled()) { box.setSelected(feature.isEnabled()); } } } }); box.setText(Installer.getString(name)); box.setBackground(table.getBackground()); if (!feature.isAvailable()) { box.setSelected(false); box.setEnabled(false); } table.setValueAt(box, ii, 0); } FeatureListMouseListener mouseListener = new FeatureListMouseListener(); for (int ii = 0; ii < features.length; ii++) { Feature feature = (Feature) features[ii]; if (feature.isEnabled() && feature.isAvailable()) { JCheckBox box = (JCheckBox) featureMap.get(feature.getKey()); box.setSelected(true); mouseListener.processDependencies(feature); mouseListener.processExclusives(feature); } } table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setShowHorizontalLines(false); table.setShowVerticalLines(false); table.setDefaultRenderer(JCheckBox.class, new ComponentTableCellRenderer()); table.addKeyListener(new FeatureListKeyListener()); table.addMouseListener(mouseListener); table.getSelectionModel().addListSelectionListener(new FeatureListSelectionListener(table)); table.setRowSelectionInterval(0, 0); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); JPanel container = new JPanel(new BorderLayout()); container.add(table, BorderLayout.CENTER); panel.add(new JScrollPane(container), BorderLayout.CENTER); JScrollPane infoScroll = new JScrollPane(featureInfo); infoScroll.setMinimumSize(new Dimension(0, 50)); infoScroll.setMaximumSize(new Dimension(0, 50)); infoScroll.setPreferredSize(new Dimension(0, 50)); panel.add(infoScroll, BorderLayout.SOUTH); return panel; }
From source file:org.isatools.isacreator.gui.formelements.SubForm.java
protected void setTableProperties(JTable table, boolean isFieldName) { Font font = (!isFieldName) ? UIHelper.VER_12_PLAIN : UIHelper.VER_12_BOLD; table.setFont(font);/*from w w w .j a v a 2s . co m*/ table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setColumnSelectionAllowed(true); table.setRowSelectionAllowed(true); table.setGridColor(UIHelper.LIGHT_GREEN_COLOR); table.setShowGrid(true); }
From source file:org.isatools.isacreator.spreadsheet.Spreadsheet.java
/** * Setup the JTable with its desired characteristics *///from w ww.j a v a 2 s . c o m private void setupTable() { table = new CustomTable(spreadsheetModel); table.setShowGrid(true); table.setGridColor(Color.BLACK); table.setShowVerticalLines(true); table.setShowHorizontalLines(true); table.setGridColor(UIHelper.LIGHT_GREEN_COLOR); table.setRowSelectionAllowed(true); table.setColumnSelectionAllowed(true); table.setAutoCreateColumnsFromModel(false); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.getSelectionModel().addListSelectionListener(this); table.getColumnModel().getSelectionModel().addListSelectionListener(this); table.getTableHeader().setReorderingAllowed(true); table.getColumnModel().addColumnModelListener(this); try { table.setDefaultRenderer(Class.forName("java.lang.Object"), new SpreadsheetCellRenderer()); } catch (ClassNotFoundException e) { // ignore this error } table.addMouseListener(this); table.getTableHeader().addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent event) { } public void mouseMoved(MouseEvent event) { // display a tooltip when user hovers over a column. tooltip is derived // from the description of a field from the TableReferenceObject. JTable table = ((JTableHeader) event.getSource()).getTable(); TableColumnModel colModel = table.getColumnModel(); int colIndex = colModel.getColumnIndexAtX(event.getX()); // greater than 1 to account for the row no. being the first col if (colIndex >= 1) { TableColumn tc = colModel.getColumn(colIndex); if (tc != null) { try { table.getTableHeader().setToolTipText(getFieldDescription(tc)); } catch (Exception e) { // ignore this error } } } } }); //table.getColumnModel().addColumnModelListener(this); InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0); // Override the default tab behaviour // Tab to the next editable cell. When no editable cells goto next cell. final Action previousTabAction = table.getActionMap().get(im.get(tab)); Action newTabAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { // maintain previous tab action procedure previousTabAction.actionPerformed(e); JTable table = (JTable) e.getSource(); int row = table.getSelectedRow(); int originalRow = row; int column = table.getSelectedColumn(); int originalColumn = column; while (!table.isCellEditable(row, column)) { previousTabAction.actionPerformed(e); row = table.getSelectedRow(); column = table.getSelectedColumn(); // Back to where we started, get out. if ((row == originalRow) && (column == originalColumn)) { break; } } if (table.editCellAt(row, column)) { table.getEditorComponent().requestFocusInWindow(); } } }; table.getActionMap().put(im.get(tab), newTabAction); TableColumnModel model = table.getColumnModel(); String previousColumnName = null; for (int columnIndex = 0; columnIndex < tableReferenceObject.getHeaders().size(); columnIndex++) { if (!model.getColumn(columnIndex).getHeaderValue().toString() .equals(TableReferenceObject.ROW_NO_TEXT)) { model.getColumn(columnIndex).setHeaderRenderer(columnRenderer); model.getColumn(columnIndex).setPreferredWidth(spreadsheetFunctions .calcColWidths(model.getColumn(columnIndex).getHeaderValue().toString())); // add appropriate cell editor for cell. spreadsheetFunctions.addCellEditor(model.getColumn(columnIndex), previousColumnName); previousColumnName = model.getColumn(columnIndex).getHeaderValue().toString(); } else { model.getColumn(columnIndex).setHeaderRenderer(new RowNumberCellRenderer()); } } JTableHeader header = table.getTableHeader(); header.setBackground(UIHelper.BG_COLOR); header.addMouseListener(new HeaderListener(header, columnRenderer)); table.addNotify(); }