Java Code Examples for javax.swing.table.DefaultTableModel

The following examples show how to use javax.swing.table.DefaultTableModel. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
private void saveCapabilities() {
    if (capTable.isEditing()) {
        capTable.getCellEditor().stopCellEditing();
    }
    DefaultTableModel model = (DefaultTableModel) capTable.getModel();
    LinkedProperties properties = new LinkedProperties();
    for (int i = 0; i < model.getRowCount(); i++) {
        String prop = Objects.toString(model.getValueAt(i, 0), "").trim();
        if (!prop.isEmpty()) {
            String value = Objects.toString(model.getValueAt(i, 1), "");
            properties.setProperty(prop, value);
        }
    }
    settings.getCapabilities().addCapability(browserCombo.getSelectedItem().toString(),
            properties);
}
 
Example 2
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
private MainPanel() {
  super(new BorderLayout());

  String[] columnNames = {"Column1", "Column2"};
  Object[][] data = {
    {"colors", makeModel("blue", "violet", "red", "yellow")},
    {"sports", makeModel("basketball", "soccer", "football", "hockey")},
    {"food", makeModel("hot dogs", "pizza", "ravioli", "bananas")},
  };
  TableModel model = new DefaultTableModel(data, columnNames) {
    @Override public Class<?> getColumnClass(int column) {
      return column == 1 ? DefaultComboBoxModel.class : String.class;
    }
  };
  JTable table = new JTable(model);
  table.setRowHeight(24);
  table.setAutoCreateRowSorter(true);

  TableColumn col = table.getColumnModel().getColumn(1);
  col.setCellRenderer(new ComboCellRenderer());
  col.setCellEditor(new ComboCellEditor());

  add(new JScrollPane(table));
  setPreferredSize(new Dimension(320, 240));
}
 
Example 3
public void testDataSchemaForPlainTables() throws ReportDataFactoryException {
  final DefaultTableModel model = new DefaultTableModel();
  model.addColumn( "Test" );

  final ResourceManager mgr = new ResourceManager();
  mgr.registerDefaults();

  final DataSchemaDefinition schemaDefinition = DataSchemaUtility.parseDefaults( mgr );
  final DataSchemaCompiler compiler =
      new DataSchemaCompiler( schemaDefinition, new DefaultDataAttributeContext(), mgr );
  final DataSchema compiledSchema = compiler.compile( model );
  final DataAttributes attributes = compiledSchema.getAttributes( "Test" );
  assertNotNull( attributes );
  assertEquals( "Test", attributes.getMetaAttribute( MetaAttributeNames.Formatting.NAMESPACE,
      MetaAttributeNames.Formatting.LABEL, String.class, new DefaultDataAttributeContext() ) );
}
 
Example 4
Source Project: MooTool   Source File: HttpRequestForm.java    License: MIT License 6 votes vote down vote up
/**
 * 初始化CookieTable
 */
public static void initCookieTable() {
    JTable paramTable = getInstance().getCookieTable();
    paramTable.setRowHeight(36);
    String[] headerNames = {"Name", "Value", "Domain", "Path", "Expiry", ""};
    DefaultTableModel model = new DefaultTableModel(null, headerNames);
    paramTable.setModel(model);
    paramTable.updateUI();
    DefaultTableCellRenderer hr = (DefaultTableCellRenderer) paramTable.getTableHeader().getDefaultRenderer();
    // 表头列名居左
    hr.setHorizontalAlignment(DefaultTableCellRenderer.LEFT);

    TableColumnModel tableColumnModel = paramTable.getColumnModel();
    tableColumnModel.getColumn(headerNames.length - 1).
            setCellRenderer(new TableInCellButtonColumn(paramTable, headerNames.length - 1));
    tableColumnModel.getColumn(headerNames.length - 1).
            setCellEditor(new TableInCellButtonColumn(paramTable, headerNames.length - 1));

    // 设置列宽
    tableColumnModel.getColumn(headerNames.length - 1).setPreferredWidth(46);
    tableColumnModel.getColumn(headerNames.length - 1).setMaxWidth(46);
}
 
