如何为JCheckBox和JTextField使用单个ActionListener

时间:2016-08-07 02:20:17

标签: java jtextfield jcheckbox

我正在写一个eJuice计算器。它完全没有完成,你将在下面看到。我的问题是:我有4个JCheckBox和5个可编辑的JTextField;我可以使用一个ActionListener来执行程序执行的东西。或者我需要一个用于CheckBoxes的监听器和一个用于TextField的监听器吗?

这是一段粗略的代码草案。

    package ejuicecalculatorv2;

    import java.awt.*;
    import java.awt.event.*;

    import javax.swing.*;

       public class EJuiceCalculatorV2 extends JFrame {
    //Form Controls
    private JCheckBox isPGbasedNic_CB       = new JCheckBox("PG Based NIC");
    private JCheckBox isPGbasedFlavor_CB    = new JCheckBox("PG Based Flavor");

    private JCheckBox isVGbasedNic_CB       = new JCheckBox("VG Based NIC");
    private JCheckBox isVGbasedFlavor_CB    = new JCheckBox("VG Based Flavor");

    private JTextField batchSize_TF         = new JTextField(5);
    private JLabel batchSize_LB             = new JLabel("Batch Size:");

    private JTextField baseNicStrength_TF   = new JTextField(5);
    private JLabel baseNicStrength_LB       = new JLabel("Base NIC Strength:");

    private JTextField targetNicStrength_TF = new JTextField(5);
    private JLabel targetNicStrength_LB     = new JLabel("Target NIC Strength:");

    private JTextField totalNic_TF          = new JTextField(5);
    private JLabel totalNic_LB              = new JLabel("Total NIC:");

    private JTextField flavorStrength_TF    = new JTextField(5);
    private JLabel flavorStrength_LB        = new JLabel("Flavoring Strength:");

    private JTextField totalFlavor_TF       = new JTextField(5);
    private JLabel totalFlavor_LB           = new JLabel("Total Flavoring:");

    private JTextField vgRatio_TF           = new JTextField(5);
    private JLabel vgRatio_LB               = new JLabel("VG Ratio:");

    private JTextField pgRatio_TF           = new JTextField(5);
    private JLabel pgRatio_LB               = new JLabel("PG Ratio:");

    private JTextField additionalVG_TF      = new JTextField(5);
    private JLabel additionalVG_LB          = new JLabel("Additional VG:");

    private JTextField additionalPG_TF      = new JTextField(5);
    private JLabel additionalPG_LB          = new JLabel("Additional PG:");

    private JTextField totalVG_TF           = new JTextField(5);
    private JLabel totalVG_LB               = new JLabel("Total VG:");

    private JTextField totalPG_TF           = new JTextField(5);
    private JLabel totalPG_LB               = new JLabel("Total PG:");

    private JTextField vgBasedIng_TF        = new JTextField(5);
    private JLabel vgBasedIng_LB            = new JLabel("Total VG Ingredients:");

    private JTextField pgBasedIng_TF        = new JTextField(5);
    private JLabel pgBasedIng_LB            = new JLabel("Total PG Ingredients:");


    //Variables
    private boolean _PGnicFlag;
    private boolean _VGnicFlag;

    private boolean _PGflavorFlag;
    private boolean _VGflavorFlag;

    private double baseNic;
    private double targetNic;
    private double totalNic;

    private double flavorStrength;
    private double totalFlavor;

    private double batchSize;

    private double totalPG;
    private double totalVG;

    private double additionalVG;
    private double additionalPG;

    private double pgBasedIng;
    private double vgBasedIng;

    private double pgRatio;
    private double vgRatio;


    public EJuiceCalculatorV2() {
        super("EJuice Calculator V2");
        setLayout(new FlowLayout());

        //Add CheckBoxes
        add(isPGbasedNic_CB);
        add(isPGbasedFlavor_CB);
        add(isVGbasedNic_CB);
        add(isVGbasedFlavor_CB);

        //Add TextFields and Labels
        add(batchSize_LB);
        add(batchSize_TF);

        add(vgRatio_LB);
        add(vgRatio_TF);

        add(pgRatio_LB);
        add(pgRatio_TF);

        add(baseNicStrength_LB);
        add(baseNicStrength_TF);

        add(targetNicStrength_LB);
        add(targetNicStrength_TF);

        add(flavorStrength_LB);
        add(flavorStrength_TF);

        //Add ActionListeners
        ActionListener actionListener = new ActionHandler();
        isPGbasedNic_CB.addActionListener(actionListener);
        isPGbasedFlavor_CB.addActionListener(actionListener);
        isVGbasedNic_CB.addActionListener(actionListener);
        isVGbasedFlavor_CB.addActionListener(actionListener);
        batchSize_TF.addActionListener(actionListener);
        vgRatio_TF.addActionListener(actionListener);
        pgRatio_TF.addActionListener(actionListener);
        baseNicStrength_TF.addActionListener(actionListener);
        targetNicStrength_TF.addActionListener(actionListener);
        flavorStrength_TF.addActionListener(actionListener);     


        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    class ActionHandler implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent event){

            //if event.getSource() == JCheckBox then execute the following code. 


            if(checkBox.isSelected()){
                if(checkBox == isPGbasedNic_CB){
                    _PGnicFlag = true;
                    _VGnicFlag = false;
                    checkBox = isVGbasedNic_CB;
                    checkBox.setSelected(false);                   
                }
                else if(checkBox == isVGbasedNic_CB){
                    _VGnicFlag = true;
                    _PGnicFlag = false;
                    checkBox = isPGbasedNic_CB;
                    checkBox.setSelected(false);
                }
                else if(checkBox == isVGbasedFlavor_CB){
                    _VGflavorFlag = true;
                    _PGflavorFlag = false;
                    checkBox = isPGbasedFlavor_CB;
                    checkBox.setSelected(false);
                }
                else if(checkBox == isPGbasedFlavor_CB){
                    _PGflavorFlag = true;
                    _VGflavorFlag = false;
                    checkBox = isVGbasedFlavor_CB;
                    checkBox.setSelected(false);
                }
            }
            else{
                if(checkBox == isPGbasedNic_CB){
                    _PGnicFlag = false;
                    _VGnicFlag = true;
                }
                else if(checkBox == isVGbasedNic_CB){
                    _VGnicFlag = false;
                    _PGnicFlag = true;
                }
                else if(checkBox == isVGbasedFlavor_CB){
                    _VGflavorFlag = false;
                    _PGflavorFlag = true;
                }
                else if(checkBox == isPGbasedFlavor_CB){
                    _PGflavorFlag = false;
                    _VGflavorFlag = true;
                }
            }
    }
}

