Turning ArrayList of Rows into a JTable - java

I decided it would be easiest to store my data in a custom Row object based on this post
Java data structure to store tabular data
But Im wondering how I actually go onto then create a JTable with this Array of row objects
My current attempt starts out looking like this:
public class TestTable extends JTable {
private final String[] columnNames = {"col1", "col2", "col3"};
public TestTable() {
DefaultTableModel model = new DefaultTableModel(columnNames, 10); //10 is just a placeholder for the number of rows as I dont know how to add the data yet
}
}
My data would be stored in an ArrayList that looks like this:
Row row1 = new Row("1", "2", "3");
ArrayList<String> data = new ArrayList<String>;
data.add(row1);
data.add(row2);
...
data.add(row10);
where my final ArrayList would just look like a list of row objects

List<String> data = List.of("1", "2", "3" );
model.addRow(data.toArray());
would be a simple approach

Related

How to fill a JTable with data from a HashMap?

I'm new to Java and I want to know how to fill a JTable with HashMap data. In the hash map, the key is an integer and the value is an array of objects. I want to put the data from the hash map into the table, but I don't know how to get the values.
The HashMap:
Map<Integer, Object[]> prodList = new HashMap<>();
prodList.put(1, new Object[]{"Prod_1", 8000.0, 550}); //name, price, amount
prodList.put(2, new Object[]{"Prod_2", 2300.0, 15});
prodList.put(3, new Object[]{"Prod_3", 2700.0, 15});
I have been trying with this:
public TableModel fillTable(Map<?,?> prodList)
{
DefaultTableModel tableModel = new DefaultTableModel(
new Object[] {"key", "value"}, 0
);
for(Map.Entry<?,?> data : prodList.entrySet())
{
tableModel.addRow(new Object[] {data.getKey(), data.values()});
}
return tableModel;
}
But it just returns the key and this: [L] java.lang.Object; # 1565e42a. I think I have to iterate over the array and put all the array values ​​into a new column, but I don't know how to do it.
I think I have to iterate over the array and put all the array values ​​into a new column,
Correct. You can do this by adding all the values to a Vector and then add the Vector to the model.
Iterator<Integer> iter = prodList.keySet().iterator();
while (iter.hasNext())
{
Vector<Object> row = new Vector<>(4);
Integer key = iter.next();
row.addElement(key);
// Cell represents a row after the inserted row
Object[] values = (Object[])prodList.get(key);
for (Object item: values)
{
row.addElement(item);
}
System.out.println(row);
tableModel.addRow( row );
}
The above code should will create a Vector with 4 items, the first will be the key and the last 3 will be the values in the Array that you added to the HashMap.
Note, I rarely iterate over a HashMap and I don't remember how to use the EntrySet, so I'm just using the old Iterator.
Figured out how to do it using the EntrySet:
for(Map.Entry<Integer,Object[]> data : prodList.entrySet())
{
Vector<Object> row = new Vector<>(4);
row.addElement(data.getKey());
Object[] values = data.getValue();
for (Object item: values)
{
row.addElement(item);
}
System.out.println(row);
tableModel.addRow( row );
}

Data structure like hashmap but with the ability to swap indexes in Java

I want to use a data structure to store column names of a JTable with their respective indexes, so that I can select the corresponding data column. If I filter out a column name, then the name and the index gets removed, if I put it back, the index will be the same. If I want to swap two columns, the indexes change but the column names stay the same. It also has to be serializable. Can I do this with a HashMap<String,Integer>?
I managed to load it with values, I basically filtered the dataList with the selected columnNames. I'm not too familiar with maps. As far as a know, I can't "swap" key's in HashMap
private List<Object[]> data = new ArrayList<Object[]>();
private List<String> columnNames = new ArrayList<String>();
public CustomTableModel(List<Object[]> dataList, Map<Integer,String> columnNames) {
for (Map.Entry<Integer, String> set : columnNames.entrySet()) {
this.columnNames.add(set.getValue());
}
ArrayList<Integer> selectedColIndexes = new ArrayList<Integer>();
for (Map.Entry<Integer, String> set : columnNames.entrySet()) {
selectedColIndexes.add(set.getKey());
}
for(int n=0; n<dataList.size(); n++) {
Object[] selectedRow = new Object[columnNames.size()];
for(int j=0; j<selectedColIndexes.size(); j++) {
int index = selectedColIndexes.get(j);
selectedRow[j]=dataList.get(n)[index];
}
data.add(selectedRow);
}
}

