在jtable中计算%,total [英] calculating in jtable with %, total

查看:116
本文介绍了在jtable中计算%,total的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我差不多完成了我的项目,并且解决了一些问题。我是主厨谁想要他自己的应用程序与他自己的商务相关



我的表格被称为食谱,有数量单价,%使用。



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



示例




  • 项目总是100 %,

  • 数量5,

  • Unitprice 5,

  • 已使用%100%总计= 25



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



最后我必须计算食品成本。



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



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



这是在eclipse的标题中

 公共类食谱扩展javax.swing.JFrame {
double qty;
double UnitPrice;
double使用;
总计双倍;
double subTotal;
private static Connection connection = null;
私人JPanel contentPane;
连接conn = null;

  JButton btnNewButtonAdd = new JButton(Add); 
// btnNewButtonAdd.setIcon(new // ??
btnNewButtonAdd.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
int i = 100;
数量= 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.getSelectedIte m(),textFieldUsed.getText(),
txtTotal.getText()});
}
}

  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
* /
公共类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);
列表<员工> 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(新员工(Peter,经理,40000));
listEmployees.add(新员工(Paul,程序员,25000));
listEmployees.add(新员工(Mary,Designer,25000));
listEmployees.add(新员工(Donald,Leader,30000));
listEmployees.add(新员工(Tom,Designer,28000));
listEmployees.add(新员工(Samantha,分析师,50000));
listEmployees.add(新员工(Jerome,程序员,32000));
listEmployees.add(新员工(Jonathon,开发人员,29000));
listEmployees.add(新员工(Kevin,程序员,23000));
listEmployees.add(新员工(Anthony,程序员,23000));
listEmployees.add(新员工(John,Designer,33000));
listEmployees.add(new Employee(David,Developer,28000));
listEmployees.add(新员工(Harry,Designer,31000));
listEmployees.add(新员工(Charles,程序员,26000));
listEmployees.add(新员工(Joseph,经理,40000));
return listEmployees;
}

私有静态类EmployeeTableModel扩展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};
私人最终名单< Employee>类ListEmployees;

public EmployeeTableModel(List< Employee> listEmployees){
this.listEmployees = listEmployees;
int indexCount = 1;
for(员工雇员: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());
默认值:
抛出新的IllegalArgumentException(无效的列索引);
}
}

private int sum(){
int sum = 0;
for(int r = 0; r< getRowCount(); r ++){
sum + =(int)getValueAt(r,COLUMN_SALARY);
}
返还金额;
}
}

私有静态类雇员{

private int index;
private String name;
private String job;
私人工资;

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

私有静态类CurrencyFormatter扩展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.setHorizo​​ntalAlignment(JLabel.RIGHT);
数字num =(数字)值;
String text = nf.format(num);
label.setText(text);
}
返回c;
}
}

私有静态类PercentFormatter扩展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.setHorizo​​ntalAlignment(JLabel.RIGHT);
数字num =(数字)值;
String text = nf.format(num);
label.setText(text);
}
返回c;
}
}
}


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

解决方案

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.

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

这篇关于在jtable中计算%,total的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