ullQuiorra
ullQuiorra

Reputation: 31

JTable in JDialog

I have problem with JTable using in JDialog. I want to show my table in dialog with this code:

 public class ShortcutKeys extends JDialog {
  public ShortcutKeys( JFrame parent ) {
    super( parent );
    this.setTitle( "Shortcut Keys of..." );
    this.setLocationRelativeTo( null );
    this.setModal( true );
    this.setResizable( false );
    this.setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE );
    this.getContentPane().setLayout( new BorderLayout() );

    JTable shortcutKeysTable = getShortcutKeysTable();
    this.add( shortcutKeysTable, BorderLayout.CENTER );

    this.pack();
  }

  private JTable getShortcutKeysTable() {
    JTable shortcutKeysTable;

    Object rowData[][] = { { "1", "11" }, { "2", "22"} };
    Object columnNames[] = { "Column One", "Column Two" };

    shortcutKeysTable = new JTable(rowData, columnNames);
    JScrollPane scrollPane = new JScrollPane(shortcutKeysTable);

    this.add(scrollPane, BorderLayout.CENTER);
    this.setSize(300, 150);

    return shortcutKeysTable;
  }

}

So, problem is such that with exactly this code, doesn't show column names - only row data without my size, result is in small table not with my preference. BUT when in method or in constructor I add this line:

this.setVisible( true );

Then this table shows row data and columns with my size 300x150 BUT when I click ok Exit 'X' then of course this dialog disappeared but show new empty dialog:

https://i.sstatic.net/gyr2C.png

What I did wrong and how can I resolve this problem?

Upvotes: 1

Views: 3506

Answers (2)

wero
wero

Reputation: 33000

You need to call JDialog.setVisible(true); in order to show the dialog.

But you have a bug in your code: You put the table in a scrollpane and add the scrollpane to the dialog (in method getShortcutKeysTable) and then add the table to the dialog again (in the constructor).

Your code runs fine if you do in the constructor

    ...
    getShortcutKeysTable();

    this.pack();
    this.setVisible(true);
}

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691903

What must be added to the dialog is the scollPane, which itself contains the table. Not the table itself.

You should decide what the getShortcutKeysTable()does:

  • either it creates a table, a scrollPane, and adds the scollPane to the dialog (and should be refactored to void createAndAddTable())
  • or it simply creates a table and returns it, and the caller is responsible for wrapping it into a scollpane and adding the scrollpane to the dialog.

Mixing the two responsibilities makes the code confusing, even for you who wrote the code.

In any wase, setting the size of the dialog is not its responsibility, and it's unneeded, since you call pack() after anyway.

Upvotes: 3

Related Questions