Example 5
private void saveModule() {
    if (moduleCombo.getSelectedIndex() != -1) {
        String moduleName = moduleCombo.getSelectedItem().toString();
        TestMgModule module = testMgmtModule.getModule(moduleName);
        Properties properties;
        properties = encryptpassword(PropUtils.getPropertiesFromTable(moduleTable));
        PropUtils.loadPropertiesInTable(properties, moduleTable, "");
        if (moduleTable.isEditing()) {
            moduleTable.getCellEditor().stopCellEditing();
        }
        module.getOptions().clear();
        DefaultTableModel model = (DefaultTableModel) moduleTable.getModel();
        for (int i = 0; i < model.getRowCount(); i++) {
            String prop = Objects.toString(model.getValueAt(i, 0), "").trim();
            if (!prop.isEmpty()) {
                String value = Objects.toString(model.getValueAt(i, 1), "");
                module.getOptions().add(new Option(prop, value));
            }
        }
    }
}
 
Example 6
/**
 * Constructs a LibraryPanel.
 *
 * @param libraries
 *          a list of libraries (represented by Library objects).
 */
public LibraryPanel( final List libraries ) {

  setLayout( new BorderLayout() );

  final ResourceBundle resources = ResourceBundle.getBundle( SwingPreviewModule.BUNDLE_NAME );

  final String[] names =
      new String[] { resources.getString( "libraries-table.column.name" ),
        resources.getString( "libraries-table.column.version" ),
        resources.getString( "libraries-table.column.licence" ), resources.getString( "libraries-table.column.info" ) };
  final DefaultTableModel model = new DefaultTableModel( names, libraries.size() );
  for ( int i = 0; i < libraries.size(); i++ ) {
    final DependencyInformation depInfo = (DependencyInformation) libraries.get( i );
    model.setValueAt( depInfo.getName(), i, 0 );
    model.setValueAt( depInfo.getVersion(), i, 1 );
    model.setValueAt( depInfo.getLicenseName(), i, 2 );
    model.setValueAt( depInfo.getInfo(), i, 3 );
  }

  this.table = new JTable( model );
  add( new JScrollPane( this.table ) );

}
 
Example 7
Source Project: openAGV   Source File: FilterTableModel.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Filters the transport orders.
 */
private void filter() {
  int rowCount = getModel().getRowCount();
  int[] help = new int[rowCount];
  int counter = 0;

  for (int i = 0; i < rowCount; i++) {
    Object value = getModel().getValueAt(i, fColumnIndexToFilter);

    if (!isFilterSet(value)) {
      help[counter] = i;
      counter++;
    }
  }

  fIndices = new int[counter];
  System.arraycopy(help, 0, fIndices, 0, counter);

  ((DefaultTableModel) getModel()).fireTableDataChanged();
}
 
Example 8
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
private MainPanel() {
  super(new BorderLayout());
  URL[] icons = {getIconUrl("wi0062-16.png"), getIconUrl("wi0063-16.png"), getIconUrl("wi0064-16.png")};
  String[] columnNames = {"Column1", "Column2", "Column3"};
  JTable table = new JTable(new DefaultTableModel(columnNames, 8));
  TableColumnModel m = table.getColumnModel();
  for (int i = 0; i < m.getColumnCount(); i++) {
    // m.getColumn(i).setHeaderRenderer(new IconColumnHeaderRenderer());
    // m.getColumn(i).setHeaderRenderer(new HtmlIconHeaderRenderer());
    // m.getColumn(i).setHeaderValue(String.format("<html><table><td><img src='%s'/></td>%s", icons[i], columnNames[i]));
    String hv = String.format("<html><table cellpadding='0' cellspacing='0'><td><img src='%s'/></td>&nbsp;%s", icons[i], columnNames[i]);
    m.getColumn(i).setHeaderValue(hv);
  }
  table.setAutoCreateRowSorter(true);
  add(new JScrollPane(table));

  JMenuBar mb = new JMenuBar();
  mb.add(LookAndFeelUtil.createLookAndFeelMenu());
  SwingUtilities.invokeLater(() -> getRootPane().setJMenuBar(mb));

  setPreferredSize(new Dimension(320, 240));
}
 
