0

I am almost at the end of my project and have some problems solving it. I m a chef who wants his own application what is relevant for his own bussines

My form is called Recipes and have Qty unitprice, % used.

So lets say, you have 1kg apples for 5 euro. At the end of cleaning you just have 800 grams of apples. So i have paid 20 percent more.

example

  • Item is always 100%,
  • Qty 5,
  • Unitprice 5,
  • Used% 100% total = 25

Qty 5, Unitprice 5, Used% 70%, Total= 32.5 ( must increase with 30 percent)

At the end I would have to calculate the Foodcost.

So "Total Cost / Selling price * 100"

I m stuck with this code. Please can someone help me further with my project. I just met java 1 week ago. So i don t have time to learn it properly. working 12h per day.

This is in the header in eclipse

public class Recipe extends javax.swing.JFrame {
    double Qty;
    double UnitPrice;
    double Used;
    double total;
    double subTotal;
    private static Connection connection = null;
    private JPanel contentPane;
    Connection conn=null;

JButton btnNewButtonAdd = new JButton("Add");
// btnNewButtonAdd.setIcon(new // ??      
btnNewButtonAdd.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        int i=100;
        Qty=Double.parseDouble(textFieldQty.getText());
        UnitPrice=Double.parseDouble(txtUnitPrice.getText());
        Used=Double.parseDouble(textFieldUsed.getText());
        //Used=subTotal/100;
        subTotal=Qty*UnitPrice;
        //total=subTotal*Used;
        //Used=subTotal/100;
        total=subTotal*(Used/100);//(100+Used);

        String TotalRow= String.format("%.2f", total);
        txtTotal.setText(TotalRow);

        DefaultTableModel model=(DefaultTableModel) table.getModel();
        model.addRow(new Object[]{textFieldQty.getText(), BoxCategory.getSelectedItem(), 
            BoxDescription.getSelectedItem(), textFieldItemID.getText(), 
            txtUnitPrice.getText(), BoxUnit.getSelectedItem(), textFieldUsed.getText(), 
            txtTotal.getText()});
    }
}

enter image description here

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Erol
  • 71
  • 1
  • 8
  • 1
    `"I m a chef who wants his own application what is relevant for his own bussines."` -- If you're serious, then you really, really want to spend the money and hire a professional as there's no way that you will be able to create a business-ready type of application with your current experience, even with our help. This is a recipe for disaster. – Hovercraft Full Of Eels Jul 04 '16 at 19:02
  • 1
    `"So i don t have time to learn it properly"` you have a lot of irrelevant information like @HovercraftFullOfEels said, you **need** to learn it properly, or hire a professional who has done that for you and knows what (s)he's doing! But if you insist in doing it yourself, well... good luck with it. And for better help sooner please post a [mcve] – Frakcool Jul 04 '16 at 19:12
  • I Totaly agree. It doesn t have to be that professional. Just for internal use. I already finished the rest. Cat. Product.VAT ..; ... all database sqlite. – Erol Jul 04 '16 at 19:30
  • 1
    You're making some basic mistakes, including totally ignoring all Swing threading rules and mixing model with view code. Regardless if this is for professional or home use, you should try to implement your functionality yourself first, and then if that doesn't work, post your [mcve] as @Frakcool also suggests. – Hovercraft Full Of Eels Jul 04 '16 at 19:32
  • i dont know where to start learning it properly. If i see you guys how you give tips to people. Where do you learn all of that. How you start ? For now i just copy and paste the code, trying to understand what it means and integrate in my application. All went well, untill this calculating methode. – Erol Jul 04 '16 at 19:36
  • Do like most of us did: get a decent book and/or decent tutorials and start working at learning the rudiments. Then work towards the advanced stuff. This is like learning math -- you have to learn the basics first before trying complex stuff. And we do love to help, but your question should show your attempt to solve first. Else you're asking others to code for you, and that's not appropriate on this site. – Hovercraft Full Of Eels Jul 04 '16 at 19:40
  • no it s not that i want ready codes. No way. I might aswell hire a professional to do that for me. I was trying for 5 hours how i could calculate the increase of price. I can calculate decrease :).Total/100*used. But Used must be x, since i don't give the parameters for that.I want to learn it myself. But needed a little push of you guys. I really admire your knowledge. It s my day off today, and wanted to get over with this math thing. I ll figure it out, for sure. Thanks for the help. If you guys ever come to belgium, swing by for a coffee. – Erol Jul 04 '16 at 19:55
  • 1
    Thank you for your invitation, I think you should start with a console application to do the maths first, then try to understand how methods and parameters work and then move that knowledge to your application, and also don't mix view with model code, or it will be a mess. If you want to learn it properly and develop the system yourself, then it's fine, but you first need to learn the basics of Java, OOP and algorithms. Here's the [Oracle's Tutorial](https://docs.oracle.com/javase/tutorial/) – Frakcool Jul 04 '16 at 20:55
  • To get your sums, you'd use your TableModel, here a DefaultTableModel, find the column of interest, iterate through each row using a for loop (calling `getRowCount()` on the model will tell you how many times to loop), extract the information from the column of interest using the model's `getValueAt(...)` method, and then add that value to your total. It's nothing more than adding items in a for loop. – Hovercraft Full Of Eels Jul 04 '16 at 21:05
  • thanks for your reply. 1 sorry about my english ! – Erol Jul 04 '16 at 21:13
  • 2. I dont understand what you mean by view en model code. I got everyting working. When i push "add button" everything is correct. Because the values are filled automaticly. I just have to input the % of use of the product. i mean i can calculate the sum (total) with 100% use of a product. What i want is when i "input" myself lets say 70% in the txtfield, it s giving me 70% of the total. Instead of increasing the total with 30%. I am to far with this project to give up now. – Erol Jul 04 '16 at 21:18
  • i dont know if you see a picture of the frame "recipes". That one i made myself, it s not that i use a ready project without doing anything. In 1 week i build the whole project with the associating popups, tables, frames etc. etc.Trying to understand the codes and implement in my project whit copy and paste. Not like you guys, who can write a whole project in wordpad. My Java knowledge = 0. I'll figure for sure this one out, but somtimes i need help from pro's like you. thanks – Erol Jul 04 '16 at 21:25
  • I told you what you need to do in my comment above. Give it a go. – Hovercraft Full Of Eels Jul 04 '16 at 21:26
  • it s in there DefaultTableModel model=(DefaultTableModel) table.getModel(); model.addRow(new Object[]{textFieldQty.getText(),BoxCategory.getSelectedItem(),BoxDescription.getSelectedItem(),textFieldItemID.getText(),txtUnitPrice.getText(),BoxUnit.getSelectedItem(),textFieldUsed.getText(),txtTotal.getText()}); } – Erol Jul 04 '16 at 21:29
  • ????? that has nothing to do with what I said. – Hovercraft Full Of Eels Jul 04 '16 at 21:48