public static void main(String[] args) {
        // TODO code application logic here
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run (){
                new EJuiceCalculatorV2().setVisible(true);
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

  

我的问题是:我有4个JCheckBox和5个可编辑的JTextField;我可以使用一个ActionListener来执行程序执行的东西。或者我需要一个用于CheckBoxes的监听器和一个用于TextField的监听器吗?

您有一堆控件组件,但没有一个可以从GUI启动操作。而所有这些,JCheckBoxes和JTextField都可以获得输入,并且您似乎缺少一个最终组件,例如JButton。我会将这个组件添加到你的GUi中,我会单独添加一个ActionListener。然后在按下时,它会检查复选框和文本组件的状态,然后根据它们的状态,给用户提供适当的响应。

还有一些,如果不是大多数或所有的JTextField,我会改为JComboBoxes或JSpinners,以限制用户可以输入的输入到允许的内容,因为你不希望用户输入“是” “进入”批量大小“JTextField。

例如:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;
import javax.swing.JSpinner.DefaultEditor;

@SuppressWarnings("serial")
public class JuiceTwo extends JPanel {
    private static final String[] FLAVORS = {"Flavor 1", "Flavor 2", "Flavor 3", "Flavor 4"};
    private static final Integer[] ALLOWABLE_BATCH_SIZES = {1, 2, 5, 10, 15, 20};
    private static final String[] ALLOWABLE_VG_RATIOS = {"1/4", "1/3", "1/2", "1/1", "2/1", "3/1", "4/1", "8/1", "16/1"};
    private List<JCheckBox> flavorBoxes = new ArrayList<>();
    private JComboBox<Integer> batchSizeCombo;
    private JSpinner vgRatioSpinner;

    public JuiceTwo() {

        // JPanel to hold the flavor JCheckBoxes
        JPanel flavorPanel = new JPanel(new GridLayout(0, 1)); // hold them in vertical grid
        flavorPanel.setBorder(BorderFactory.createTitledBorder("Flavors"));
        for (String flavor : FLAVORS) {
            JCheckBox flavorBox = new JCheckBox(flavor);
            flavorBox.setActionCommand(flavor);
            flavorPanel.add(flavorBox);
            flavorBoxes.add(flavorBox);
        }

        batchSizeCombo = new JComboBox<>(ALLOWABLE_BATCH_SIZES);

        SpinnerListModel vgRatioModel = new SpinnerListModel(ALLOWABLE_VG_RATIOS);
        vgRatioSpinner = new JSpinner(vgRatioModel);
        JComponent editor = vgRatioSpinner.getEditor();
        if (editor instanceof DefaultEditor) {
            ((DefaultEditor)editor).getTextField().setColumns(4);
        }


        JButton getSelectionButton = new JButton("Get Selection");
        getSelectionButton.setMnemonic(KeyEvent.VK_S);
        getSelectionButton.addActionListener(new SelectionActionListener());

        add(flavorPanel);
        add(Box.createHorizontalStrut(20));
        add(new JLabel("Batch Size:"));
        add(batchSizeCombo);
        add(Box.createHorizontalStrut(20));
        add(new JLabel("VG Ratio:"));
        add(vgRatioSpinner);
        add(Box.createHorizontalStrut(20));
        add(getSelectionButton);
    }

    private class SelectionActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            for (JCheckBox flavorBox : flavorBoxes) {
                System.out.printf("%s selected: %b%n", flavorBox.getActionCommand(), flavorBox.isSelected());
            }

            System.out.println("Batch Size: " + batchSizeCombo.getSelectedItem());            
            System.out.println("VG Ration:  " + vgRatioSpinner.getValue());

            System.out.println();
        }
    }

    private static void createAndShowGui() {
        JuiceTwo mainPanel = new JuiceTwo();

        JFrame frame = new JFrame("JuiceTwo");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}