简体   繁体   English

如何将动态变量添加到JTextField?

[英]How can I add a dynamic variable to a JTextField?

this is my output generated. 这是我生成的输出。 As you can see the JTextField isn't being modified according to the totalValue 如您所见,JTextField并未根据totalValue进行修改

在此处输入图片说明

I'm a beginner at Java and I need help on this matter; 我是Java的初学者,因此需要帮助。 I'm doing a POS system using a JTable. 我正在使用JTable做POS系统。

I'm having difficulty getting the correct total when adding the cost (column) together, but I do not have any errors. 将成本(列)加在一起时,我很难获得正确的总数,但是我没有任何错误。

My main problem at the moment is: how can I add a dynamic variable a jtextfield. 目前,我的主要问题是:如何在jtextfield中添加动态变量。 As in, when I edit in the quantity column a digit, how can I get the new total displayed in the jtextfield. 就像这样,当我在数量列中编辑一个数字时,如何获得显示在jtextfield中的新总数。 My jtextfield (totalField) is never being updated. 我的jtextfield(totalField)从未更新过。

Here is a piece of my code; 这是我的一段代码;

   public class EditableTable extends JPanel {

   private JTextField filterField = new JTextField();
   private JButton filterButton = new JButton("Filter");
   public JTextField totalField = new JTextField(10);


   private JScrollPane scroll;
   public JPanel panel = new JPanel(new BorderLayout());
   public JPanel filterPanel = new JPanel(new BorderLayout());  
   public JPanel receiptPanel = new JPanel(new BorderLayout());
   public JPanel transactionPanel = new JPanel();
   JPanel cashPanel = new JPanel();
   JPanel totalPanel = new JPanel();

   private TableModelListener tableModelListener;


   ProductsTableModel model = new ProductsTableModel();
   final JTable table = new JTable(model);

   Double total;
   double totalValue; 
   double payment;

   public JLabel cashLab = new JLabel("Cash");
   public JTextField cashInput = new JTextField(10);

   public JLabel totalLab = new JLabel("Total");

   public JLabel changeLab = new JLabel("");

   public JButton confirmButton = new JButton("Confirm");
   public double change;


public EditableTable(){


    table.getModel().addTableModelListener(new CheckBoxModelListener());
    // final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    final TableRowSorter<TableModel> rowSorter = new TableRowSorter<>(table.getModel());
    table.setRowSorter(rowSorter);


    table.setPreferredScrollableViewportSize(new Dimension(500, 700));
    table.setFillsViewportHeight(true);
    table.setCellSelectionEnabled(true);
    KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0);
    InputMap map = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    map.put(tab, "selectNextRowCell");


    scroll = new JScrollPane(table);

    filterPanel.add(new JLabel("Specify a word to match: "), BorderLayout.WEST);
    filterPanel.add(filterField, BorderLayout.CENTER);






    filterField.getDocument().addDocumentListener(new DocumentListener(){

        @Override
        public void insertUpdate(DocumentEvent e){
            String text = filterField.getText();

            if(text.trim().length() == 0){
                rowSorter.setRowFilter(null);
            }else{
                rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
            }
        }

        @Override
        public void removeUpdate(DocumentEvent e){
            String text = filterField.getText();

            if(text.trim().length() == 0){
                rowSorter.setRowFilter(null);
            }else{
                rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
            }
        }

        @Override
        public void changedUpdate(DocumentEvent e){
            throw new UnsupportedOperationException("Not supported yet.");
        }
    });

    panel.add(scroll, BorderLayout.CENTER);
    panel.add(filterPanel, BorderLayout.SOUTH);

    cashPanel.add(cashLab);
    cashPanel.add(cashInput);
    receiptPanel.add(cashPanel, BorderLayout.CENTER); 

    cashInput.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            payment = Double.parseDouble(cashInput.getText());
            change = payment - totalValue;
            changeLab.setText("" + change);
            System.out.println("Change" + change);
        }
    });


    receiptPanel.add(new JLabel("Change " + change), BorderLayout.SOUTH);
    totalPanel.add(totalLab);
    totalPanel.add(totalField);
    receiptPanel.add(totalPanel, BorderLayout.NORTH);

   table.getModel().addTableModelListener(new TableModelListener(){
       @Override
       public void tableChanged(TableModelEvent ev){
           if(ev.getColumn() == 3|| ev.getColumn() == 4){
               calculateTotal();
            }
        }
    });


}

//Simple method to calculate the total and set it to the JTextField
public void calculateTotal(){
    double total = 0d;
    int numOfRows = table.getRowCount();
    for(int i = 0; i < numOfRows; i++){
        Object cost = table.getValueAt(i,5);
        if(cost instanceof Number){
            total += ((Number)cost).doubleValue();
        }
    }
    System.out.println("Total" + total);

    totalField.setText(NumberFormat.getNumberInstance().format(total));
    System.out.println("I DID IT");
}


}

Any help is really really appreciated 真的很感谢任何帮助

This is my latest update! 这是我的最新更新! I think I might have a problem in my receiptPanel , where the totalField is concerned. 我想我可能在我的receiptPanel,其中totalField来讲有问题。

To many comments I post an answer so that you see how TableModel and listener are used. 对于许多评论,我发布了一个答案,以便您了解如何使用TableModel和listener。

    table = new JTable();
    //I override the getValueAt see @mKorbel comments so that columns 5
    //return the value of 3*4 (you should not to calculate and set this from   
    //the listener, setting the value will recall the listener again)
    table.setModel(new DefaultTableModel() {

        @Override
        public Object getValueAt(int row, int column) {
            if (column == 5) {
                Object price = super.getValueAt(row, 3);
                Object quantity = super.getValueAt(row, 4);
                if (price instanceof Number && quantity instanceof Number) {
                    return ((Number) price).doubleValue() * ((Number) quantity).intValue();

                }
                return 0d;
            }
            return super.getValueAt(row, column);
        }

    });

    //I use the listener to understand if column 3 or 4 is changed
    //to recalculate my totale. I have also added code to detect inseration/delation of rows.
    table.getModel().addTableModelListener(new TableModelListener() {

        @Override
        public void tableChanged(TableModelEvent ev) {
            switch(ev.getType()){
            case TableModelEvent.UPDATE:
                if (ev.getColumn() == 3 || ev.getColumn() == 4) {
                    calculateTotale();
                }
                return;
            case TableModelEvent.INSERT:
            case TableModelEvent.DELETE:
                calculateTotale();
                break;
            }
        }
    });
}

//Simple metod to calculate the total and set it to the JTextField.
public void calculateTotale() {
    double tot = 0d;
    int numOfRows = table.getRowCount();
    for (int i = 0; i < numOfRows; i++) {
        Object cost = table.getValueAt(i, 5);
        if (cost instanceof Number) {
            tot += ((Number) cost).doubleValue();
        }
    }
    totalField.setText(NumberFormat.getNumberInstance().format(tot));
    System.out.println("I DID IT!!");
}

Note this is not copy and past code, its an brief code example to make you understand of JTable can work. 注意这不是复制和过去的代码,它是一个简短的代码示例,以使您了解JTable可以正常工作。

If you see in the console I DID IT!! 如果您在控制台中看到了, 我会DIT! and the JTextField does not change, the totalField is not the totalField you belive it is!... I guess could be; 而且JTextField不变,totalField不是您相信的totalField! that you are doing new JTextField() , adding it to layout and then you are doing new JTextField() again (this would change its reference). 您正在执行new JTextField() ,将其添加到布局中,然后再次执行new JTextField() (这将更改其引用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM