Example usage for javax.swing.table DefaultTableModel setColumnIdentifiers

List of usage examples for javax.swing.table DefaultTableModel setColumnIdentifiers

Introduction

In this page you can find the example usage for javax.swing.table DefaultTableModel setColumnIdentifiers.

Prototype

public void setColumnIdentifiers(Object[] newIdentifiers) 

Source Link

Document

Replaces the column identifiers in the model.

Usage

From source file:Main.java

public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultTableModel model = new DefaultTableModel();
    model.setColumnIdentifiers(new Object[] { "Column 1", "Column 2", "Column 3" });

    JTable table = new JTable(model);
    for (int count = 0; count < 3; count++) {
        model.insertRow(count, new Object[] { count, "name", "age" });
    }//from  w w  w. j a  va  2s  .  c  om
    table.setRowHeight(1, 30);

    frame.add(new JScrollPane(table));
    frame.setLocationByPlatform(true);
    frame.pack();
    frame.setVisible(true);
}

From source file:Main.java

private static JPanel createPanel() {
    JPanel panel = new JPanel();
    DefaultTableModel model = new DefaultTableModel() {
        @Override// w  ww  . j  a  v a 2s . com
        public Class<?> getColumnClass(int col) {
            if (col == 0) {
                return Icon.class;
            } else {
                return Double.class;
            }
        }
    };
    model.setColumnIdentifiers(new Object[] { "Book", "Cost" });
    for (int i = 0; i < 42; i++) {
        model.addRow(new Object[] { ICON, Double.valueOf(i) });
    }
    JTable table = new JTable(model);
    table.setDefaultRenderer(Double.class, new DefaultTableCellRenderer() {
        @Override
        protected void setValue(Object value) {
            NumberFormat format = NumberFormat.getCurrencyInstance();
            setText((value == null) ? "" : format.format(value));
        }
    });
    table.setRowHeight(ICON.getIconHeight());
    panel.add(new JScrollPane(table) {
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(320, 240);
        }
    });
    return panel;
}

From source file:com.dvd.ui.UpdateBooking.java

private void populateTable() {

    getData();/*from  w  w w . j a v a  2  s . c  om*/

    DefaultTableModel model = new DefaultTableModel();
    model.setColumnIdentifiers(new String[] { "Booking ID", "User ID", "DVD Copy Number", "Added Date " });
    bookingTable.setModel(new DefaultTableModel());

    for (Booking booking_item : bookingList) {
        model.addRow(new String[] { String.valueOf(booking_item.getId()),
                String.valueOf(booking_item.getUserID()), String.valueOf(booking_item.getCopyNumber()),
                String.valueOf(booking_item.getBookingAddedDate()) });

    }
    bookingTable.setModel(model);
}

From source file:GeMSE.GS.Analysis.Stats.OneSampleCovariancePanel.java

private void GridView(double[][] matrix) {
    DefaultTableModel spaceTabMod = new DefaultTableModel() {
        @Override//from  w ww. j  a va  2 s .co  m
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };

    String[] columnTitle = new String[matrix[0].length + 1];
    columnTitle[0] = "";
    for (int col = 1; col < columnTitle.length; col++)
        columnTitle[col] = "Column " + String.valueOf(col);
    spaceTabMod.setColumnIdentifiers(columnTitle);

    int col = 0;
    for (int r = 0; r < matrix.length; r++) {
        String[] row = new String[matrix[0].length + 1];
        row[0] = "Row " + Integer.toString(r);

        for (col = 0; col < matrix[0].length; col++)
            row[col + 1] = Double.toString(matrix[r][col]);

        spaceTabMod.addRow(row);
    }

    matrixDG.setModel(spaceTabMod);
    matrixDG.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    matrixDG.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    ResizeColumnWidth(matrixDG);
}

From source file:aasdntool.AASDNTool.java

private void devicesActionPerformed(java.awt.event.ActionEvent evt) {
    StringBuffer response = new StringBuffer();

    try {/*  w w w. ja va2  s  .c  o  m*/
        URL obj = new URL("http://" + controllerIP + ":8080/wm/device/");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        con.setRequestMethod("GET");

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + "http://" + controllerIP + ":8080/wm/device/");
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        ObjectMapper mapper = new ObjectMapper();

        List<Device> devList = mapper.readValue(response.toString(),
                mapper.getTypeFactory().constructCollectionType(List.class, Device.class));

        DefaultTableModel dtm = new DefaultTableModel(0, 0);

        // add header of the table
        String header[] = new String[] { "MAC Address" };

        // add header in table model
        dtm.setColumnIdentifiers(header);
        macTable.setModel(dtm);

        for (Device dev : devList) {
            dtm.addRow(new Object[] { dev.getMac() });
        }

    } catch (Exception e) {
        System.out.println("Exception occured:" + e);
    }
}

From source file:aasdntool.AASDNTool.java

