adding columns

Reply

Join Date: Jan 2008
Posts: 36
Reputation: codered152 is an unknown quantity at this point 
Solved Threads: 0
codered152's Avatar
codered152 codered152 is offline Offline
Light Poster

adding columns

 
0
  #1
Jul 17th, 2008
Hi All
i have java question for you guys.
How can i add columns by click the button. i want my program keep adding columns whenever user click the button. any help.
Thank you
Best
Codered152
Reply With Quote Quick reply to this message  
Join Date: Mar 2004
Posts: 763
Reputation: Phaelax is on a distinguished road 
Solved Threads: 38
Phaelax Phaelax is offline Offline
Master Poster

Re: adding columns

 
0
  #2
Jul 18th, 2008
I'm assuming you're talking about adding columns to a JTable? Check out the methods in the DefaultTableModel class.
Reply With Quote Quick reply to this message  
Join Date: Jul 2007
Posts: 66
Reputation: vidaj is an unknown quantity at this point 
Solved Threads: 14
vidaj vidaj is offline Offline
Junior Poster in Training

Re: adding columns

 
0
  #3
Jul 18th, 2008
I'm also assuming you're talking about adding columns to a JTable.

Adding a new column to a table is quite simple. it goes something like this:
  1. JTable tabell = new JTable();
  2. TableColumn column = new TableColumn();
  3. column.setHeaderValue("New column");
  4. tabell.getColumnModel().addColumn(column);

Unfortunately, the hard part is getting meaningful data to the column.

A JTable (usually) works in the following way:
You have a list of data.
You have a TableModel that transform an object from the list of data into columns.
You have the JTable that converts the information from the TableModel into TableColumns.

This way each column is mapped to specific data from the objects in your datalist. By dynamically adding columns in the way I described above, you also have to either write a tablemodel that handles variable number of columns, or you somehow have to fetch the data you want to display in a custom cellRenderer.

Edit:
To answer the rest of the question - how to add it with a button:

  1.  
  2. class ButtonListener implements ActionListener {
  3.  
  4. private JTable table;
  5.  
  6. public ButtonListener(JTable table) {
  7. this.table = table;
  8. }
  9.  
  10. public void actionPerformed(ActionEvent e) {
  11. TableColumn column = new TableColumn();
  12. column.setHeaderValue("column header");
  13. this.table.getColumnModel().addColumn(column);
  14. }
  15.  
  16. }
  17.  
  18. JTable table = new JTable();
  19. JButton button = new JButton();
  20. button.addActionListener(new ButtonListener());

Hope that helps
Last edited by vidaj; Jul 18th, 2008 at 5:31 am. Reason: added button code
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC