Search code examples
javaswingadditionjtextfieldjcombobox

Is there a way to add the value chosen from all combobox into 1 textfield?


is there a way for me to add the value of combobox choosen into 1 textfield? i.e noOfBks.

For example, I have two comboboxes, which is quantitiesCB1 and ebquantitiesCB1. quantitiesCB1 is for hardcopies, ebquantitiescb1 is for ebook

Every of this code is working fine. So at the end of the program page, I would like to have a text field stating the total number of books.

Am I able to add into the first ActionListener to do

totalNoOfBks += currenQuantity;

for both actionlistener quantitiesCB1 and ebquantitiesCB2?

Inside ebquantitiesCB2 would have the same above code but an additional

totalNoOfBks += currenQuantity;
NoOfBks.setText(totalNoOfBks);

Below is my coding which is working fine.

public class CataloguePanel extends JPanel {
        JPanel catalogue = new JPanel(new GridBagLayout());

        //batman cost and fields
        String value1 = "15";
        String ebvalue1 = "12";
        final JTextField result1 = new JTextField();
        final JTextField ebresult1 = new JTextField();
        //total no. of books field
        final JTextField noOfBks = new JTextField(); 
        final int totalBks;

        public CataloguePanel(){
        JPanel catalogue = new JPanel(new GridBagLayout());

        //combobox for batman textfield
        JComboBox quantitiesCB1 = new JComboBox(quantities1);
        quantitiesCB1.setPreferredSize(new Dimension(125,20));
        quantitiesCB1.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent e){
                        JComboBox combo = (JComboBox)e.getSource();
                        String currentQuantity = (String)combo.getSelectedItem();
                        int finalvalue1 = Integer.valueOf(value2);
                        int finalvalue2 = Integer.valueOf(currentQuantity);

                        String resultText = String.valueOf(finalvalue1*finalvalue2);
                        result2.setText("$" + resultText);
                    }
                }            
        );           
        JComboBox ebquantitiesCB1 = new JComboBox(quantities1);
        ebquantitiesCB1.setPreferredSize(new Dimension(125,20));
        ebquantitiesCB1.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent e){
                        JComboBox combo = (JComboBox)e.getSource();
                        String currentQuantity = (String)combo.getSelectedItem();
                        int finalvalue1 = Integer.valueOf(ebvalue2);
                        int finalvalue2 = Integer.valueOf(currentQuantity);

                        String resultText = String.valueOf(finalvalue1*finalvalue2);
                        ebresult2.setText("$" + resultText);
                    }
                }            
        );
    }
}

