JTable 3 fields arrayList - java

I am trying to add values to a Jtable, the values are fetched from arrayList,
How do you do that
I tried making Object[][] data; and the populate it inside a loop, but it does not work, How do you fix this?
String[] columns = {"Field String","Field Double"," Field Double"};
Object[][] data;
Iterator<Node> itr = arrayList.iterator();
while (itr.hasNext()) {
Node el = itr.next();
double a = el.getval();
data[i][1] = el.getstring();
data[i][2] = a;
data[i][3] = a*4;
i++;
}
JFrame frame = new JFrame("Title ");
JTable tablE = new JTable(data, columnas);
JPanel panel = new JPanel();
panel.add(table);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
How do you populate "data" inside a while loop?

Use a DefaultTableModel and add rows of data using its addRow(Object[]) or addRow(Vector) method. Set this as your JTable's model. The API and the JTable tutorial can get you started.
For e.g.,
ArrayList arrayList = new ArrayList();
String[] columns = {"Field String","Field Double"," Field Double"};
DefaultTableModel model = new DefaultTableModel(columns, 0);
for (Object item : arrayList) {
Object[] row = new Object[3];
//... fill in row with info from item
model.addRow(row);
}
JTable table = new JTable(model);
This demonstrates doing it with a for loop, but a while loop would be similar.

Related

Create a JTable using an ArrayList of "n" AbstractDrawablePoints

I have an ArrayList<AbstractDrawablePoint> nodePoints which changes dynamically/can have anywhere from 1 to n number of points within it.
I would like to have a JTable fill dynamically based on the number of points within nodePoints. Currently, I can hardcode an Object [][] to do so like the following:
String[] columnNames = {"u", "v"};
Object[][] nodeData = new Object[][] {
{nodePoints.get(0).getU(), nodePoints.get(0).getV() },
{nodePoints.get(1).getU(), nodePoints.get(1).getV() }
};
JTable table = new JTable(nodeData, columnNames);
However, I would like to fill nodeData dynamically instead of hard coding like I did.
Based on #g00se's answer I came up with the following:
String[] columnNames = {"u", "v"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames,0);
for (AbstractDrawablePoint node: nodePoints) {
Object [] currentNode = {node.getU(),node.getV()};
tableModel.addRow(currentNode);
}
JTable table = new JTable(tableModel);

Put firebase data in a JTable

I am struggling to put some firebase data into a jtable in java swing.
As seen in photo I've been able to retrieve the data from firebase but for some reason the data won't be displayed in the JTable field(table1)
I looks like the getID(), getName()... methods didn't get any value, since I tried to print row[i] to see if there is any value.
There is a screenshot of the actual program
Could any of you tell what's the problem?
addNewCaseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
database = FirebaseDatabase.getInstance();
ref = database.getReference("NewCases");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot.getValue());
ArrayList<Object[]> myList = new ArrayList<>();
DefaultTableModel tableModel = (DefaultTableModel) table1.getModel();
tableModel.addColumn("ID");
tableModel.addColumn("Name");
tableModel.addColumn("Age");
tableModel.addColumn("City");
tableModel.addColumn("TimeStamp");
tableModel.addColumn("Disease");
tableModel.addColumn("Risk");
Object[] row = new Object[6];
tableModel.setNumRows(0);
myList.clear();
CasesList casesList = new CasesList();
for (DataSnapshot ds : dataSnapshot.getChildren()){
casesList.setID((Integer)ds.child("ID").getValue());
casesList.setName(ds.child("Name").getValue().toString());
casesList.setAge((Integer)ds.child("Age").getValue());
casesList.setCity(ds.child("City").getValue().toString());
casesList.setTimeStamp(ds.child("TimeStamp").getValue().toString());
casesList.setDisease(ds.child("Disease").getValue().toString());
casesList.setRisk(ds.child("Risk").getValue().toString());
// myList.add(ds.getKey());
row[0] = casesList.getID();
row[1] = casesList.getName();
row[2] = casesList.getAge();
row[3] = casesList.getCity();
row[4] = casesList.getTimeStamp();
row[5] = casesList.getDisease();
row[6] = casesList.getRisk();
myList.add(row);
System.out.println(myList);
tableModel.addRow(row);
}
table1.setModel(tableModel);
Thanks in advance!
Have you defined the table columns with lines like these?
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("ID");
tableModel.addColumn("Name");
tableModel.addColumn("Age");
Also, the method setModel should be called after the for:
for... {
//add row to tableModel
}
table1.setModel(tableModel);
EDIT:
Analyzing in more detail, I also verify that you have 7 fields but your array has only space for 6. In this line row [6] = casesList.getRisk (); throws an exception at runtime. Expand the size of your array to solve this.
Object[] row = new Object[7];
To display the column names it is convenient to add your table to a scroll panel.
JScrollPane scrollPane = new JScrollPane(table1);
frame.getContentPane().add(scrollPane);
This works for me:
ArrayList<Object[]> myList = new ArrayList<>();
DefaultTableModel tableModel = (DefaultTableModel) table1.getModel();
tableModel.addColumn("ID");
tableModel.addColumn("Name");
tableModel.addColumn("Age");
tableModel.addColumn("City");
tableModel.addColumn("TimeStamp");
tableModel.addColumn("Disease");
tableModel.addColumn("Risk");
Object[] row = new Object[7];
tableModel.setNumRows(0);
myList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
CasesList casesList = new CasesList();
casesList.setID((Integer) ds.child("ID").getValue());
casesList.setName(ds.child("Name").getValue().toString());
casesList.setAge((Integer) ds.child("Age").getValue());
casesList.setCity(ds.child("City").getValue().toString());
casesList.setTimeStamp(ds.child("TimeStamp").getValue().toString());
casesList.setDisease(ds.child("Disease").getValue().toString());
casesList.setRisk(ds.child("Risk").getValue().toString());
row[0] = casesList.getID();
row[1] = casesList.getName();
row[2] = casesList.getAge();
row[3] = casesList.getCity();
row[4] = casesList.getTimeStamp();
row[5] = casesList.getDisease();
row[6] = casesList.getRisk();
myList.add(row);
System.out.println(myList);
tableModel.addRow(row);
}
table1.setModel(tableModel);

