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);
Related
the task which I do is quite simple, but I faced one problem with JList component.
What i need is. I fetch data from DataBase, load it to String array, pack array into ArrayList (just because I duno how many records I have), return it from method as ArrayList.
Now at receiver side. I have a trouble, I cant fetch String array from ArrayList so that I can pass to JList.
Here is the code.
ArrayList<Object> fetch = new ArrayList<Object>();
public String[] data =new String[10];
listModel = new DefaultListModel();
myList = new JList(listModel);
//myList = new JList(data);
// So it works with simple array of strings.
fetch=DAO.loadPasswords();
//At this point it asks me to cast an object to smth which late cause null pointer exception.
myList = new JList(fetch.get(0));
And here is loadPasswords();
public static ArrayList<Object> loadPasswords(){
dbConnect();
boolean unswer = false;
String[] result=null;
String query1 = "select * from tblPasswordsStorage where "
+ "_user_id = ?";
String userId=Personal_Organizer.userProfile.getUserID();
ArrayList<Object> params = new ArrayList<Object>();
params.add(userId);
executeQueryP(query1, params);
ArrayList<Object> fetched=null;
try {
if (rs.next()) {
unswer = true;
//Personal_Organizer.userProfile.setUserID(rs.getString(1));
result[0]=rs.getString(1);
result[1]=rs.getString(2);
result[2]=rs.getString(3);
result[3]=rs.getString(4);
result[4]=rs.getString(5);
result[5]=rs.getString(6);
result[6]=rs.getString(7);
result[7]=rs.getString(8);
result[8]=rs.getString(9);
result[9]=rs.getString(10);
fetched.add(result);
}
if (unswer) {
while (rs.next()) {
Tools.print(rs.getString(1));
}
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,
"SQL Server connection issue.\n"
+ "Please, check Server address, user name and password.",
"Output",
JOptionPane.PLAIN_MESSAGE);
}
dbClose();
return fetched;
}
I tried to use multidimensional array but still JList require single dimensional array.
Either use a DefaultListModel and load it with your Strings using a simple for or for-each loop that loops through your ArrayList, adding each String item in the ArrayList into the model, or create your own ListModel class, one that extends AbstractListModel and that uses the ArrayList as its data nucleus.
Edit, since your data is held in an ArrayList of arrays, then perhaps you don't want to display it within an ArrayList after all, but rather in a JTable. Here your best bet would be to create your own TableModel, one based off of AbstractTableModel and that uses your ArrayList as its data nucleus. Also, perhaps better than loading your data into an array would be to create a custom class to hold each row of data from the ResultSet.
You state:
My problem is to simply load something to JList. The idea is to display application/website name in the list, then when you click on it, you get full data which contains in array. That's why I put fetch.get(0)...because. I need at least something.
Then
Create a custom class to hold each row of data.
Create items of this class from each row of the ResultSet
Fill your DefaultListModel with items of this class
Give your JList a custom ListCellRenderer, one that display's the application/website name
Then you can display the name and still have each list item hold all the pertinent information that it needs.
i was setting the number of rows of my Table in java using properties of the table but how can i add new row inside the code because i don't know the number of inputs that should be entered?
but how can i add new row inside the code
This will depend on the implementation of the TableModel, for example, the DefaultTableModel provides two addRow methods.
The TableModel itself doesn't provide this functionality directly and is dependent on the physical implementation to provide this functionality if and when required.
See How to Use Tables for more details
first, i set the number of rows equal "0" in the properties of the table
second, write this code in the for loop with your condition
ArrayList arr = new ArrayList();
for (int i = 0; i < shipmain.files.length; i++) {
arr.add(shipmain.files[i]);
arr.add(shipmain.fabricName[i]);
arr.add(shipmain.color[i]);
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.addRow(arr.toArray());
jTable1.setModel(model);
arr.remove(shipmain.files[i]);
arr.remove(shipmain.fabricName[i]);
arr.remove(shipmain.color[i]);
}
AddRow() function must take an object and ArrayList provided that
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;
}
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.
I have a JTable, which is a DefaultTableModel. The data in the table is accessed from the ArrayList CarList. The problem I am having, is that after I delete the row, it is only deleted temporarily. To delete the row in the project, the user has to select a row and then press the button delete. When I use the coding that I am using, the row is deleted from the jTable, but the data is not removed from my Arraylist, so when I open up the JTable again, the row that I deleted is still there. Can anyone please help me? I have some coding here :
ArrayList CarList = CarRentalSystem.CarList;
UsingFiles CarFile = CarRentalSystem.CarFile; //ArrayLists accessed from the whole project
/**
* Creates new form ViewCars
*/
public ViewCars() { //creating the table and accessing the data from the arraylists
initComponents();
this.CarList=CarList;
DefaultTableModel model = (DefaultTableModel) carTable.getModel();
for (int i=0; i<CarList.size(); i++){
Car car = (Car) CarList.get(i);
model.addRow(new Object[]{car.getCarNum(), car.getManufacturer(), car.getModel(), car.getBooked(), car.getAircondition()});
btnEdit.setVisible(true);
btnDelete.setVisible(false);
btnSave.setVisible(false);
}
//delete button coding
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) this.carTable.getModel();
int[] rows = carTable.getSelectedRows();
for(int i=0;i<rows.length;i++){
model.removeRow(rows[i]-i);
JOptionPane.showMessageDialog(null, "Row Deleted"); //the row is deleted but the data isn't
}
}
}
Each time you create the JTable model you are taking all of item in your car list. You delete them from the table model, but you never remove the items from your array list. You need to modify your deletion code to remove from the carList.
You should also be naming your variables using lower camel case conventions.
I would create your own table model that contains the car list so that the table model itself can directly remove things from the car list. Unless you have use cases for the car list not being in sync with what you display in your JTable.
Here you are failing to remove the items from ArrayList, therefore every time you create the JTable model all the items from CarList are added to JTable.
You need to add
CarList.remove(Object_To_Remove);
to your delete code.
For more help on how to delete objects from ArrayList see this. Remove Item from ArrayList this question on StackOverflow may help you. Or better way you can directly go for Docs.