Solution

    • add Integer or Double value directly to the ComboBoxModel

    enter image description here

    import java.awt.GridLayout;
    import java.util.Vector;
    import javax.swing.Icon;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    
    public class ComboBoxIntegerModel {
    
        private JComboBox comboBoxDouble;
        private JComboBox comboBoxInteger;
        private JComboBox comboBoxBoolean;
        private JComboBox comboBoxIcon;
        private Vector<Double> doubleVector = new Vector<Double>();
        private Vector<Integer> integerVector = new Vector<Integer>();
        private Vector<Boolean> booleanVector = new Vector<Boolean>();
        private Vector<Icon> iconVector = new Vector<Icon>();
        private Icon icon1 = ((UIManager.getIcon("OptionPane.errorIcon")));
        private Icon icon2 = (UIManager.getIcon("OptionPane.informationIcon"));
        private Icon icon3 = (UIManager.getIcon("OptionPane.warningIcon"));
        private Icon icon4 = (UIManager.getIcon("OptionPane.questionIcon"));
    
        public ComboBoxIntegerModel() {
            doubleVector.addElement(1.001);
            doubleVector.addElement(10.00);
            doubleVector.addElement(0.95);
            doubleVector.addElement(4.2);
            comboBoxDouble = new JComboBox(doubleVector);
            integerVector.addElement(1);
            integerVector.addElement(2);
            integerVector.addElement(3);
            integerVector.addElement(4);
            comboBoxInteger = new JComboBox(integerVector);
            booleanVector.add(Boolean.TRUE);
            booleanVector.add(Boolean.FALSE);
            comboBoxBoolean = new JComboBox(booleanVector);
            iconVector.addElement(icon1);
            iconVector.addElement(icon2);
            iconVector.addElement(icon3);
            iconVector.addElement(icon4);
            comboBoxIcon = new JComboBox(iconVector);
            JFrame frame = new JFrame("");
            frame.setLayout(new GridLayout(2,2,5,5));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(comboBoxDouble);
            frame.add(comboBoxInteger);
            frame.add(comboBoxBoolean);
            frame.add(comboBoxIcon);
            frame.setLocationRelativeTo(null);
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    ComboBoxIntegerModel cBModel = new ComboBoxIntegerModel();
                }
            });
        }
    }
    
    • then you avoiding to parseInt from JComboBox

    • use JFormattedTextField with number formatter, for the same reason as mentioned for JComboBox

    enter image description here

    import java.awt.*;
    import java.awt.font.TextAttribute;
    import java.math.*;
    import java.text.*;
    import java.util.Map;
    import javax.swing.*;
    import javax.swing.JFormattedTextField.*;
    import javax.swing.event.*;
    import javax.swing.text.InternationalFormatter;
    
    public class DocumentListenerAdapter {
    
        public static void main(String args[]) {
            JFrame frame = new JFrame("AbstractTextField Test");
            final Map attributes = (new Font("Serif", Font.BOLD, 16)).getAttributes();
            attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);        
            final JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01));
            textField1.setFormatterFactory(new AbstractFormatterFactory() {
                @Override
                public AbstractFormatter getFormatter(JFormattedTextField tf) {
                    NumberFormat format = DecimalFormat.getInstance();
                    format.setMinimumFractionDigits(2);
                    format.setMaximumFractionDigits(2);
                    format.setRoundingMode(RoundingMode.HALF_UP);
                    InternationalFormatter formatter = new InternationalFormatter(format);
                    formatter.setAllowsInvalid(false);
                    formatter.setMinimum(0.0);
                    formatter.setMaximum(1000.00);
                    return formatter;
                }
            });
            final JFormattedTextField textField2 = new JFormattedTextField(new Float(10.01));
            textField2.setFormatterFactory(new AbstractFormatterFactory() {
                @Override
                public AbstractFormatter getFormatter(JFormattedTextField tf) {
                    NumberFormat format = DecimalFormat.getInstance();
                    format.setMinimumFractionDigits(2);
                    format.setMaximumFractionDigits(2);
                    format.setRoundingMode(RoundingMode.HALF_UP);
                    InternationalFormatter formatter = new InternationalFormatter(format);
                    formatter.setAllowsInvalid(false);
                    //formatter.setMinimum(0.0);
                    //formatter.setMaximum(1000.00);
                    return formatter;
                }
            });
            textField2.getDocument().addDocumentListener(new DocumentListener() {
                @Override
                public void changedUpdate(DocumentEvent documentEvent) {
                    printIt(documentEvent);
                }
    
                @Override
                public void insertUpdate(DocumentEvent documentEvent) {
                    printIt(documentEvent);
                }
    
                @Override
                public void removeUpdate(DocumentEvent documentEvent) {
                    printIt(documentEvent);
                }
    
                private void printIt(DocumentEvent documentEvent) {
                    DocumentEvent.EventType type = documentEvent.getType();
                    double t1a1 = (((Number) textField2.getValue()).doubleValue());
                    if (t1a1 > 1000) {
                        Runnable doRun = new Runnable() {
                            @Override
                            public void run() {
                                textField2.setFont(new Font(attributes));
                                textField2.setForeground(Color.red);
                            }
                        };
                        SwingUtilities.invokeLater(doRun);
                    } else {
                        Runnable doRun = new Runnable() {
                            @Override
                            public void run() {
                                textField2.setFont(new Font("Serif", Font.BOLD, 16));
                                textField2.setForeground(Color.black);
                            }
                        };
                        SwingUtilities.invokeLater(doRun);
                    }
                }
            });
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(textField1, BorderLayout.NORTH);
            frame.add(textField2, BorderLayout.SOUTH);
            frame.setVisible(true);
            frame.pack();
        }
    
        private DocumentListenerAdapter() {
        }
    }