每次我单击代码上的提交按钮时,为什么会不断为我提供小时字符串值?即使我的JComboBox中的项目具有每周的当前值?我该如何解决?

我的ComputeWindow的代码

public class ComputeWindow extends JFrame{

        private JLabel payRate,employeeID,payType,gWage;
        private JTextField  empRate,idTxt,gWageTxt;
        private JComboBox rateChooser;
        private JPanel panel;
        private JButton generate;

        public ComputeWindow(){

            super("Gross Wage");
            setSize(300, 150);
            setLocationRelativeTo(null);
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);


            String[] employeeType = {"Hourly","Bi Weekly","Weekly","Base"};

            employeeID = new JLabel("Employee ID: ");
            payRate  = new JLabel("Employee Rate: ");
            payType = new JLabel("Pay Type: ");
            gWage = new JLabel("Gross Wage");
            empRate = new JTextField(10);
            idTxt = new JTextField(10);
            gWageTxt = new JTextField(10);
            generate = new JButton("Compute!");
            rateChooser = new JComboBox(employeeType);
            panel = new JPanel(new GridLayout(5,1));

            panel.add(employeeID);
            panel.add(idTxt);
            panel.add(payRate);
            panel.add(empRate);
            panel.add(payType);
            panel.add(rateChooser);
            panel.add(gWage);
            panel.add(gWageTxt);
            panel.add(generate);
            add(panel, BorderLayout.CENTER);
            String Option =(String)rateChooser.getSelectedItem();

            GenerateHandler generateHandler = new GenerateHandler();
            generate.addActionListener(generateHandler);
            generateHandler.setOption(Option);
        }
    }


对于这里的处理程序

private class GenerateHandler implements ActionListener{

        String option;

        public void setOption(String option){
            this.option = option;
        }

        public void actionPerformed(ActionEvent e) {

            if(option =="Hourly"){
                JOptionPane.showMessageDialog(null,option);
            }else if(option == "Weekly"){
                JOptionPane.showMessageDialog(null,option);
            }
        }

    }

}


有什么建议么?我该如何解决?否则它将返回或显示我的JComboBox中正在使用的当前值?

最佳答案

您可以按以下方式更改代码:

GenerateHandler generateHandler = new GenerateHandler(rateChooser);




private class GenerateHandler implements ActionListener{
    JComboBox rateChooser;

    public GenerateHandler(JComboBox rateChooser){
        this.rateChooser = rateChooser;
    }

    public void actionPerformed(ActionEvent e) {
        String Option =(String)rateChooser.getSelectedItem();
        if("Hourly".equals(option)){
            JOptionPane.showMessageDialog(null,option);
        }else if("Weekly".equals(option)){
            JOptionPane.showMessageDialog(null,option);
        }
    }
}




上面的代码将解决您的解决方案,但这不是扩展JFrame(尤其是JSomething)并在构造函数中初始化所有内容的好方法。

10-06 05:33