Example 9
@Test
public void testRowWithPrePostPad() throws Exception {
  final MasterReport report = new MasterReport();
  report.setDataFactory( new TableDataFactory( "query", new DefaultTableModel( 10, 1 ) ) );
  report.setQuery( "query" );

  final Band table = TableTestUtil.createTable( 1, 1, 6, true );
  table.getStyle().setStyleProperty( ElementStyleKeys.MIN_WIDTH, 200f );
  table.setName( "table" );
  report.getReportHeader().addElement( TableTestUtil.createDataItem( "Pre-Padding", 100, 10 ) );
  report.getReportHeader().addElement( table );
  report.getReportHeader().addElement( TableTestUtil.createDataItem( "Post-Padding", 100, 10 ) );
  report.getReportHeader().setLayout( "row" );

  PdfReportUtil.createPDF( report, "test-output/PRD-3857-output-row.pdf" );
  List<LogicalPageBox> pages = DebugReportRunner.layoutPages( report, 0, 1, 2 );

  assertPageValid( pages, 0 );
  assertPageValid( pages, 1 );
  assertPageValid( pages, 2 );
  // assertPageValid(report, 3);
  // assertPageValid(report, 4);
}
 
Example 10
Source Project: dsworkbench   Source File: VillageSupportFrame.java    License: Apache License 2.0 6 votes vote down vote up
private boolean deleteSelection(boolean pAsk) {
    List<Attack> selectedSupports = getSelectedSupports();
    if (pAsk) {
        String message = ((selectedSupports.size() == 1) ? "Unterstützung " : (selectedSupports.size() + " Unterstützungen ")) + "wirklich löschen?";
        if (selectedSupports.isEmpty() || JOptionPaneHelper.showQuestionConfirmBox(jResultFrame, message, "Angriffe löschen", "Nein", "Ja") != JOptionPane.YES_OPTION) {
            return false;
        }
    }
    DefaultTableModel model = (DefaultTableModel) jSupportTable.getModel();
    int numRows = jSupportTable.getSelectedRows().length;
    for (int i = 0; i < numRows; i++) {
        model.removeRow(jSupportTable.convertRowIndexToModel(jSupportTable.getSelectedRow()));
    }
    showSuccess(((numRows == 1) ? "Unterstützung " : " Unterstützungen ") + " gelöscht");
    return true;
}
 
Example 11
Source Project: WePush   Source File: PushHisForm.java    License: MIT License 6 votes vote down vote up
private static void initHisLeftTable() {
    // 导入历史管理
    String[] headerNames = {"消息名称", "状态", "时间", "id"};
    DefaultTableModel model = new DefaultTableModel(null, headerNames);
    pushHisForm.getPushHisLeftTable().setModel(model);

    DefaultTableCellRenderer hr = (DefaultTableCellRenderer) pushHisForm.getPushHisLeftTable().getTableHeader()
            .getDefaultRenderer();
    // 表头列名居左
    hr.setHorizontalAlignment(DefaultTableCellRenderer.LEFT);

    List<TPushHistory> pushHistoryList = pushHistoryMapper.selectByMsgType(App.config.getMsgType());
    Object[] data;
    for (TPushHistory tPushHistory : pushHistoryList) {
        data = new Object[4];
        data[0] = tPushHistory.getMsgName();
        data[1] = tPushHistory.getResult();
        data[2] = tPushHistory.getCreateTime();
        data[3] = tPushHistory.getId();
        model.addRow(data);
    }

    // 隐藏id列
    JTableUtil.hideColumn(pushHisForm.getPushHisLeftTable(), 3);
}
 
