Sebastian Zeki Sebastian Zeki - 1 year ago 47
Java Question

Is it possible jtable row in optionDialog box

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 show a row from a JTable in a pop-up eg showDialog type box (ie where the selected row is organised as a column).

Even a link to a tutorial would do.

I have scoured the internet but I don't think I'm really using the correct keywords as I get a lot of right-click options.

If this is not possible are there any other suggestions for how to do this?


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() {
    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) {
                public Dimension getPreferredScrollableViewportSize() {
                    return new Dimension(140, 240);
            // Apply any custom renderers and editors
            JOptionPane.showMessageDialog(f, new JScrollPane(newTable),
                rowName, JOptionPane.PLAIN_MESSAGE);