how to add column value in jtable - java

I am very new to java and i am developing an inventory management system(Its my first project ).I want to add the column values sententiously when a new row is created. please any one help me how to do so..
i want to sum the line total and show it as the arrow is located..here is my code for table data.
int quantity, price;
Product p = new Product();
String[] result = new String[8];
String data[] = new String[7];
int i = 0;
result=p.getInfo(this.addItemField.getText());
for (String s : result) {
data[i] = s;
i += 1;
}
data[0] = "1";
quantity = Integer.parseInt(data[0]);
price = Integer.parseInt(data[5]);
int tPrice = price*quantity;
data[6] = Integer.toString(tPrice); //this is the field which i want to add for all row.
table.addRow(data);
this.addItemField.grabFocus();
addItemField.setText("");

Add a TableModelListener to the TableModel. When a TableModel event is generated you can loop through all the rows in the model and calculate a new total and then update your label.

Related

How can I display dishName according to the searched price after sorting in jtable java?

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String dishName = "";
ArrayList<Integer> st = new ArrayList<Integer>();
int rowCount = table.getRowCount();
int fPrice;
int rowIndex = 0;
int colIndex = 4;
boolean emptyFlag = false;
do {
String price = (String) table.getValueAt(rowIndex, 4);
fPrice = Integer.parseInt(price);
if (price != null && price.length() != 0) {
st.add(fPrice);
rowIndex++;
} else {
emptyFlag = true;
}
} while (rowIndex < rowCount && !emptyFlag);
Collections.sort(st);
int key = Integer.parseInt(searchPrice.getText());
int low = 0;
int high = st.size() - 1;
int searchResult = MenuInfo.priceSearch(st, low, high, key);
if(searchResult==-1){
JOptionPane.showMessageDialog(this, "Could not find the dish of your price!");}
else{
dishName = (String) table.getValueAt(searchResult,1);
JOptionPane.showMessageDialog(this, "The price you have searched can afford " + dishName);
}
} //ends here
The above code is the code I have tried in my program. But it can display the corresponding dishName only if the data are sorted previously. If I add dish of lower price, then it displays the dishname of first row. Please do appreciate my request :)
Here is the image of my jtable
I wrote some code that may help. It looks like you're using Swing, so I used Swing. My code will find the corresponding value, but not sort the rows. I'll share it, but if you really need it to be sorted, let me know.
public static void main(String[] args) {
String[] headers = {"Name","Number"};
String[][] rowData = {{"foo","500"},{"bar","700"}};
JFrame frame = new JFrame();
JPanel panel = new JPanel();
//frame.add(panel);
//A table is controlled by its model, so we need a variable to access the model
DefaultTableModel model = new DefaultTableModel(rowData,headers);
JTable table = new JTable(model);
JScrollPane scroll = new JScrollPane(table);
//To allow sorting, we us a TableRowSorter object
TableRowSorter<TableModel> sorter = new TableRowSorter<>(table.getModel());
table.setRowSorter(sorter);
//We have to set the 2nd column to be sortable
ArrayList<RowSorter.SortKey> sortKeys = new ArrayList<>();
//sorting on 2nd column (with index of 1), which is Number
sortKeys.add(new RowSorter.SortKey(1, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
sorter.sort();
//add new value, then sort
Object[] newRow = {"baz", "600"};
model.addRow(newRow);
sorter.sort();
panel.add(scroll);
frame.add(panel);
frame.setSize(800, 400);
//show is deprecrated.. I shouldn't be using it!
frame.show();
int minIndex = findMin(table, 1);
//use the row index of the min item in column 1 to get the corresponding value in column 0
System.out.println("Minimum String: " + table.getValueAt(minIndex, 0));
}
//find min value in the column with index tableColumnIndex and return the row index of that item
public static int findMin(JTable table, int tableColumnIndex) {
int minIndex = 0;
String min = table.getValueAt(0, tableColumnIndex).toString();
for (int i = 1; i < table.getRowCount(); i++) {
if (table.getValueAt(i, tableColumnIndex).toString().compareTo(min) < 0) {
min = table.getValueAt(i, tableColumnIndex).toString();
minIndex = i;
}
}
return minIndex;
}

MPAndroidChart LineChart Showing just on LineData

I am having problem creating LineChart it's just showing the last Line when I need to show all Lines can you please help? here's the code:
Collections.addAll(labels,` column);
dataSets = new ArrayList<ILineDataSet>();
for (monthlysales company : companieslist) {
entries.clear();
for (int j = 0; j < listofcompanies.Total.size(); j++) {
entries.add(new Entry(Float.parseFloat(listofcompanies.Total.get(j)), j));
}
setComp1 = new LineDataSet(entries, company.StoreName);
setComp1.setAxisDependency(YAxis.AxisDependency.LEFT);
setComp1.setColor(Color.BLUE);
dataSets.add(setComp1);
}
LineData data = new LineData(column,dataSets);
linechart.setData(data);
linechart.setDescription("Sales");
linechart.animateXY(5000,5000);
linechart.setPinchZoom(true);
linechart.setDoubleTapToZoomEnabled(true);
linechart.setDragDecelerationEnabled(true);
linechart.notifyDataSetChanged();
linechart.invalidate();
}
Thank you
This actually makes sense. You are adding data to the entries list, and then add it to the DataSet correctly. The problem is, you are clearing the entries list every time after you add it. you should use a separate list for each dataset.
replace the line:
entries.clear();
with
List<Entry> entries = new ArrayList<>();
it's now solved by creating a Function and call it as below :
**dataSets.add(createLineChart(company,company.StoreName,company.Total));**
data = new LineData(column,dataSets);
linechart.setData(data);
linechart.invalidate();
linechart.setDescription("Sales");
and this is the function:
private LineDataSet createLineChart(monthlysales company,String storeName,List<String> listofcompanies){
// LineData data=new LineData();
ArrayList<Entry> entries= new ArrayList<Entry>();
for (int j = 0; j < listofcompanies.size(); j++) {
entries.add(new Entry(Float.parseFloat(listofcompanies.get(j)),j));
linechart.notifyDataSetChanged();
}
Random rd = new Random();
setComp1 = new LineDataSet(entries,storeName);
setComp1.setColor(Color.argb(255,rd.nextInt(256),rd.nextInt(256),rd.nextInt(256)));
// LineData data =new LineData(labels,dataset);
return setComp1;
}
it seems that the LineDataSet was used the last time it was called displaying just one line.

How do i calculate the mean from data read in a file

I'm trying obtain all the names from one file and all the attendances from another then calculate the average attendance. I know the att bit in the calculation is completely wrong but I could not work it out.
{
ArrayList<Match> ourList = new ArrayList(teams);
ArrayList<Match> teamsAttendance = new ArrayList<Match>();
for (Match att : ourList)
{
if (att != null && att.getTeamName().equals(team.getName()))
{
teamsAttendance.add(att);
}
}
double attendance = 0; //start attendance as 0
for (int i = 0; i < att.length; i++)
{
attendance += att[i];
}
return attendance / att.length;
}
I am guessing that the Match class will have a team name and attendance(an array list). Just like getting the team name, there should be a get to get the attendance array list .Assuming this you can try the below approach:
{
ArrayList<Match> ourList = new ArrayList(teams);
ArrayList<Match> teamsAttendance = new ArrayList<Match>();
//to store the attendance mean for each team
ArrayList<double> teamAttendanceMean = new ArrayList<double>();
//to store the attendance values of team
ArrayList<double> tempAttendance= new ArrayList<double>();
//declare outside
double attendance = 0;
for (Match att : ourList)
{
if (att != null && att.getTeamName().equals(team.getName()))
{
teamsAttendance.add(att);
}
attendance = 0;// assign 0
tempAttendance = att.getTeamAttendance();
for (int i = 0; i < tempAttendance.size(); i++)
{
attendance += tempAttendance [i];
}
//storing the mean value
teamAttendanceMean.add(attendance/tempAttendance.size());
}
}
Let me know if any of my assumptions are wrong and also post information on the Match class if so.

Copy selected data from a jtable in frame1 to another table in frame2

I have a JTable2 in frame1 and JTable1 in frame2. I want to copy and send selected data from table2 to table1. how do i do it ?
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
String sql = "select * from table1 where Bill_No like '"+jTextField2.getText()+"'";
try{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
JFrame NewJFrame2 = new NewJFrame2();
NewJFrame2.setVisible(true);
int i=0;
while(rs.next()) {
Object bno = rs.getString("Bill No");
Object bamount = rs.getString("Bill Amount");
Object btds = rs.getString("TDS");
Object btax = rs.getString("Tax");
Object bpayable = rs.getString("Payable");
jTable1.getModel().setValueAt(bno,i, 0 );
jTable1.getModel().setValueAt(bamount, i, 1);
jTable1.getModel().setValueAt(btds, i, 2);
jTable1.getModel().setValueAt(btax, i, 3);
jTable1.getModel().setValueAt(bpayable, i, 4);
System.out.println(i);
i++;
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Start by having a look at How to Use Tables.
If you want to "copy" the selected data, then you will need to know what rows are selected, see JTable#getSelectedRows.
You're making life difficult for yourself using DbUtils as you've lost the ability to just transfer the objects from one model to another.
The basic idea would be to copy the values from the original table into a new TableModel and pass that to the second window, something like
TableModel original = table.getModel();
DefaultTableModel model = new DefaultTableModel(table.getSelectedRowCount(), original.getColumnCount());
for (int col = 0; col < original.getColumnCount(); col++) {
model.addColumn(original.getColumnName(col));
}
int[] selectedRows = table.getSelectedRows();
for (int targetRow = 0; targetRow < selectedRows.length; targetRow++) {
int row = selectedRows[targetRow];
int modelRow = table.convertRowIndexToModel(row);
for (int col = 0; col < original.getColumnCount(); col++) {
model.setValueAt(original.getValueAt(modelRow, col), targetRow, col);
}
}
for example. Now you just need to pass model to the second window and apply it to the JTable contained within

Add and remove from one Table To another

I am facing a problem with the functionality of removing a row(s) form one table view to another table view currently I have two button one add row form the bottom table to the above and the next add from the above the the botton. the button that add from bottom to top called add and the button that add from top to bottom called remove in both once the row is copied across it get deleted from the original table.
The problem I am facing is:
when I add all the row from the bottom table to the top table
if I sort Column 0 in top table ,then try to remove the row from the top table to the bottom table
the row do not get deleted from the top table although it is added in the bottom table.
Could you please Help me solve this problem or advice me on a better way?
Here is my current code:
Remove button:
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
spTable.removeAll();
x = resultTable.getSelectedRows();
String[] cName= {"Column 0","Column 1","Column 2","Column 3","Column 4","Column 5","Column 6","Column 7","Column 8"};
if(rTable.getRowCount()==0){
model=addToNew(resultTable,x,cName,model);
}else{ model =addToExisting(resultTable,rTable, x, model);
}
deletRows(x,resultTable);
rTable.setModel(model);
JScrollPane spS = new JScrollPane(rTable);
rTable.getColumnModel().getColumn(1).setPreferredWidth(290);
spS.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
spS.setPreferredSize(new Dimension(800,200));
rTable.setFillsViewportHeight(true);
spTable.add(spS);
validate();
}});
Add button:
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.removeAll();
x = rTable.getSelectedRows();
String[] cName= {"Column 0","Column 1","Column 2","Column 3","Column 4","Column 5","Column 6","Column 7","Column 8"};
if(resultTable.getRowCount()==0){
model=addToNew(rTable,x,cName,model);
}else{ model =addToExisting(rTable,resultTable, x, model);
}
deletRows(x,rTable);
resultTable.setModel(model);
JScrollPane spS = new JScrollPane(resultTable);
resultTable.getColumnModel().getColumn(1).setPreferredWidth(290);
spS.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
spS.setPreferredSize(new Dimension(800,170));
panel.add(spS);
resultTable.setFillsViewportHeight(true);
validate();}});
deletRow
public void deletRows(int[] selected, JTable t){
for(int i = selected.length-1;i>=0;i--){
int y = selected[i];
((DefaultTableModel)t.getModel()).removeRow(y);
validate();}}
/**
* this method allow to add rows to an New table
*/
public DefaultTableModel addToNew(JTable t1,int[] selected,String[] ColName, DefaultTableModel m){
String[] name = ColName;
int col = name.length;
m =new DefaultTableModel();
for(int i= 0;i<col;i++){
m.addColumn(name[i]);
}
Object[] data= new Object[col];
for(int i =0; i<selected.length;i++){
int y= selected[i];
for (int z =0; z<col;z++){
if( t1.getValueAt(y, z)!= null){
String value = t1.getValueAt(y, z).toString();
data[z]= value;
}else{
data[z]=null;
}
}
m.addRow(data);
}
return m;
}
/* this method allow to add rows to an Existing table */
public DefaultTableModel addToExisting(JTable t1,JTable t2, int[] selected, DefaultTableModel m){
m =(DefaultTableModel)t2.getModel();
Object[] data= new Object[m.getColumnCount()];
for(int i =0; i<selected.length;i++){
int y= selected[i];
for (int z =0; z<m.getColumnCount();z++){
if( t1.getValueAt(y, z)!= null){
String value = t1.getValueAt(y, z).toString();
data[z]= value;
}else{
data[z]=null;
}
}
m.addRow(data);
}
return m;
}

Categories