private void openFlowSwitchesActionPerformed(java.awt.event.ActionEvent evt) {

    StringBuffer response = new StringBuffer();

    try {/*from  w w w  . ja  va  2  s  .c  o  m*/
        URL obj = new URL("http://" + controllerIP + ":8080/wm/core/controller/switches/json");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        con.setRequestMethod("GET");

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + "http://" + controllerIP
                + ":8080/wm/core/controller/switches/json");
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        ObjectMapper mapper = new ObjectMapper();
        List<Switches> switchList = mapper.readValue(response.toString(),
                mapper.getTypeFactory().constructCollectionType(List.class, Switches.class));

        DefaultTableModel dtm = new DefaultTableModel(0, 0);

        // add header of the table
        String header[] = new String[] { "Switch DPID", "IP Address" };

        // add header in table model
        dtm.setColumnIdentifiers(header);
        switchTable.setModel(dtm);

        // add row dynamically into the table
        for (Switches sw : switchList) {
            dtm.addRow(new Object[] { sw.getDpid(), sw.getInetAddress() });
        }

    } catch (Exception e) {
        System.out.println("Exception Occured:" + e);
    }
}

From source file:pl.piotrsukiennik.jbrain.gui.ModelPanel.java

protected TableModel convert2Model(ConnectionsDTO connectionsDTO) {
    String[] layers = connectionsDTO.getLayers();
    double[][] connections = connectionsDTO.getConnections();
    DefaultTableModel tableModel = new DefaultTableModel(layers.length, layers.length + 1);
    for (int i = 0; i < layers.length; i++) {
        tableModel.setValueAt(layers[i], i, 0);
    }//from w  w w .  j  a va  2  s. c om
    for (int i = 0; i < connections.length; i++) {
        for (int j = 0; j < connections.length; j++) {
            double connection = connections[i][j];
            if (connection != 0) {
                tableModel.setValueAt(connections[i][j], i, j + 1);
            }
        }
    }
    List<String> labels = new ArrayList<String>();
    labels.add("");
    labels.addAll(Arrays.asList(connectionsDTO.getLayers()));
    tableModel.setColumnIdentifiers(labels.toArray());
    return tableModel;
}

From source file:com.dvd.ui.SearchDVD.java

