Dynamically adding a row
Hai
I am stuck with how to dynamically add a new row to my jtable provided that I do not know in the first place how many rows of data will the user enter.
Thanks a lot.
Hi,
Try
((DefaultTableModel)myTable.getModel()).addRow(object[] or Vector);
Note that getModel() returns a TableModel which is read-only. However the actual model it will return (unless you have changed it) is a DefaultTableModel, which is writable. So you need to do the cast then you can add rows to your heart's conent.
Hope this will help you.
Anil.
Developer Tecnical Support
Sun Microsystems Inc,
http://www.sun.com/developers/support
Similar Messages
-
Generating Indiex for dynamically added table rows in HRFORMS
Hi ,
We are developing Payslip in HRFORMS by copying standard form.
We have got one business scenario which requires a table rows needs to generated dynamically to populate the retro values in the form.
We could able to generate the table rows dynamically by below command in HRFORMs scripts.
Table1.Row.InstanceManager.addInstance(1) but it is not generating with correct index.
Please help in adding table rows dynamically at specified index.
Regards,
akulaYou can do that with 2 differents ways :
by creating a colomn key which is the concatenation of the key for each lin
by using field groups
I think you have to use the second one.
[sample by help|http://help.sap.com/saphelp_nw70/helpdata/en/ce/b518b6513611d194a50000e8353423/frameset.htm]
In this case you can put dynamiquely what are you wanted in your keys.
Regards,
Christophe. -
Dynamically adding a row in a table in JSF
Hi All,
I am searching for a control in JSF using which I can dynamically add more than one row in a table. Currently I am handling this in javasript where I have to click on the "Add Row" button to add one more row at the bottom of the table. I want to get rid of javascript.
If anyone knows about such control then please help me.
Thanks in advance.
Regards,
Sakethello Saketh,
here is the code for Create Delete Update code where a row is added for every button click..and the JSF code is at the bottom.. today u r blessed with ocean. :-) have fun!!
package redrose;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.Query;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
public class RowEntry {
private DataModel datamodel = null;
static Integer sid;
private Medata mdobject = null;
private Medata nm=null;
* @return Returns the newMdobject.
public Medata getNm() {
nm = new Medata();
return nm;
* @param newMdobject The newMdobject to set.
public void setNm(Medata newMdobject) {
this.nm = newMdobject;
* @return Returns the mdobject.
public Medata getMdobject() {
return mdobject;
* @param mdobject The mdobject to set.
public void setMdobject(Medata mdobject) {
this.mdobject = mdobject;
public DataModel getDatamodel()
datamodel = new ListDataModel();
Session hibSession;
try{
hibSession = HibernateSessionFactory.currentSession();
Query q = hibSession.createQuery("FROM Medata");
q.setMaxResults(9999);
datamodel.setWrappedData(q.list());
catch(Exception ex){
System.err.println("%%%% Error GetData %%%%");
ex.printStackTrace();
return datamodel;
* Inserting a new Record by reading from Client
public void insertEntry()
Transaction tx = null;
Session session = null;
try{
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
Medata dbmedata = new Medata();
dbmedata.setEmploy(nm.getEmploy());
session.save(dbmedata);
tx.commit();
session.close();
catch(Exception ex){
System.err.println("%%%% Modify Data %%%%");
ex.printStackTrace();
* Modify data
public void updateEntry()
int a =0;
if (this.datamodel == null) return;
Medata mdupdate = (Medata) this.datamodel.getRowData();
if (mdupdate == null ) return;
Transaction tx = null;
Session session = null;
try{
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
Medata dbmedata = (Medata) session.load(Medata.class,mdupdate.getId());
if (dbmedata != null){ // we have to update the record
dbmedata.setEmploy(mdupdate.getEmploy());
session.update(dbmedata);
else // we have to insert the record
dbmedata = new Medata();
dbmedata.setEmploy(mdupdate.getEmploy());
session.save(dbmedata);
tx.commit();
session.close();
catch(Exception ex){
System.err.println("%%%% Modify Data %%%%");
ex.printStackTrace();
* Delete Data
public void removeEntry()
if (this.datamodel == null) return;
Medata mdupdate = (Medata) this.datamodel.getRowData();
Transaction tx = null;
Session session = null;
try{
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
Medata dbmedata = (Medata) session.load(Medata.class,mdupdate.getId());
if (mdupdate == null ) return;
if (dbmedata != null){ // we have to update the record
session.delete(dbmedata);
tx.commit();
catch(Exception ex){
System.err.println("%%%% Delete Data %%%%");
ex.printStackTrace();
Here starts the JSF code
<%@ page language="java" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSF 'trial.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<f:view>
<h:form>
<h:dataTable border="3" value="#{bla.all}" var="currentRow">
<h:column>
<f:facet name="header">
<h:outputText value="Employee Name" />
</f:facet>
<h:inputText value="#{currentRow.employ}">
</h:inputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Employee Number" />
</f:facet>
<h:inputText value="#{currentRow.id}"></h:inputText>
</h:column>
<h:column>
<f:facet name="header">
</f:facet>
<h:commandButton id="Delete" action="#{bla.insert}" value="Delete"></h:commandButton>
<h:commandButton id="Modify" action="#{bla.modify}" value="Modify"></h:commandButton>
</h:column>
</h:dataTable>
<h:commandButton id="Insert" action="#{bla.insert}" value="Insert"></h:commandButton>
<%--h:outputText value="#{bla.sid}"></h:outputText--%>
</h:form>
</f:view>
</body>
</html>
Faces-config file starts here
<managed-bean>
<description>Inserts a record</description>
<managed-bean-name>bla</managed-bean-name>
<managed-bean-class>redrose.RowEntry</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
-
Dynamically adding a row and context binding
Hi All
i need to display existing values in DB in row wise
Also there is a add button on click of this add button i need to insert a row along with the exiting rows
and also bind a context to the new row.
Finally on clicking of Save button i need to update this to a database table
Please guide me how to insert a row dynamically and binding context to it
client dont want to use table.
Thanks
Karthi D.
Edited by: karthi D on Aug 22, 2008 6:35 AMHi,
Displaying table data in view without using table takes time and you need to work more.
To display the table data follow the below steps
1. Create the "TransparentContainer" UI element in view
2. create the context node and attribute according to your table data
3. get the table data and bind to context
IPrivateSDNView.ITableDataNode node = wdContext.nodeTableData();
IPrivateSDNView.ITableDataElement ele = null;
for(int i=0;i<tableRecords.length;i++) {
ele = node.createTableDataElement();
ele.setId(); // set your data to all attributes
node.addElement(ele);
4.in wdDoModifyView get the "TransparentContainer" UI element and set the layout and col size (ex: 4)
IWDTransparentContainer tContainer = (IWDTransparentContainer)view.getElement("TransparentContainer");
IWDGridLayout gridLayout = (IWDGridLayout)tContainer.createLayout(IWDGridLayout.class);
gridLayout.setColCount(4);
tContainer.destroyAllChildren();
5. Create the UI elements (textview, label ....) and add to tContainer
IPrivateSDNView.ITableDataNode node = wdContext.nodeTableData();
IWDTextView textView = null;
int count = 0;
for(int i=0;i<node.size();i++) {
count = 0;
textView = (IWDTextView)view.createElement(IWDTextView.class,""i(count++));
textView.setText(node.getTableDataElementAt(i).getAtt1());
tContainer.addChild(textView);
textView = (IWDTextView)view.createElement(IWDTextView.class,""i(count++));
textView.setText(node.getEmpDataElementAt(i).getAtt2());
tContainer.addChild(textView);
To insert records into the above table
1. Create the form with your fields with add button with Action "Add"
2. Create the context for this form
3. In onActionAdd method add the element to TableData node context
Let me know if you are not cleared with above code
Thanks -
Dynamically adding new rows and columns
i want to have a button on my jsp page which shud add new rows dynamically. and same one for columns.
how do i calculate the values across the rows on the forms
I'm new to JSP. Please point me in the right direction...any tutorials or code will be helpful.
thanksWell its a good question actually and the most needed one.
Say 4 example u need a screen which should accepts the employee details in one screen
and the user should be able to enter all the employee details in one screen and he should
have a flexibility to change the previous details too.
So 4 that u need to know 2 things:
1) Using of JspBeans
2) Using Vector
I will give u a brief idea:
So the bean is just a container been which has the methods say
setEmployeeName(.....)
getEmployeeName()
So the basic logic is, the naming of html form elements and displaying multiple rows of elements.
Say 4 eg, empname -> <input type=text name=empname<%= count%> value=<%= ....%>>
So u should run the loop the size of ur vector times and every time u add a vector u should save all
the data using same logic in ur vector and thatz it once u commit get all the values from the vector.
Try this u will definitely get it,
all da best,
kiran
kiran -
DYNAMICALLY ADDING A ROW TO A JSF COMPONENT
Hai users
Is it possible to add a new row to a datatable on click of a button.THe previous row&the contents in that table should also be maintained.
ThanksNot so difficutl.
You should hold the row data in a session scoped managed bean,
bind the value property of h:dataTable to the data,
and simply add a new row to them. -
I have pdf table like this:-
Header 1
Header 2
Header 3
Header 4
Header 5
Header 6
Header 7
From
To
No. of Days
Balance
Date
1
2
<ADD Button> / <Del Button>
3
4
5
This
Row
is
730
to
be
hidden
DateFieldFrom
DateFieldTo
DateFieldTo-DateFieldFrom(Some No1.)
Remaining1=uppervalue(730)-Some No1.
Now when i click the <add rows button> rows are to be added and i have to get the valuesof Remaining2(Remaining1- Some No.2 )in the Added Balance Row
how will i do this?Hi Luis,
According to your description, you have a report with different dynamic columns. Now what you want is show your user percentage growth in your matrix report after your user select two of those columns (I think you may use parameter to achieve your “checkbox”
function). Is my understanding correct?
In Reporting Service, we can’t calculate dynamic columns with our build-in arrogation functions. So we need to add custom code into our report, and call those functions which defined in custom code in our expression. We have tested your scenario in our local
environment. Here are steps and screenshots for your reference.
Go to your Report Properties, add the custom code below into your report:
Dim Shared Num1 As Double
Dim shared Num2 As Double
Public Function GetCalification(Calification as Double,Type as String,Type2 as String)
If Type = Type2 Then
Num1=Calification
Else
Num2=Calification
End If
Return Calification
End Function
Public Function GetPec()
Return (Num2-Num1)/Num1
End function
Create a matrix. Put PilarName into Row field, put Period into Column field. In Data field, put the expression below into the textbox:
=Code.GetCalification(Fields!Calification.Value,Fields!Period.Value,Parameters!Period.Value(0))
In our sample report, we created a parameter (named Period) for selecting two columns. You can replace “Parameters!Period.Value(0)” with your own parameter.
Add an outside column at right (%Growth), put the expression below into the textbox:
=Code.GetPec()
Save and preview. The matrix and result looks like below:
Reference:
Custom Code and Assembly References in Expressions in Report Designer (SSRS)
If you have any question, please feel free to ask.
Best Regards,
Simon Hou -
Reading the Data from dynamically added rows of a table...
Hi,
I am using adobe interactive form (WD ABAP) in which i am adding the table rows dynamically (using Jscript code). I have to fech these data into an internal table. But I can read only the first row data..
Also While adding rows dynamically the same data is repeating for the consecutive rows..
I have found many similar posts in sdn, but i cannot get the solution. They have mentioned about adding in WDDOINIT method. Can anyone explain me what should be done,..?
1) How to solve repeatative data while adding rows..?
2) How to read dynamically added row data during runtime into internal table..?
Thanks,
Surya.Discussed @ SDN lot of time before. Have a look at any of below threads:-
Dynamic table in interactive form...
Make dynamic tables in Adobe Interactive forms
Adding Rows dynamically upon clicking the button
How to get values to WebDynpro ABAP from dynamic table?
Chintan -
Adding Specific columns of dynamic internal table row into another column
Hi Gurus,
I need to add few columns of a dynamic internal table row into another column:
Article description hy01 hy02 total
101 panza 10 12 22
102 masht 12 12 24
dynamic internal table is created and columns hy01 hy02.... can increase
How to add the the values in hy01 hy 02... into total.
Regards,
DepHi,
If you really want to have a dynamic table, then you will have to find a way to generate a whole new table, and then copy the data from the old table to the new one. There is no way to modify a type during runtime in ABAP.
Here an example how to generate a dynamic table based on another internal table, hope this will help you.
TYPE-POOLS: slis.
PARAMETERS: p_nb_hy TYPE i DEFAULT 2. "Number of new HY columns to be added
* Type ZST_T:
* matnr TYPE matnr
* maktx TYPE maktx
* hy01 TYPE i
* total TYPE i
TYPES: ty_t TYPE STANDARD TABLE OF zst_s.
PERFORM main.
*& Form main
* text
FORM main.
DATA: lt_fieldcat TYPE slis_t_fieldcat_alv,
lt_t TYPE ty_t,
lr_new_t TYPE REF TO data.
FIELD-SYMBOLS: <lt_new_t> TYPE STANDARD TABLE.
"Add some lines to LT_T just to have something to display on screen
DO 10 TIMES.
APPEND INITIAL LINE TO lt_t.
ENDDO.
CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
EXPORTING
i_structure_name = 'ZST_S'
CHANGING
ct_fieldcat = lt_fieldcat.
"Copy LT_T to LR_NEW_T
PERFORM extend_and_copy_table USING lt_t p_nb_hy CHANGING lr_new_t lt_fieldcat.
CLEAR lt_t. "Not needed anymore...
ASSIGN lr_new_t->* TO <lt_new_t>.
CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
EXPORTING
it_fieldcat = lt_fieldcat
TABLES
t_outtab = <lt_new_t>.
ENDFORM. "main
*& Form extend_and_copy_table
FORM extend_and_copy_table USING ut_t TYPE STANDARD TABLE
uv_nb_hy TYPE i
CHANGING cr_t TYPE REF TO data
ct_fieldcat TYPE slis_t_fieldcat_alv
RAISING cx_sy_struct_creation cx_sy_table_creation.
DATA: lo_tabledescr TYPE REF TO cl_abap_tabledescr,
lo_structdescr TYPE REF TO cl_abap_structdescr,
lo_new_structdescr TYPE REF TO cl_abap_structdescr,
lo_new_tabledescr TYPE REF TO cl_abap_tabledescr,
lt_components TYPE cl_abap_structdescr=>component_table,
ls_component TYPE cl_abap_structdescr=>component,
lv_field_cnt TYPE numc2,
ls_fieldcat TYPE slis_fieldcat_alv,
lr_fieldcat TYPE REF TO slis_fieldcat_alv.
FIELD-SYMBOLS: <ls_old_s> TYPE ANY,
<lt_new_t> TYPE STANDARD TABLE,
<ls_new_s> TYPE ANY.
"Get the list of all components from UT_T line structure
lo_tabledescr ?= cl_abap_tabledescr=>describe_by_data( ut_t ).
lo_structdescr ?= lo_tabledescr->get_table_line_type( ).
lt_components = lo_structdescr->get_components( ).
"The new columns will be from type of column HY01
ls_component-type = lo_structdescr->get_component_type( 'HY01' ).
"The new columns will have the same fieldcat info as column HY01
READ TABLE ct_fieldcat INTO ls_fieldcat WITH KEY fieldname = 'HY01'.
"HY<lv_field_cnt> = new field name
lv_field_cnt = uv_nb_hy + 1.
"For each new column...
DO uv_nb_hy TIMES.
"Generate the new column field name
CONCATENATE 'HY' lv_field_cnt INTO ls_component-name.
ls_fieldcat-fieldname = ls_component-name.
"Add the new field to the components of the new structure
INSERT ls_component INTO lt_components INDEX 4.
"Add the new field's fieldcat info to the fieldcat
INSERT ls_fieldcat INTO ct_fieldcat INDEX 4.
lv_field_cnt = lv_field_cnt - 1.
ENDDO.
"Adjust the COL_POS from fieldcat
LOOP AT ct_fieldcat REFERENCE INTO lr_fieldcat.
lr_fieldcat->col_pos = sy-tabix.
ENDLOOP.
"Create the new table
lo_new_structdescr = cl_abap_structdescr=>create( p_components = lt_components ).
lo_new_tabledescr = cl_abap_tabledescr=>create( p_line_type = lo_new_structdescr ).
CREATE DATA cr_t TYPE HANDLE lo_new_tabledescr.
ASSIGN cr_t->* TO <lt_new_t>.
"Copy all data from old to new table
LOOP AT ut_t ASSIGNING <ls_old_s>.
APPEND INITIAL LINE TO <lt_new_t> ASSIGNING <ls_new_s>.
MOVE-CORRESPONDING <ls_old_s> TO <ls_new_s>.
ENDLOOP.
ENDFORM. "main -
Add null rows in WDDOINIT for fetching data from dynamically added rows..
Hi,,
I have to fetch data from a dynamically added rows of a table.
I have followed / gone through many forums but they ddnot mention how to add null rows in the initialization method..
I am using WD Abap..
Can anyone help how to bind null rows in WDDOINIT method..?
Thanks,
SuryaDiscussed @ SDN lot of time before. Have a look at any of below threads:-
Dynamic table in interactive form...
Make dynamic tables in Adobe Interactive forms
Adding Rows dynamically upon clicking the button
How to get values to WebDynpro ABAP from dynamic table?
Chintan -
Why data are not getting poulated in dynamically added tab in a tab navigator???
Hi All,
I am facing a very strange problem and need you expert opinion on this. Ok so the problem goes like this:
In my application i have a tab navigator where i have 2 fixed tabs say tab A and tab B. In tab B I have a data grid where All the user name are getting populated. Once the user clicks on any datagrid row i am dynamically adding a new tab based on username , so if in my datagrid u1,u2 and u3 are getting displayed then once you clik on u1 a new tab called u1 is getting displayed. Code for this goes like this:
var vbox1: VBox= new VBox();
box1.label=mydatagrid.selectedItem.uName;
var sde:* = new searchDetails();
vbox1.addChild(sde);
myTabnavigator.addChild(vBox1);
Application.application.searchdetails.displayall();
I have created a component called searchDetails where i have designed the page wit various fields for this tab.This also has a method called displayall() which is populating the data in all fields using php an my sql where i have designed the page wit various fields for this tab.
New tab is getting displayed perfectly. My problem is once the tab is getting displayed fields are not getting populated with data.
Please let me know what wrong i am doing. I am really strugglingHmm.. you have to assign text to the labelfields on creation complete not before that, the fllow will be like this
var vbox1: VBox= new VBox();
var sde:* = new searchDetails();
vbox1.addEventListener(creationcompleteevent,function);
vbox1.addChild(sde);
myTabnavigator.addChild(vBox1);
function(e:event):void{
box1.label = "text"; -
Passing values to form bean string array from dynamic added textboxes
Hi,
I am unable to pass values to form bean string array from a jsp in which I have incorporated dynamically adding of textboxes in javascript.
I have given add/delete row option in the jsp. If there is single row, this is working fine. But after adding a row, I am not able to either do any validations on added textboxes or pass the values to the String array form bean variable.
code snippet:
var cell6 = row.insertCell(4);
var element5 = document.createElement("input");
element5.type = "text";
element5.className = "formtext1";
element5.size = "5";
element5.value = "00.00";
element5.name= "qty"; // this is a string array of the form bean.
element5.onchange=function() {checkNumeric(this);};
cell6.appendChild(element5);
<html:text styleClass="formtext1" property="qty" value="" size="5" styleId="qty" onchange="checkNumeric(this)"/></td>
form bean declaration
private String[] qty; Please help.
Edited by: j2eefresher on Jan 12, 2010 11:23 PMShivanand,
There's no need to post that much code when you could create a very short test case that demonstrates only the problem you are having.
You're using &NAME. notation on something that isn't a page or application item. You can't reference PL/SQL variables that way (or any other way) outside the PL/SQL scope. For your situation, you could create a page item named P55_DOCID and assign it a value in the PL/SQL process (:P55_DOCID := DOCID;), then reference &P55_DOCID. in HTML areas like the success message.
Scott -
Dynamic Table - Add rows and columns in same table
Hi there,
I wonder if someone could help please? I'm trying to create and table where a user can add both rows and columns (preferably with separate buttons) but am having trouble trying to figure out how to do this. Is it possible? If so how? I'm not familar with script but have found examples of seprate tables where you can add a row and then another table where you can add columns and essentailly want to merge the two but cannot make it work.
Any help much appreciated!
Thanks,
KenIt is great example....you can learn the concepts there and apply....however you may have to think twice before you implement column adding dynamically....because the technique here is make copy of what we already have and reproduce it as a new item and this technique works great for rows as they all have every thing in common. But when it comes to columns it may have unique visible identity as column head and displaying repeatedly the same column head may not look good. Of-Course you can do few extra lines of code and change the column appearance based on users input each time. Situations where users need to add additional column is very unlikely (sure your requirement might be an exception).
Key in allowing adding/removing instances is managing design mode settings under Object>>Binding>>....and select the checkbox "Repeat <subform/row/...> for Each Data Item" and then set Min, Max and Initial count values.
Also you need to club your effots by using simple scipt with button clicks....
for the example refered in URL you posted following is what I did to make the first table allow Adding/Removing Rows....
1. Opened the form in LC designer.
2. Add two buttons AddRow & RemoveRow right next to RemoveColumn
3. For AddRow I used following JS code....
Table1._Row1.addInstance(1);//that means any time this button is clicked a new instance of Row1 is added use _Row2 or Row3 based on your needs
var fVersion = new Number(xfa.host.version); // this will be a floating point number like "7.05"
if (fVersion < 8.0) // do this for Acrobat versions earlier than 8.0
// make sure that the new instance is properly rendered
xfa.layout.relayout();
4. For RemoveRow I used following JS code....
Table1._Row1.removeInstance(1);//Syntax is...<objectReference>.removeInstance(<index of the repeating object that needs to be removed>); //in this case since we used 1 alwasys second object from top gets deleted.
var fVersion = new Number(xfa.host.version); // this will be a floating point number like "7.05"
if (fVersion < 8.0) // do this for Acrobat versions earlier than 8.0
// make sure that the new instance is properly rendered
xfa.layout.relayout();
5. Now time to update settings at Object>>Binding tab and set "Repeat......" and also set Min, Max and Initial count as explained above.
Those settings needs to be updated for Row1 (or your choice of row) of the table
6. Set the Height to Expand of the Subform, where the table is housed.... this is done under Layout pallet
7. Save the PDF as dynamic template and verify the results...
If you still run into issues I can send you copy that works on my machine, but you need send me an email at n_varma(AT)lycos.com
Good luck, -
Dynamically adding a column to a jtable - simple & urgent
I am new to using JTables.
I have read the tutorial and looked at several examples, but I am still confused as to how to add/remove columns and how to add rows to the table.
I want to have a totally dynamic table which will allow me to add/remove columns and to add rows.
The table gets the data to be displayed (and the column header values) from an outside object. I thought about writing my own table model.
Here is the code for my simple table model:
import javax.swing.table.*;
import java.util.Vector;
public class MyTableModel extends AbstractTableModel{
private Vector columnHeaders;
private Vector data;
// simple constructor
public MyTableModel() {
columnHeaders = new Vector();
data = new Vector(); // data is a vector of vectors
public int getColumnCount() {
return columnHeaders.size();
public int getRowCount() {
if (data.size() == 0) {
return 0;
Vector columnData = (Vector)data.elementAt(0);
return columnData.size();
public Object getValueAt(int row, int column) {
Vector columnData = (Vector)data.elementAt(column);
return columnData.elementAt(row);
// the method I call for dynamically adding a new empty column
public void addNewEmptyColumn(String value) {
columnHeaders.add(value);
fireTableStructureChanged();
}Here is how I use the table model with my table
import javax.swing.*;
public class Demo extends JFrame{
private JTable table;
public Demo() {
super("test");
table = new JTable(new MyTableModel());
getContentPane().add(table);
pack();
show();
public void addColumn(String value) {
MyTableModel model = (MyTableModel)table.getModel();
model.addNewEmptyColumn(value);
public static void main(String[] args) {
Demo demo = new Demo();
// here I am trying to add columns...
demo.addColumn("one");
demo.addColumn("two");
}I try to add columns, but nothing happens!!!
What am I doing wrong?
I would appreciate if someone who take himself/herslef to be a JTable expert could give me his/her e-mail and this way I won't bother the rest of the world with my stupid JTable questions...
Sincerely
NirI have another question.
What if I want to render the table headers in a certain way.
I would like to use:
TableColumn's setHeaderRenderer(TableCellRenderer headerRenderer).
But in order to do it, I need to get a TableColumn.
How do I get it from the model?
I thought about subclassing JTable and overriding:
public void tableChanged(TableModelEvent e)that function is called everytime I invoke fireTableStructureChanged().
In that function, I am assuming that a column has been added, however, when I query for JTable's getColumnCount(), I keep getting 0! -
How to add af:inputFile dynamically within each row of table?
I need to add af:inputfile dynamically within each row of af:table, when the user hits a commandlink at the bottom of each row.
I have tried wrapping af:inputfile with af:foreach:
<af:table value="Bean.rows" var="row">
<af:column>
<af:forEach step="1" begin="1"
end="#{Bean.filecount}">
<af:inputFile label="Please upload a file"
id="1"
valueChangeListener="#{Bean.onClickUpload}"/>
</af:forEach>
<af:commandLink text="Add more file" id="cl3" actionListener="#{Bean.onAddFile}"/>
</af:column>
</af:table>
in Bean.onAddFile, I have:
public void onAddFile(ActionEvent event){
filecount++;
It works but there's no independent control of each row. When I click one commandlink, All rows now have 2,3,.... af:inputFile. The change affects all rows.
The requirement should be that when I click one commandlink in a row, only that row shows additional af:inputFile.
So why not leverage the row variable of the table, right? That's what I did, I changed the end attribute of foreach to the following:
<af:forEach step="1" begin="1"
end="#{row.fileRowCount}">
the backing bean method changed to the following:
public void onAddFile(ActionEvent event){
int filerowcount = (Integer)JsfUtil.resolveExpression("#{row.fileRowCount}");
Integer newcount = filerowcount+1;
JsfUtil.setExpressionValue("#{row.fileRowCount}", newcount.toString());
Note that "row" refers to an object that has a int field called "filerowcount". And the initial value is "1".
Just for testing, I also added <af:outputText value="row.filerowcount"/>, to see if the count is what I expected it to be.
I didn't see the any af:inputfile this time, but the outtext is showing the filerowcount properly. When I click the commandlink, the number changed to 2,3,..... Also in the backing bean newcount and filerowcount is incrementing correctly.
I know the begin, end attribute means the index of a for loop. So I changed begin="0", it now shows one row of af:inputfile, but when I click the commandlink, no additional rows are shown. (Although the outputtext of filerowcount keeps incrementing as expected.
So to sum up, the END attribute of af:foreach row CAN pick up the value from the backing bean and render af:inputfile dynamically, but it CANNOT pick up the value from the the field in VAR object of a table.
Is is a known issue? Or I did something by mistake.
Is there any other way to add af:inputFile dynamically within each row of table?
Any advice/comment is appreciated.Hi,
here is how it goes:
- add an af:inputFile to the column and set its rendered property to point to a managed bean property. The managed bean property has a default value of "false" and the bean should be in viewScope
- create another variable that holds the row number that should show the inputFile component. This is updated by the command link and evaluated by the get method of the managed bean property controlling the inputFile visibility
- Define a property name for the table varStatus property
- For the command link, define a attribute f:attribute with the name rowNumber and set its value to #{varStatusPropertyName.index}
- define an action listener for the command link
public void showInputFile(ActionEvent actionEvent){
int rowNumber = ((RichCommandLink) actionEvent.getSource()).getAttributes().get("varStatusPropertyName");
//set the value on the internal variable
- In the getter of the property that defines the render value of the inputFile, use code like this
public boolean get<whatever name you use>(){
//access the following EL from Java #{varStatusPropertyName.index}
int currentRenderedRow = <EL result here>;
// compare the current row index with the one set by the command link, which is stored in the variable of the managed bean
if true return true
else return false
- Set the PartialTriggers property of the table to point to the commandLink ID so the table is repainted when the command link is pressed
This should then render the fileInput component for a single row (the one you clicked the command link in)
Frank
Maybe you are looking for
-
Filename problems file containing ' , o
Ive been a creative owner now for many years and its issues with filenames has never really bothered me before, the problem im having is similar to some threads i've read on here but not quite the same so i've opened a new thread.. When i sync my pla
-
YouTube and WiFi have a love-hate relationship
My iPhone for some reason refuses to play YouTube videos under WiFi. With Edge it will always play them but with not so great, albeit watchable, quality. On the rare occasions the WiFi works with YouTube the quality is great. When trying on WiFi I co
-
Acrobat X Pro not opening - Part II
I previously posted on this topic on April 19 and 20 (see http://forums.adobe.com/message/5253051#5253051), but surprisingly, received no responses. I am now reposting because the problem continues and I have been unable to find a satisfactory soluti
-
How do I moved my saved photos to my new Windows 8.1 computer?
I have Zoom Browser 4.1.0.46 which came with my Canon SD100 about 10 years ago. I have hundreds of photos saved and I want to move them from my windows XP computer to my new windows 8.1 computer. How do I transfer them? They're in a folder titled c:\
-
We are running Zenworks 7.00.0047 SP1. We ran product live update and went from IR 11 to IR 12. In the webconsole reports tab we get the following error. Details: [Microsoft][ODBC SQL Server Driver][SQL Server]Column 'nc_workstation.AssetType' is inv