1 Answers1

4

As shown here, here and here, you can calculate derived values in your implementation of getValueAt(). In the example below,

  • COLUMN_PERCENTis the ratio of each row's salary to the sum() of salaries in the table.

  • The percent column also gets an instance of PercentFormatter to format the derived value as a percentage.

image

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultRowSorter;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;

/**
 * @see https://stackoverflow.com/posts/38192710/edit
 * @see https://stackoverflow.com/a/37913520/230513
 * @see https://stackoverflow.com/a/37892395/230513
 */
public class JTablePercentTotalExample {

    public static void main(String[] args) {
        EventQueue.invokeLater(JTablePercentTotalExample::display);
    }

    public static void display() {
        JFrame f = new JFrame("JTable Sorting Example");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        List<Employee> listEmployees = createListEmployees();
        TableModel model = new EmployeeTableModel(listEmployees);
        JTable table = new JTable(model) {
            @Override
            public Dimension getPreferredScrollableViewportSize() {
                return new Dimension(500, getRowCount() * getRowHeight());
            }
        };
        table.getColumnModel().getColumn(3).setCellRenderer(new CurrencyFormatter());
        table.getColumnModel().getColumn(4).setCellRenderer(new PercentFormatter());
        table.setAutoCreateRowSorter(true);
        DefaultRowSorter sorter = (DefaultRowSorter) table.getRowSorter();
        sorter.setSortable(4, false);
        f.add(new JScrollPane(table), BorderLayout.CENTER);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private static List<Employee> createListEmployees() {
        List<Employee> listEmployees = new ArrayList<>();
        listEmployees.add(new Employee("Peter", "Manager", 40000));
        listEmployees.add(new Employee("Paul", "Programmer", 25000));
        listEmployees.add(new Employee("Mary", "Designer", 25000));
        listEmployees.add(new Employee("Donald", "Leader", 30000));
        listEmployees.add(new Employee("Tom", "Designer", 28000));
        listEmployees.add(new Employee("Samantha", "Analyst", 50000));
        listEmployees.add(new Employee("Jerome", "Programmer", 32000));
        listEmployees.add(new Employee("Jonathon", "Developer", 29000));
        listEmployees.add(new Employee("Kevin", "Programmer", 23000));
        listEmployees.add(new Employee("Anthony", "Programmer", 23000));
        listEmployees.add(new Employee("John", "Designer", 33000));
        listEmployees.add(new Employee("David", "Developer", 28000));
        listEmployees.add(new Employee("Harry", "Designer", 31000));
        listEmployees.add(new Employee("Charles", "Programmer", 26000));
        listEmployees.add(new Employee("Joseph", "Manager", 40000));
        return listEmployees;
    }

    private static class EmployeeTableModel extends AbstractTableModel {

        private static final int COLUMN_NUM = 0;
        private static final int COLUMN_NAME = 1;
        private static final int COLUMN_JOB = 2;
        private static final int COLUMN_SALARY = 3;
        private static final int COLUMN_PERCENT = 4;
        private final String[] columnNames = {"No", "Name", "Job", "Salary", "Percent"};
        private final List<Employee> listEmployees;

        public EmployeeTableModel(List<Employee> listEmployees) {
            this.listEmployees = listEmployees;
            int indexCount = 1;
            for (Employee employee : listEmployees) {
                employee.setIndex(indexCount++);
            }
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public int getRowCount() {
            return listEmployees.size();
        }

        @Override
        public String getColumnName(int columnIndex) {
            return columnNames[columnIndex];
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return getValueAt(0, columnIndex).getClass();
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Employee employee = listEmployees.get(rowIndex);
            switch (columnIndex) {
                case COLUMN_NUM:
                    return employee.getIndex();
                case COLUMN_NAME:
                    return employee.getName();
                case COLUMN_JOB:
                    return employee.getJob();
                case COLUMN_SALARY:
                    return employee.getSalary();
                case COLUMN_PERCENT:
                    int salary = (int) getValueAt(rowIndex, COLUMN_SALARY);
                    return Double.valueOf(salary / (double) sum());
                default:
                    throw new IllegalArgumentException("Invalid column index");
            }
        }

        private int sum() {
            int sum = 0;
            for (int r = 0; r < getRowCount(); r++) {
                sum += (int) getValueAt(r, COLUMN_SALARY);
            }
            return sum;
        }
    }

    private static class Employee {

        private int index;
        private String name;
        private String job;
        private int salary;

        public Employee(String name, String job, int salary) {
            this.name = name;
            this.job = job;
            this.salary = salary;
        }

        public int getIndex() {
            return index;
        }

        public void setIndex(int index) {
            this.index = index;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getJob() {
            return job;
        }

        public void setJob(String job) {
            this.job = job;
        }

        public int getSalary() {
            return salary;
        }

        public void setSalary(int age) {
            this.salary = age;
        }
    }

    private static class CurrencyFormatter extends DefaultTableCellRenderer {

        private final NumberFormat nf = NumberFormat.getCurrencyInstance();

      @Override
        public Component getTableCellRendererComponent(JTable jTable, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
            Component c = super.getTableCellRendererComponent(jTable, value,
                isSelected, hasFocus, row, column);
            if (c instanceof JLabel && value instanceof Number) {
                JLabel label = (JLabel) c;
                label.setHorizontalAlignment(JLabel.RIGHT);
                Number num = (Number) value;
                String text = nf.format(num);
                label.setText(text);
            }
            return c;
        }
    }

    private static class PercentFormatter extends DefaultTableCellRenderer {

        private NumberFormat nf = NumberFormat.getPercentInstance();

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
            Component c = super.getTableCellRendererComponent(table, value,
                isSelected, hasFocus, row, column);
            if (c instanceof JLabel && value instanceof Number) {
                JLabel label = (JLabel) c;
                label.setHorizontalAlignment(JLabel.RIGHT);
                Number num = (Number) value;
                String text = nf.format(num);
                label.setText(text);
            }
             return c;
        }
    }
}
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • You're welcome, but I don't understand: Give up what? – trashgod Jul 04 '16 at 22:41
  • Give up my project, and read a book about java before i move along. Just found "thinking in java 4th edition". – Erol Jul 04 '16 at 22:50
  • 1
    See also *Thinking in Patterns* by the same author. – trashgod Jul 05 '16 at 01:09
  • Also, if you're in doubt with the book's examples or your own study you can always come back and ask a specific question :) (Don't forget to post a [mcve] when you do so) and we'll be glad to help, you have a good attitude... Happy programming! :D – Frakcool Jul 05 '16 at 05:01