How to set Data to multidimensional array in Java?

I try to set data from list to two multidimensional array.
Normally I can set data to two multidimensional array like this:
Object[][] newData = {
{ "test", "test2", 15.98, 0.14, "+0.88%",
32157250 },
{ "AAPL", "Apple Inc.", 126.57, -1.97, "-1.54%", 31367143 }"
However I want to set data dynamically from list .
I have a method wich return a list :
List<User> user = listUser(id);
static User {
private int id;
private String name;
and getter(...),setter(..).
I need to set user from listUser(id) method to Object[][] array.
I try to do it but I couldnt get succesfull result :
for (int i=0;i<user.size();i++){
for(int j=0;j<user.size();j++){
newData[i][j]=user.get(i).getName();
}
}
Could you help me ?
The columns are fixed, i.e., 0,1,2,etc.. and you need to iterate and set the data for each row as shown below:
for (int i=0;i<user.size();i++){
for(int j=0;j<user.size();j++){
newData[i][j]=user.get(i).getId();//get id for each rowand set to 0th column
newData[i][j]=user.get(i).getName();
newData[i][j]=user.get(i).getX();//other fields
newData[i][j]=user.get(i).getY();//other fields
}
}
Also, it is not a good idea to use Object[][] (not sure for what reason you are using this) as it requires explicit casting while retrieving/using the fields.
It looks like the data is well structured. I would create a class and keep a single-dimension array of your private "CompanyStock" class instead of using a dangerous 2d Object[][] array.

JTable with data from properties file

I have simple JTable object with 2 columns. I want to put here values from file.properties but I don't know how do this.
For example file.properties looks like:
some1.text1=Text1
some1.text2=Text2
some2.text1=Text_1
some2.text2=Text_2
And now I want to add these data to TableModel like this(it's example from swing):
Object rowData[][] = { { some1.text1, some2.text1 }, ... };
How can I do this?
You would NOT create a 2 dimensional array since you may not know how many properties you have.
Instead you would create one row of data for each property and then add the row to the DefaultTableModel. The basic logic would be something like:
String columnNames = { "Column1", "Column2" };
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
for (each property pair)
{
Vector<String> row = new Vector<String>(2);
row.addElement( get first value );
row.addElement( get second value );
model.addRow( row );
}
JTable table = new JTable( model );
I found one way to do this using 'new Property()'
This read my file.propertieswell but now I'm interesting something else. How can I read my file in other way, for example my file.property looks like:
some.1.name=...
some.1.value=...
some.2.name=...
some.2.value=...
I can read each of them like this
#ResourceBundleBean(key="some.1.name")
private String some_1_name;
#ResourceBundleBean(key="some.1.value")
private String some_1_value;
etc...
But if is there possibility to use only one String field for for name and value(Value is String too) OR only 1 String field to get each property some.1. some.2. etc and get from this field name and value?
For example if my file.properties will have many item only with name/value some like:
some.1.name=...
some.1.value=...
...
some.200.name=...
some.200.value=...
I do not want to create 200 fields to do this. Is it possible?
Or if it is not possible how can I read arrays from property?
Instead of upper properties make some like this:
some.[1].name=n1
some.[1].value=v1
...
some.[200].name=n200
some.[200].value=v200
And how can I read this array to use it for output some like:
n1 - v1
...
n200 - v200

Get only one row from hashmap

I'm new for android.
Now I'm using hashmap to show my listview
Below is my SimpleAdapter,
private SimpleAdapter createSimpleAdapter() {
List<Map<String, String>> data = this.createData();
return new SimpleAdapter(this, data, R.layout.menuui,
new String[] {
"name", "food"
}, new int[] {
R.id.membername, R.id.food
});
}
I want to get only one row but if I use listview.getItemAtPosition(position).toString() just like this {food=Onigiri, name=Hashimoto Nanami}
How can I get only one row ?
If there's not enough information to let you know what I ask, please tell me, thanks.

Categories

Resources