在jtable中用%,total计算

时间:2016-07-04 18:59:41

标签: java swing jtable percentage defaulttablemodel

我差不多已经完成了我的项目并且解决了一些问题。我是一名厨师,他希望自己的应用程序与他自己的商务相关

我的表单名为Recipes,有数量单价,%使用。

让我们说,你有1公斤苹果5欧元。在清洁结束时,你只需要800克苹果。所以我付了20%以上。

例如

  • 项目始终为100%,
  • 数量5,
  • Unitprice 5,
  • 已使用%100%总计= 25

数量5,单价5,使用%70%,总数= 32.5(必须增加30%)

最后,我必须计算食物成本。

所以"总成本/销售价格* 100"

我坚持使用这段代码。请有人帮助我进一步完善我的项目。 我刚刚在1周前见过java。所以我没有时间正确地学习它。每天工作12小时。

这是在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()});
    }
}

onAuthStateChanged()

1 个答案:

答案 0 :(得分:3)

hereherehere所示,您可以在getValueAt()的实施中计算派生值。在下面的示例中,

  • COLUMN_PERCENT是表格中每行薪水与工资sum()的比率。

  • 百分比列还会获得PercentFormatter的实例,以便将派生值格式化为百分比。

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;
        }
    }
}