Example 12
Source Project: visualvm   Source File: JavaObjectsSummary.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected JComponent createComponent() {
    TableModel model = new DefaultTableModel(PREVIEW_ITEMS, 1) {
        { setValueAt(Bundle.JavaObjectsSummary_ComputingProgress(), 0, 0); }
        public boolean isCellEditable(int row, int column) { return false; }
    };

    ProfilerRenderer renderer = new LabelRenderer() {
        public void setValue(Object o, int i) {
            super.setValue(o, i);
            setIcon(o == null || o.toString().isEmpty() ? null : Icons.getIcon(HeapWalkerIcons.PROGRESS));
        }
    };

    ProfilerTable t = createTable(model);
    t.setDefaultRenderer(Object.class, renderer);
    
    return t;
}
 
Example 13
Source Project: WePush   Source File: HttpMsgForm.java    License: MIT License 6 votes vote down vote up
/**
 * 初始化ParamTable
 */
public static void initParamTable() {
    JTable paramTable = getInstance().getParamTable();
    paramTable.setRowHeight(36);
    String[] headerNames = {"Name", "Value", ""};
    DefaultTableModel model = new DefaultTableModel(null, headerNames);
    paramTable.setModel(model);
    paramTable.updateUI();
    DefaultTableCellRenderer hr = (DefaultTableCellRenderer) paramTable.getTableHeader().getDefaultRenderer();
    // 表头列名居左
    hr.setHorizontalAlignment(DefaultTableCellRenderer.LEFT);

    TableColumnModel tableColumnModel = paramTable.getColumnModel();
    tableColumnModel.getColumn(headerNames.length - 1).
            setCellRenderer(new TableInCellButtonColumn(paramTable, headerNames.length - 1));
    tableColumnModel.getColumn(headerNames.length - 1).
            setCellEditor(new TableInCellButtonColumn(paramTable, headerNames.length - 1));

    // 设置列宽
    tableColumnModel.getColumn(headerNames.length - 1).setPreferredWidth(46);
    tableColumnModel.getColumn(headerNames.length - 1).setMaxWidth(46);
}
 
Example 14
Source Project: java-swing-tips   Source File: HeaderCheckBoxHandler.java    License: MIT License 6 votes vote down vote up
private boolean fireUpdateEvent(DefaultTableModel m, TableColumn column, Object status) {
  if (status == Status.INDETERMINATE) {
    List<?> data =  m.getDataVector();
    List<Boolean> l = data.stream()
        .map(v -> (Boolean) ((List<?>) v).get(targetColumnIndex))
        .distinct()
        .collect(Collectors.toList());
    boolean notDuplicates = l.size() == 1;
    if (notDuplicates) {
      boolean isSelected = l.get(0);
      column.setHeaderValue(isSelected ? Status.SELECTED : Status.DESELECTED);
      return true;
    } else {
      return false;
    }
  } else {
    column.setHeaderValue(Status.INDETERMINATE);
    return true;
  }
}
 
Example 15
Source Project: triplea   Source File: AccessLogTabActions.java    License: GNU General Public License v3.0 6 votes vote down vote up
BiConsumer<Integer, DefaultTableModel> banUser() {
  return (rowNumber, tableModel) ->
      ActionDurationDialog.builder()
          .parent(parentFrame)
          .actionName(ActionName.BAN)
          .build()
          .prompt()
          .map(
              duration ->
                  BanData.builder()
                      .actionDuration(duration)
                      .username(String.valueOf(tableModel.getValueAt(rowNumber, 1)))
                      .ip(String.valueOf(tableModel.getValueAt(rowNumber, 2)))
                      .hashedMac(String.valueOf(tableModel.getValueAt(rowNumber, 3)))
                      .build())
          .ifPresent(this::confirmAndExecuteBan);
}
 