private void getDvdBtnActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_getDvdBtnActionPerformed
    String dvdCodeStr = dvdCodeTxt.getText();
    errorLabelReserve.setVisible(false);
    copyTable.setVisible(false);//from  w  w w  .  j  a v  a  2  s.  com
    copyTable.setModel(new DefaultTableModel());
    boolean isMatched = false;

    DefaultTableModel model = new DefaultTableModel();
    model.setColumnIdentifiers(new String[] { "Copy Number", "ISLE Number", "Shelf Number", "is Available " });

    if (dvdCodeStr != null && !dvdCodeStr.isEmpty()) {
        int dvdCodeInt = 0;
        try {
            dvdCodeInt = Integer.parseInt(dvdCodeStr);
            // Get DVD Service

            for (Dvd dvd : searchDVDList) {
                if (dvd.getCode() == dvdCodeInt) {
                    isMatched = true;
                    jLabelDVDCode.setText(String.valueOf(dvd.getCode()));
                    jLabelDVDCode1.setText(String.valueOf(dvd.getCode()));
                    jLabelDVDTitle.setText(dvd.getTitle());
                    jLabelDVDTitle1.setText(dvd.getTitle());
                    jLabelYear.setText(String.valueOf(dvd.getYear()));
                    jLabelImdb.setText(String.valueOf(dvd.getRating()));
                    jLabelActors.setText(dvd.getActors());
                    jLabelFormat.setText(dvd.getDefiniiton());

                    // Get Copies from DVD code - Service
                    DVDRepository dVDRepository = new DVDRepository();
                    try {
                        if (isServiceOn) {
                            searchCopyDVDList = new ArrayList<DvdCopy>();
                            searchCopyDVDList = dVDRepository.getCopyDVDList(dvdCodeInt);
                        } else {
                            com.dvd.hibernate.repo.DVDRepository repository = new com.dvd.hibernate.repo.DVDRepository();
                            searchCopyDVDList = new ArrayList<DvdCopy>();
                            List<DVDCopyDao> s = repository.getCopyDVDList(dvdCodeInt);
                            if (s != null) {
                                for (DVDCopyDao dvdCopyDao : s) {
                                    searchCopyDVDList.add(new DvdCopy(dvdCopyDao.getIsleNumber(),
                                            String.valueOf(dvdCopyDao.getCopyNumber()),
                                            dvdCopyDao.getShelfNumber(), dvd, dvdCopyDao.isAvailable()));
                                }
                            }

                        }
                    } catch (Exception ex) {
                        Logger.getLogger(SearchDVD.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    for (DvdCopy copy : searchCopyDVDList) {

                        model.addRow(new String[] { copy.getCopyNumber(), copy.getIsleNumber(),
                                copy.getShelfNumber(), String.valueOf(copy.isIsAvailable()) });

                    }
                    jLabelCopies.setText(String.valueOf(searchCopyDVDList.size()));
                    copyTable.setVisible(true);
                    copyTable.setModel(model);

                }
            }
            if (!isMatched) {
                errorLabelReserve.setVisible(true);
                errorLabelReserve.setText("No DVD match");
            }

        } catch (Exception e) {
            errorLabelReserve.setText("");
            errorLabelReserve.setVisible(true);
            errorLabelReserve.setText("Please enter a valid DVD Code");
            resetData();

        }

    } else {
        resetData();
        errorLabelReserve.setVisible(true);
        errorLabelReserve.setText("Please enter a valid DVD Code");
    }
}

From source file:com.dvd.ui.SearchDVD.java

private void searchActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_searchActionPerformed
    errorTag.setVisible(false);/*from   w ww  .j av a2  s. c o m*/
    searchTable.setModel(new DefaultTableModel());
    String searchTerm = keyword.getText().toLowerCase();
    String ratingTerm = rating.getSelectedItem().toString();
    String yearTerm = year.getSelectedItem().toString();
    String definitionTerm = definition.getSelectedItem().toString();

    boolean isResultFound = false;

    DefaultTableModel model = new DefaultTableModel();
    model.setColumnIdentifiers(
            new String[] { "Code", "Title", "Year", "Rating ", "Definition", "Actors", "Book" });

    if (searchTerm != null && !searchTerm.isEmpty()) {

        for (Dvd dvd_item : searchDVDList) {
            if (dvd_item.getTitle().toLowerCase().contains(searchTerm)) {

                model.addRow(new String[] { String.valueOf(dvd_item.getCode()), dvd_item.getTitle(),
                        String.valueOf(dvd_item.getYear()), String.valueOf(dvd_item.getRating()),
                        dvd_item.getDefiniiton(), dvd_item.getActors() });

            }
        }
        isResultFound = true;

        if (isResultFound) {
            searchTable.setVisible(true);
            searchTable.setModel(model);
        } else {
            errorTag.setVisible(true);
            searchTable.setModel(new DefaultTableModel());
            // errorTag.setText("No Result Found");
        }
    } else {

        if (!ratingTerm.equals("Any")) {
            for (Dvd dvd_item : searchDVDList) {
                if (dvd_item.getRating() == Integer.parseInt(ratingTerm)) {

                    model.addRow(new String[] { String.valueOf(dvd_item.getCode()), dvd_item.getTitle(),
                            String.valueOf(dvd_item.getYear()), String.valueOf(dvd_item.getRating()),
                            dvd_item.getDefiniiton(), dvd_item.getActors() });

                }
            }
            isResultFound = true;

            if (isResultFound) {
                searchTable.setVisible(true);
                searchTable.setModel(model);
            } else {
                errorTag.setVisible(true);
                searchTable.setModel(new DefaultTableModel());
                errorTag.setText("No Result Found");
            }

        } else if (!yearTerm.equals("Any")) {

            for (Dvd dvd_item : searchDVDList) {
                if (dvd_item.getYear().equals(yearTerm)) {

                    model.addRow(new String[] { String.valueOf(dvd_item.getCode()), dvd_item.getTitle(),
                            String.valueOf(dvd_item.getYear()), String.valueOf(dvd_item.getRating()),
                            dvd_item.getDefiniiton(), dvd_item.getActors() });

                }
            }
            isResultFound = true;

            if (isResultFound) {
                searchTable.setVisible(true);
                searchTable.setModel(model);
            } else {
                errorTag.setVisible(true);
                searchTable.setModel(new DefaultTableModel());
                errorTag.setText("No Result Found");
            }

        } else if (!definitionTerm.equals("Any")) {

            for (Dvd dvd_item : searchDVDList) {
                if (dvd_item.getDefiniiton().equals(definitionTerm)) {

                    model.addRow(new String[] { String.valueOf(dvd_item.getCode()), dvd_item.getTitle(),
                            String.valueOf(dvd_item.getYear()), String.valueOf(dvd_item.getRating()),
                            dvd_item.getDefiniiton(), dvd_item.getActors() });

                }
            }
            isResultFound = true;

            if (isResultFound) {
                searchTable.setVisible(true);
                searchTable.setModel(model);
            } else {
                errorTag.setVisible(true);
                searchTable.setModel(new DefaultTableModel());
                errorTag.setText("No Result Found");
            }

        } else {
            errorTag.setText("Please enter more specific search criteria");
            errorTag.setVisible(true);
        }

        // errorTag.setText("No Result Found");
    }

}

From source file:captureplugin.CapturePlugin.java

/**
 * Check the programs after data update.
 *//*ww w  .  ja v 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);
                }
            });
        }
    }
}