Codename one a loop inside a TableModel

i'm trying to place a loop inside a TableModel to loop all the articles inside an arraylist to insert all the rows inside the table so i can add it to the form and show all the articles to the user
public class ListArticlesForm extends Form {
public ListArticlesForm(Form previous) {
setTitle("List all articles");
SpanLabel sp = new SpanLabel();
sp.setText(ServiceTask.getInstance().getAllArticles().toString());
ArrayList<Articles> articles = ServiceTask.getInstance().getAllArticles();
TableModel model = new DefaultTableModel(new String[]{"name", "description", "label", "quantity", "rating", "rate"},
new Object[][]{
{
// I WANT TO PLACE A FOR HERE (this is showing only the first row !
articles.get(0).getName(), articles.get(0).getDescription(), articles.get(0).getLabel(), articles.get(0).getQuantity(), articles.get(0).getRating(), add(createStarRankSlider())
},});
Table table = new Table(model);
add(table);
getToolbar().addMaterialCommandToLeftBar("", FontImage.MATERIAL_ARROW_BACK, e -> previous.showBack());
}
}
You can't create an array as a for loop inside the array. You need to do it a line sooner.
Object[][] rows = new Object[articles.size()][];
for(int iter = 0 ; iter < rows.length ; iter++) {
rows[iter] = new Object[] {
articles.get(iter).getName(), articles.get(0).getDescription(), articles.get(0).getLabel(), articles.get(0).getQuantity(), articles.get(0).getRating(), add(createStarRankSlider())
};
}
TableModel model = new DefaultTableModel(new String[]{"name", "description", "label", "quantity", "rating", "rate"}, rows);
now after i Run the project the table rows are displayed correctly except the rank stars
the show outside the table and inside the colonne a text appears:
the function for the star rank creation is :
private Slider createStarRankSlider(int id) {
Slider starRank = new Slider();
starRank.setEditable(true);
starRank.setMinValue(0);
starRank.setMaxValue(10);
int fontSize = Display.getInstance().convertToPixels(3);
Font fnt = Font.createTrueTypeFont("Handlee", "Handlee-Regular.ttf").
derive(fontSize, Font.STYLE_PLAIN);
Style s = new Style(0xffff33, 0, fnt, (byte) 0);
Image fullStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
s.setOpacity(100);
s.setFgColor(0);
Image emptyStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
initStarRankStyle(starRank.getSliderEmptySelectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderEmptyUnselectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderFullSelectedStyle(), fullStar);
initStarRankStyle(starRank.getSliderFullUnselectedStyle(), fullStar);
starRank.setPreferredSize(new Dimension(fullStar.getWidth() * 5, fullStar.getHeight()));
starRank.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
ServiceTask.getInstance().UpdateRank(id,starRank.getIncrements());
Dialog.show("Success","thank you for rating our product",new Command("OK"));
}
});
return starRank;
}

How to prevent selection of new added element on top of JTable?

I have a JTable that contains one row. I'am using multiple selection interval as a selection mode, besides a new row will be inserted on top of the table after 5 seconds from execution. My problem is: When I run the code and select the first row, after 5 seconds a new row is added (this is OK) but I got two selected rows which I do not want because I need to preserve the old selection,that means after adding the new row only the second row is selected. How to resolve this problem using multiple selection interval mode? Here is my code:
public static void main(String args[]) {
Object[][] rowData = { { "Hello", "World" }, { "By By", "World" } };
Object[] columnNames = { "A", "B" };
JFrame frame = new JFrame("Selecting JTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final DefaultTableModel model = new DefaultTableModel(rowData,columnNames);
JTable jtable = new JTable(model);
jtable.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane scrollPane1 = new JScrollPane(jtable);
frame.add(scrollPane1, BorderLayout.CENTER);
frame.setSize(640, 300);
frame.setVisible(true);
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
model.insertRow(0, rowData[0]);
}
You can call removeRowSelectionInterval method right after you insert the row.
Something like:
int newRowIndex = 0;
model.insertRow(newRowIndex, rowData[0]);
jtable.removeRowSelectionInterval(newRowIndex, newRowIndex);

How to add this array without adding columns again in the array

I want to remove this code and set to default values in the table
model2.setColumnIdentifiers(new
Object[]{"Order_ID","Description","Quantity","Amount","Order_Time","Cost"});
public void finduserday(){
ArrayList<dayday> list = userlistdaysearch (((JTextField)jDateChooser_searchdate.getDateEditor().getUiComponent()).getText());
DefaultTableModel model2 = new DefaultTableModel();
model2.setColumnIdentifiers(new Object[]{"Order_ID","Description","Quantity","Amount","Order_Time","Cost"});
Object [] row= new Object[6];
for(int i=0;i<list.size();i++){
row[0]=list.get(i).getOrder_ID();
row[1]=list.get(i).getDescription();
row[2]=list.get(i).getQuantity();
row[3]=list.get(i).getAmount();
row[4]=list.get(i).getOrder_Time();
row[5]=list.get(i).getCost();
model2.addRow(row);
}
jTable_dayday.setModel(model2);
}

Categories