Example 16
public DesignerExpressionRuntime( final DataRow dataRow,
                                  final DataSchema dataSchema,
                                  final MasterReport report ) {
  this.report = report;
  if ( report == null ) {
    throw new NullPointerException();
  }

  this.dataRow = dataRow;
  this.dataSchema = dataSchema;
  this.tableModel = new DefaultTableModel();
  try {
    this.processingContext = new DesignerProcessingContext( report );
  } catch ( ReportProcessingException e ) {
    this.processingContext = new DesignerProcessingContext();
  }
}
 
Example 17
Source Project: MVPManager   Source File: EditorMVPDialog.java    License: MIT License 6 votes vote down vote up
/**
 * create a JTable instance
 *
 * @return
 */
private JTable newTableInstance() {
    String[] defaultValue = {"void", "method()"};
    DefaultTableModel mDefaultTableMoadel = new DefaultTableModel();
    Object[][] object = new Object[1][2];
    object[0][0] = "void";
    object[0][1] = "method()";
    mDefaultTableMoadel.setDataVector(object, new Object[]{"return", "method"});
    JTable mJtable = new JTable(mDefaultTableMoadel) {
        @Override
        public void tableChanged(TableModelEvent e) {
            super.tableChanged(e);
            repaint();
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    return mJtable;
}
 
Example 18
Source Project: Repeat   Source File: SwingUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Show a list of fields and values of them for user to confirm
 * @param confirmTitle title for the displayed window
 * @param titles list of titles of the fields to display
 * @param values values of each field in the according order
 * @return the JOptionPane selection value according to user's action
 */
public static int confirmValues(String confirmTitle, String[] titles, String[] values) {
	if (titles.length == 0 || (titles.length != values.length)) {
		return -1;
	}

	JTable table = new JTable();
	table.setModel(new DefaultTableModel(
		new Object[][] {},
		new String[] {" ", " "}
	));
	SwingUtil.TableUtil.ensureRowNumber(table, titles.length);

	for (int i = 0; i < titles.length; i++) {
		table.setValueAt(titles[i], i, 0);
		table.setValueAt(values[i], i, 1);
	}
	JScrollPane mainPanel = new JScrollPane(table);

	return JOptionPane.showConfirmDialog(null, mainPanel,
			confirmTitle, JOptionPane.YES_NO_OPTION);
}
 
Example 19
Source Project: netbeans   Source File: J2SEProjectProperties.java    License: Apache License 2.0 6 votes vote down vote up
private void storeRoots( SourceRoots roots, DefaultTableModel tableModel ) throws MalformedURLException {
    Vector data = tableModel.getDataVector();
    URL[] rootURLs = new URL[data.size()];
    String []rootLabels = new String[data.size()];
    final LinkedList<URL> oldRootURLs = new LinkedList<URL>(Arrays.asList (roots.getRootURLs (false)));
    final LinkedList<String> oldRootLabels = new LinkedList<String>(Arrays.asList(roots.getRootNames()));
    final LinkedList<String> oldRootProps = new LinkedList<String>(Arrays.asList (roots.getRootProperties()));
    boolean rootsAreSame = true;
    for (int i=0; i<data.size();i++) {
        File f = (File) ((Vector)data.elementAt(i)).elementAt(0);
        rootURLs[i] = Utilities.toURI(f).toURL();
        if (!rootURLs[i].toExternalForm().endsWith("/")) {  //NOI18N
            rootURLs[i] = new URL(rootURLs[i]+"/");
        }
        validateURL(rootURLs[i],f);
        rootLabels[i] = (String) ((Vector)data.elementAt(i)).elementAt(1);
        rootsAreSame &= !oldRootURLs.isEmpty() &&
                        oldRootURLs.removeFirst().equals(rootURLs[i]) &&
                        roots.getRootDisplayName(oldRootLabels.removeFirst(), oldRootProps.removeFirst()).equals(rootLabels[i]);
    }
    if (!rootsAreSame || !oldRootURLs.isEmpty ()) {
        roots.putRoots(rootURLs,rootLabels);
    }
}
 
Example 20
Source Project: jdk8u60   Source File: OldJTable.java    License: GNU General Public License v2.0 6 votes vote down vote up
public TableColumn addColumn(Object columnIdentifier, int width,
                             TableCellRenderer renderer,
                             TableCellEditor editor, List columnData) {
    checkDefaultTableModel();

    // Set up the model side first
    DefaultTableModel m = (DefaultTableModel)getModel();
    m.addColumn(columnIdentifier, columnData.toArray());

    // The column will have been added to the end, so the index of the
    // column in the model is the last element.
    TableColumn newColumn = new TableColumn(
            m.getColumnCount()-1, width, renderer, editor);
    super.addColumn(newColumn);
    return newColumn;
}
 
Example 21
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
private void cleanup(JComponent c, boolean remove) {
  c.getRootPane().getGlassPane().setVisible(false);
  // c.setCursor(Cursor.getDefaultCursor());
  if (remove && Objects.nonNull(indices)) {
    DefaultTableModel model = (DefaultTableModel) ((JTable) c).getModel();
    if (addCount > 0) {
      for (int i = 0; i < indices.length; i++) {
        if (indices[i] >= addIndex) {
          indices[i] += addCount;
        }
      }
    }
    for (int i = indices.length - 1; i >= 0; i--) {
      model.removeRow(indices[i]);
    }
  }
  indices = null;
  addCount = 0;
  addIndex = -1;
}
 
Example 22
/**
 * Creates data of sales per months.
 *
 * @return The tabular report data.
 */
private TableModel createData()
{
  try
  {
    final MasterReport report = createReport();
    return report.getDataFactory().queryData(report.getQuery(), report.getParameterValues());
  }
  catch (Exception e)
  {
    // ignore generate a new dataset
    final String[] columnNames = {"January", "February", "March", "April", "May", "June", "July", "August",
        "September", "October", "November", "December"};
    return new DefaultTableModel(columnNames, 0);
  }
}
 
Example 23
Source Project: netbeans   Source File: RunContainerPropertiesVisual.java    License: Apache License 2.0 6 votes vote down vote up
public Map<String, String> getVolumesTable() {
    Map<String, String> result = new TreeMap<>();
    DefaultTableModel model = (DefaultTableModel) volumesTable.getModel();
    if (volumesTable.isEditing()) {
        volumesTable.getCellEditor().stopCellEditing();
    }
    for (Object o : model.getDataVector()) {
        Vector v = (Vector) o;
        String target = (String) v.elementAt(0);
        String source = (String) v.elementAt(1);
        if (target != null && source != null) {
            result.put(target, source);
        }
    }
    return result;
}
 
Example 24
/**
 * Replaces all the content of the table by a content private as list of
 * String[].
 * 
 * @param data
 */
public void update(ArrayList<String[]> data) {
	DefaultTableModel model = (DefaultTableModel) getModel();
	model.getDataVector().removeAllElements();
	for (String[] row : data)
		model.addRow(row);
	repaint();
}
 
Example 25
private TableModel createColorTableModel() {
  final String[] names = new String[] { "Number", "Group", "Color" };
  final Object[][] data =
      new Object[][] { { new Integer( 1 ), "X", "Red" }, { new Integer( 2 ), "X", "Green" },
        { new Integer( 3 ), "Y", "Yellow" }, { new Integer( 3 ), "Y", "Yellow" }, { new Integer( 4 ), "Y", "Blue" },
        { new Integer( 4 ), "Y", "Blue" }, { new Integer( 5 ), "Z", "Orange" }, { new Integer( 5 ), "Z", "Orange" },
        { new Integer( 5 ), "Z", "Orange" }, { new Integer( 6 ), "Z", "White" }, { new Integer( 6 ), "Z", "White" },
        { new Integer( 6 ), "Z", "White" }, };
  return new DefaultTableModel( data, names );
}
 
Example 26
@Test
public void testRunSorting() {
  List<SortConstraint> sc = new ArrayList<SortConstraint>();
  sc.add( new SortConstraint( "A", true ) );
  sc.add( new SortConstraint( "B", true ) );

  MasterReport report = new MasterReport();
  report.setQuery( "default" );
  report.setDataFactory( new ValidateDataFactory( "default", new DefaultTableModel( 10, 10 ), sc ) );
  report.setAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.AUTOSORT, true );
  RelationalGroup rootGroup = (RelationalGroup) report.getRootGroup();
  rootGroup.setFields( Arrays.asList( "A", "B" ) );

  int i = DebugReportRunner.execGraphics2D( report );
}
 
Example 27
Source Project: yeti   Source File: YileController.java    License: MIT License 5 votes vote down vote up
public YileController(WorkflowController parent, YileModel dataModel) {
    setName("yileScan");

    setWorkflowController(parent);

    DisplayResultIFace displayResults = new YileDisplayResults();
    displayResults.setModel((DefaultTableModel) dataModel);
    setDisplayResults(displayResults);

    workers = new ArrayList<>();
}
 
Example 28
public XMBeanAttributes(MBeansTab mbeansTab) {
    super();
    this.mbeansTab = mbeansTab;
    ((DefaultTableModel)getModel()).setColumnIdentifiers(columnNames);
    attributesListener = new AttributesListener(this);
    getModel().addTableModelListener(attributesListener);
    getColumnModel().getColumn(NAME_COLUMN).setPreferredWidth(40);

    addMouseListener(mouseListener);
    getTableHeader().setReorderingAllowed(false);
    setColumnEditors();
    addKeyListener(new Utils.CopyKeyAdapter());
}
 
Example 29
Source Project: WePush   Source File: TxYunMsgForm.java    License: MIT License 5 votes vote down vote up
public TxYunMsgForm() {
    // 模板数据-添加 按钮事件
    templateMsgDataAddButton.addActionListener(e -> {
        String[] data = new String[2];
        data[0] = getInstance().getTemplateDataNameTextField().getText();
        data[1] = getInstance().getTemplateDataValueTextField().getText();

        if (getInstance().getTemplateMsgDataTable().getModel().getRowCount() == 0) {
            initTemplateDataTable();
        }

        DefaultTableModel tableModel = (DefaultTableModel) getInstance().getTemplateMsgDataTable()
                .getModel();
        int rowCount = tableModel.getRowCount();

        Set<String> keySet = new HashSet<>();
        String keyData;
        for (int i = 0; i < rowCount; i++) {
            keyData = (String) tableModel.getValueAt(i, 0);
            keySet.add(keyData);
        }

        if (StringUtils.isEmpty(data[0]) || StringUtils.isEmpty(data[1])) {
            JOptionPane.showMessageDialog(MessageEditForm.getInstance().getMsgEditorPanel(), "模板参数和参数对应的值不能为空!", "提示",
                    JOptionPane.INFORMATION_MESSAGE);
        } else if (keySet.contains(data[0])) {
            JOptionPane.showMessageDialog(MessageEditForm.getInstance().getMsgEditorPanel(), "模板参数不能重复!", "提示",
                    JOptionPane.INFORMATION_MESSAGE);
        } else {
            tableModel.addRow(data);
        }
    });
}
 
Example 30
Source Project: visualvm   Source File: JavaObjectsSummary.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void configureSnippet(final ResultsSnippet snippet, final Object[][] data) {
    final TableModel model = new DefaultTableModel(data, new Object[] {
                                        Bundle.JavaObjectsSummary_NameColumn(),
                                        Bundle.JavaObjectsSummary_ValueColumn() }) {
        public boolean isCellEditable(int row, int column) { return false; }
    };
    
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            snippet.setRealModel(model);
        }
    });
}