I have a table which has only field names and no data, I want to enter data from inputs
by Vector
i try this cod but is't work
Object[][] ss= new frand[1][];
for(int i = 0 ; i<feeds.size();i++){
ss[1][i]=feeds.get(i);
}
JTable table = new JTable(
// new Object[][] {
// new frand[] { feeds.get(0) },
// new frand[] { feeds.get(1) }
// },
ss,
new String[] { "connect client " }
);
frandtabmodule module = new frandtabmodule(feeds);
table.setModel(module);
how do I do that?
to load the table from an array A, if the table just create it, you can simply use:
table.setModel (new javax.swing.table.DefaultTableModel (
new String [] [] {
{"2014-02-22", A.get(0)}
} ,
new String [] {
"Date", "Total"
}));
if not, you can use the DefaultTableModel class and its methods and AddColumn addRow
It seems that you first create a table by passing data and columns, then create a model and set the model. When you pass column and row data in JTable constructor, then the table creates and uses DefaultTableModel that is initialized with that data. If you have a specialized model frandtabmodule that wraps around the original vector feeds there is no need to build an array and pass it to the table. Just use JTable default constructor and then call setModel, or use a constructor that takes a model as an argument.
See How to use Tables for more details and examples.
EDIT:
Not sure is that is the intention, but the posted code indicates that you want to use the vector elements as columns. If that is not the intention, then it seems you have a mix up of indexes while building an array. The first set of square brackets is for the rows and the second is for columns. For example:
private static Object[][] vector2DArray(Vector<Object> sourceVector) {
Object[][] rows = new Object[sourceVector.size()][1];
for (int i = 0; i < sourceVector.size(); i++) {
rows[i][0] = sourceVector.get(i);
}
return rows;
}
Related
My goal is to create a JTable and populate it with rows using either a Vector or an ArrayList. I am using IntelliJ IDEA's form builder to create the tables (not sure if this matters).
private void createUIComponents() {
// Will need to check custom create, otherwise the table data will get overwritten.
Vector<String> columns = new Vector<>();
columns.add("Name");
columns.add("Telephone");
columns.add("Last Visited");
columns.add("Reason");
columns.add("Attended by");
CSVReader patient = new CSVReader("./patients.txt");
ArrayList<Patient> patient_data = patient.parse();
Vector<String[]> table_data = new Vector<>();
for (Patient p:patient_data) {
for (int i = 0; i < p.doctors.size(); i++) {
String reason = p.reason.get(i);
String date = p.previousVisitations.get(i);
String doctor = p.doctors.get(i);
String name = String.format("%s %s", p.fname, p.lname);
String[] info = {name, p.telephone, date, reason, doctor};
table_data.add(info);
}
}
staffTimetableView = new JPanel();
staffTimetableView.setLayout(new BorderLayout());
staffTimetable = new JTable(table_data, columns);
This is the code for adding data to a table. I've created two vectors one with the column names and one with the actual entries in it. I've checked table_data's elements and verified the they are formatted as intended. The problem lies in the final line where I create a new instance of JTable.
Cannot resolve constructor 'JTable(Vector<String[]>, Vector)'
This is the error. I've checked the types of the arguments required by the constructor but I didn't get anything useful that I could understand.
JTable(Vector rowData, Vector columnNames)
Constructs a JTable to display the values in the Vector of Vectors, rowData, with column names, columnNames.
This is what is said in the documentation. I took a look at Vector in the parameters to see if there's a different kind of vector but no. It doesn't specify what the vector has to contain either. I've tried changing the type of table_data to just Vector<String> and in the for loop change tabe_data.add(info) to table_data.add("aaa") to match the type of columns which is Vector<String> however, I got the same error about not being able to resolve the constructor.
I've also tried using ArrayList instead. The code remains the same only changes are changing the type of columns from Vector<String> to ArrayList<String>. I converted table_data to an ArrayList<String[]>. Then casted it to an Object[][] like so.
Object[][] yy = {table_data.toArray()};
This leads to an error during runtime, nothing is displayed in the table. Because x looks like this.
One tedious way to solve this is to set each item individually like this.
Object[] d1 = (Object[]) table_data.toArray()[0];
Object[] d2 = (Object[]) table_data.toArray()[1];
Object[] d3 = (Object[]) table_data.toArray()[2];
Object[] d4 = (Object[]) table_data.toArray()[3];
Object[][] d = {
d1,
d2,
d3,
d4
};
Passing d into the JTable constructor that accepts Object[][] will run just fine. However, I want this to be dynamic as there are going to be many rows later on. I am at a lost and I have no idea what to do. Any help is appreciated, thanks.
I saw this Need to add JCheckBox In JTable Dynamically but it didn't help at all seeing my situation is similar but I am not sure how to add the JCheckBox after I have take the raw data from my database.
public void fillAnyTable(ResultSet resultSet, JTable table)throws SQLException{
//Create new table model
DefaultTableModel tableModel = new DefaultTableModel();
//Retrieve meta data from ResultSet
ResultSetMetaData metaData = resultSet.getMetaData();
//Get number of columns from metadata
int columnCount = metaData.getColumnCount();
//Get all column names from metadata and add columns to table
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++){
tableModel.addColumn(metaData.getColumnLabel(columnIndex));
}
//this is when I assume I can create a new column but now how to add the checkbox
tableModel.addColumn("Check");
//Create Array of Objects with size of Column count from metadata
Object[] row = new Object[columnCount];
//Scroll through Result Set
while (resultSet.next()){
//Get object from column with specific index of result set to array of objects
for (int i = 0; i < columnCount; i++){
row[i] = resultSet.getObject(i+1);
}
System.out.println(Arrays.toString(row));
//Now add row to table model with that array of objects as an argument
tableModel.addRow(row);
}
//Now we add the table model to the table
table.setModel(tableModel);
}
}
This is what the view looks like
I am not sure how to add the JCheckBox after I have take the raw data from my database.
You don't add a JCheckBox. The TableModel holds data, not components. So you need to:
override the getColumnClass(...) method of the TableModel to return Boolean.class for the column where you want the check box. Then the table will use the proper renderer/editor for a check box.
add Boolean.FALSE to the TableModel when you add the data from the ResultSet.
So you just add the Boolean value when you are finished adding each column value to your row array:
//Now add row to table model with that array of objects as an argument
row[columnCount].add( Boolean.FALSE );
tableModel.addRow(row);
Of course you will also need to make your "row" array larger to hold this value.
the size of table limit is set as static limit and i want to change that to dynamic
here jtable & object declared.
public JTable issuetable = null;
static Object[][] data;
here is my jtable
public JTable getIssues() {
issuetable = new JTable();
String[] colName = {"Member", "Book", "Issue Date", "Return Date ",
"Remarks" };
List<Issue>issues=ServiceFactory.getIssueServiceImpl().findAllIssue();
the size of issuedata is limited to 100000 .. i want to change the limit to dynamic..
data=new Object[issues.size()][100000];
for(Issue issue:issues){
data[i][0]=issue.getMemberId().getName();
data[i][1]=issue.getBookId().getName();
data[i][2]=issue.getIssueDate();
data[i][3]=issue.getReturnDate();
data[i][4]=issue.getRemark();
data[i][5]=issue;
i++;
}
if u know answer please share here..
In your previous question, You were using a DefaultTableModel. Keep in mind, a TableModel is a data structure in itself. There is no need at to store the data in two data structures, i.e. your data[][] and the DefaultTableModel. The underlying structure of DefaultTableModel is a dynamic Vector of Vectors.
What you can do is this. Just declare your DefaultTableModel with 0 rows, using this constructor
public DefaultTableModel(Object[] columnNames, int rowCount)
Then just add rows dynamically to the structure with
public void addRow(Object[] rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
So basically, your declaration will be like this
String[] colName = {"Member", "Book", "Issue Date", "Return Date ", "Remarks" };
DefaultTableModel model = new DefaultTableModel(colName, 0);
JTable table = new JTable(model);
Then just add rows like
String member = "Stack";
String book = "overflow";
Data issueDate = date;
....
Object[] row = { member, book, issueDate, returnDate, remarks };
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(row);
Please read the DefaultTableModel api documentation to see more constructors and methods available
Instead of an array, use a dynamically resizable data structure in your implementation of AbstractTableModel. This EnvDataModel is an example that contains a Map<String, String>.
Instead of copying all the data from your List to the DefaultTableModel you can use your List as the data structure for a custom TableModel. Then you can add/remove Issue object from this TableModel.
See the JButtonTableModel.java example from Row Table Model for an simple example of how the RowTableModel can be extended to give you this functionality.
Using this approach the data is only ever in one place and you can access Issue objects directly from the TableModel.
Hi I want to check if table is made to add rows.If is not I want to show message :create table first. My problem : I do not know what I should type to if statement to check if is although one row made(which can suggest me that table was created).
I create table via NetBeans JFrame options this way:
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
/*
space is empty here because on start I do not create any rows.
user has to click button create or add rows.
*/
},
new String [] {
"Name", "Surname"
}
));
My if statment:
if(//do not know what type here because new Object [][] will not work){
JOptionPane.showMessageDialog(null, "Create table!");
}else //add row to table because exist {
Object[][] temp = new Object[data.length + 1][2];
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < 2; j++) {
temp[i][j] = data[i][j];
}
}
data = temp;
jTable1.setModel(new DefaultTableModel(data, columns));
}
Looks like you're using NetBeans GUI builder. If you go to the properties pane (the tab to the very right in Netbeans design view) with the jTable highlighted, you will see a property model
Click on the ... button to the right of the property, and a Dialog will pop up
Set the number of rows to 0, and the number of columns to how many columns you want, and set the column title and type and if you want it editable
Then in your actionPerformed, however you get the data for rows, add an array of that data to the model with model.addRow()
public void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// get row data, and put it into an array
Object[] row = {data1, data2, data3 ...};
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.addRow(row);
}
So whenever the button is pressed, a row will be added dynamically to your table. That's the easiest way to do it with GUI Builder
EDIT
If you want to check the number of rows then you check the rowCount
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
if (model.getRowCount() < 1) {
do something.
}
i hav a ArreayList which is contain PRIvariable(name of the class) class data. Below shows my part of the java code. So now i want to put this Arraylist data to Jtable. how can i do that. Here i already added pri.dateText , pri.sum , pri.count to ar(arraylist)
PRIvariable pri=new PRIvariable();
while (reader.ready()) {
String line = reader.readLine();
String[] values = line.split(",");
if(values[2].equals(pri.incDate)){
if(values[4].equals("KI")){
pri.dateText=values[2]+" "+values[4];
pri.count=pri.count+1;
pri.sum = pri.sum+Integer.parseInt(values[7]);
}
}
}
System.out.println(pri.dateText+" "+pri.sum+" "+pri.count);
ar.add(pri);
Like all Swing components, a JTable relies upon the MVC pattern (at multiple levels, but that's not the subject).
You have one view (the JTable), one model (I'll come back on it later), and a controller (implemented here as a set of event listeners : one controller for each kind of control).
The array you have could be a good model starting point. However, Swing provides far better way to inject your data in JTable. Indeed, a JTable uses as model an implementation of TableModel. Hopefully, there already exist an implementation : DefaultTableModel.
So, here is what I suggest to you : create DefaultTableModel, put in its rows/columns all the data you want to display in your table, then call JTable#setModel(TableModel) to have thze table display your data.
Obviously, you'll soon find various misfits between DefaultTableModel and what you want to do. It will then be time for you to create our very own table model. But that's another question.
Besides, don't forget to take a look at Swing tutorial, it's usually a good thing when dealing with Swing components.
I don't see where you have an ArrayList anywhere.
First you create a PRIvariable object. Then you keep looping as you read a line of data from the file. For each line of data you split it into individual tokens and then add some of the token data to the PRIvariable ojbect. The problem is that you only have a single PRIVariable object. So every time you read a new line of data you change the values of the PRIvariable object. After all the looping you add this single PRIvariable object to your ArrayList, but you will only ever have one object in the ArrayList.
The easier solution is to update the TableModel as you get the data. Something like:
DefaultTableModel model = new DefaultTableModel(...);
JTable table = new JTable( model );
...
...
while (reader.ready())
{
String line = reader.readLine();
String[] values = line.split(",");
String[] row = new String[3];
row[0] = values[?];
row[1] = values[?];
row[2] = values[?];
model.addRow( row );
}
Look into GlazedLists. They make it extremely easy to create a suitable TableModel object from your list.
ArrayList< PRIvariable> myList = new ArrayList<PRIvariable>();
... fill up the list ...
// This assumes your object has a getName() and getAge() methods
String[] propertyNames = {"name","age"};
String[] columnLabels = {"Name","Age"};
// Are these columns editable?
boolean[] writeable = {false, false};
EventList<PRIvariable> eventList = GlazedLists.eventList(myList);
EventTableModel<PRIvariable> tableModel = new EventTableModel<PRIvariable>(eventList,propertyNames,columnLabels,writable);
JTable table = new JTable(tableModel);