java - 有没有办法将从所有组合框中选择的值添加到 1 个文本字段中?

标签 java swing add jtextfield jcombobox

有没有办法将选择的组合框的值添加到 1 个文本字段中? 即 noOfBks。

例如,我有两个组合框,分别是 quantitiesCB1 和 ebquantitiesCB1。 quantitiesCB1 用于硬拷贝,ebquantitiescb1 用于电子书

所有这些代码都运行良好。 因此,在程序页面的末尾,我希望有一个文本字段说明书籍总数。

我可以添加到第一个 ActionListener 中吗

totalNoOfBks += currenQuantity;

对于 actionlistener 数量 CB1 和 ebquantitiesCB2?

在 ebquantitiesCB2 内部会有与上面相同的代码,但有一个额外的

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

下面是我的代码,运行良好。

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

最佳答案

  • 将 Integer 或 Double 值直接添加到 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();
            }
        });
    }
}
  • 然后你避免从 JComboBox 解析 Int

  • 将 JFormattedTextField 与数字格式化程序一起使用,原因与针对 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() {
    }
}

关于java - 有没有办法将从所有组合框中选择的值添加到 1 个文本字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16353950/

相关文章:

java - 鼠标事件bug

java - 在另一个类中定义一个按钮

java - JPA:一对多关系中阻抗不匹配的问题

java - 运行后JFrame显示不正确

java - 防止 TextArea 背景图像向下滚动时拉伸(stretch)

json - 在Powershell中将方括号转换为json时添加方括号

java - 'fair' 和 'unfair' 锁的内部存储差异

java - 为什么 Eclipse 会警告 Java "unused variables"但 javac 不会?

JavaScript:将输入元素添加到当前 div

assembly - 具有 2 个或 3 个操作数的 ARM ADD 之间的区别?