Is it possible jtable row in optionDialog box

后端 未结 3 592
甜味超标
甜味超标 2020-12-22 01:59

I have a jtable.

Some of the cells contain very long strings and trying to scroll left and right through it is difficult. My question is whether it is possible to s

3条回答
  •  情深已故
    2020-12-22 02:33

    As shown here, the JOptionPane factory methods will display the Object passed in the message parameter. If that message is a one column JTable, you can recycle any custom renderers and editors that were applied to the original table.

    In outline,

    • Add a ListSelectionListener to your table and get the selectedRow.

    • Iterate through the table's model and construct a newModel whose rows are the columns of the selectedRow.

    • Create a JTable newTable = new JTable(newModel).

    • Apply any non-default renderers and editors.

    • Pass a new JScrollPane(newTable) as the message parameter to your chosen JOptionPane method.

    Starting from this example, the following listener displays the dialog pictured.

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            int selectedRow = table.convertRowIndexToModel(table.getSelectedRow());
            if (selectedRow > -1) {
                DefaultTableModel newModel = new DefaultTableModel();
                String rowName = "Row: " + selectedRow;
                newModel.setColumnIdentifiers(new Object[]{rowName});
                for (int i = 0; i < model.getColumnCount(); i++) {
                    newModel.addRow(new Object[]{model.getValueAt(selectedRow, i)});
                }
                JTable newTable = new JTable(newModel) {
                    @Override
                    public Dimension getPreferredScrollableViewportSize() {
                        return new Dimension(140, 240);
                    }
                };
                // Apply any custom renderers and editors
                JOptionPane.showMessageDialog(f, new JScrollPane(newTable),
                    rowName, JOptionPane.PLAIN_MESSAGE);
            }
        }
    });
    

提交回复
热议问题