SilentBomb
SilentBomb

Reputation: 168

how to add JTable in JFrame at Run time?

I am using a JFrame & JPanel to create a frame.JFrame contains comboboxes,CheckBoxes,JLabels etc.Layout of JPanel is set to "null",because i am using setBounds(int,int,int,int) to set the position of components on JFrame.

There is also a JButton(named as "Submit").On submit button i have added actionListener,so that if i click on this button,A table will generate on frame(at runtime).

JTable is successfully displaying on JFrame but Table columns name are not displaying along with JFrame(Only table data is displaying when submit button is pressed).

I am also using setBounds with JTable.What should i have to do in this case ?

submitButton.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
       Object ColumnName[] = {"Document Name", "Modified Date", "Size(in MB)"};
       Object data[][] = { {"test.txt", "24-Oct-2011", "540"}};
       table = new JTable(data,ColumnName);
       table.setBounds(20,230,330,100);
       panel.add(table);
       panel.repaint();
       panel.revalidate();
     }
});

Give me your all valuable suggestions soon. Thank you.

Upvotes: 1

Views: 7652

Answers (3)

mKorbel
mKorbel

Reputation: 109813

I think that you couldn't:

  1. Use setBounds(int, int, int, int), because this is job for LayoutManager
  2. Recreate JTable at run time. Just implement DefalutTableModel, there you can add/remove TableRows, reset TableModel - all changes are immediately displayed in JTable.

And you could:

  1. (As mentioned both posters) put JTable into a JScrollPane.
  2. Go through examples from the table tutorial and tons of Swing related examples here.

Upvotes: 2

Aman
Aman

Reputation: 548

You would need to add JTable into a JScrollPane first and then add that JScrollPane into your main panel.

JScrollPane jsp = new JScrollPane(jtable);

Have a look at this: JTable

EDIT: this thread discusses the same issue: Jtable Columns

Upvotes: 1

Sumit Singh
Sumit Singh

Reputation: 15886

may it works revalidate(); method of panel . call after setting table on panel.
but JScrollPane is best way to do this.

Upvotes: 2

Related Questions