计算JFrame中的复选框

时间:2015-04-28 19:26:01

标签: java swing

所以我在JPanel中有一个带有复选框的JFrame。我想计算所选复选框的数量,然后将该数量乘以一个数字,然后打印在屏幕上。有关如何做到这一点的任何建议?我想使用一个数组来存储复选框,然后搜索数组并查看哪些被选中。然后计算那些复选框的数量,这样它就可以用于我需要做的任何事情。我该如何修复我的代码?

import java.awt.BorderLayout;
import java.awt.Checkbox;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.*;


public class FYFGUI extends JFrame implements ActionListener
{
    Container cont = getContentPane();
    private GridLayout layout = new GridLayout(6,2);
    JPanel panel = new JPanel(layout);
    JPanel panel2 = new JPanel();
    JPanel panel3 = new JPanel();
    JCheckBox s1 = new JCheckBox("Mowing",false);
    JCheckBox s2 = new JCheckBox("Edging",false);
    JCheckBox s3 = new JCheckBox("Trimming",false);
    JCheckBox s4 = new JCheckBox("Blowing",false);
    JCheckBox s5 = new JCheckBox("Mulch",false);
    JCheckBox s6 = new JCheckBox("Hedges",false);
    JCheckBox s7 = new JCheckBox("Pruning Trees", false);
    JCheckBox s8 = new JCheckBox("Landscaping",false);
    JCheckBox s9 = new JCheckBox("Weeding", false);
    JCheckBox s10 = new JCheckBox("Leaf Removal", false);
    JLabel lbl = new JLabel("What services would you like?");
    JLabel Sqft = new JLabel("How many Sq. feet?");
    JTextField area = new JTextField(4);
    JButton exit =  new JButton("Exit");
    JButton calculate = new JButton("Calculate");

    public FYFGUI()
    {
        super("FrontYard Fairways");
        cont.setLayout(new BorderLayout());
        cont.add(panel, BorderLayout.WEST);
        cont.add(panel2, BorderLayout.SOUTH);
        cont.add(panel3, BorderLayout.EAST);
        panel.add(lbl);
        panel.add(s1);
        panel.add(s2);
        panel.add(s3);
        panel.add(s4);
        panel.add(s5);
        panel.add(s6);
        panel.add(s7);
        panel.add(s8);
        panel.add(s9);
        panel.add(s10);
        panel2.add(exit);
        panel2.add(calculate);
        panel3.add(Sqft);
        panel3.add(area);
        calculate.addActionListener(this);
        exit.addActionListener(this);

    }

    @Override
    public void actionPerformed(ActionEvent e) 
    {
        // TODO Auto-generated method stub
        Object source = e.getSource();
        if(source == exit)
        {
            System.exit(0);
        }
//This is where the question comes........
        // Get the number of check boxes selected and calculate prices. //SO,here is basically what I want to do....though this is wrong how do I fix this?
JCheckBox[] boxes = {s1,s2,s3,s4,s5,s6,s7,s8,s9,s10};
        int count;
        for(int i = 0; i < boxes.length; ++i){
            if(boxes[i].isSelected()){
                ++count;
            }

        // Get the sq ft and calculate prices
        // Use the above to calculate hours required
        // Return the total price of service + sqft + hours

    }
    public static void main(String[] args) 
    {
        // TODO Auto-generated method stub
         FYFGUI frame = new FYFGUI();
         frame.setVisible(true);
         frame.setDefaultCloseOperation(FYFGUI.EXIT_ON_CLOSE);
         frame.setSize(800,500);
         frame.setResizable(false);

    }


}

2 个答案:

答案 0 :(得分:0)

如果你从所有复选框中创建一个数组,你可以简单地遍历它们并计算许多被激活的数字。代码可能看起来像这样,但为了简单起见,使用了一组数组:

package jcheckboxtester;
/**
 * @author Miharu461
 */
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class JCheckBoxTester extends JFrame {
    public JCheckBoxTester() {
        setLayout(null);
        setLocationRelativeTo(null);
        setSize(200, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JCheckBox box = new JCheckBox();
        JLabel label = new JLabel("Number Selected: 0");
        label.setBounds(0, 40, 200, 25);

        box.setBounds(0, 0, 25, 25);
        getContentPane().add(box);
        box.addActionListener((ActionEvent e) -> {
            int count = 0;
            if(box.isSelected()) 
                count++;

            label.setText("Number Selected: " + count);
        });

        getContentPane().add(label);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            new JCheckBoxTester().setVisible(true);
        });
    }
}

答案 1 :(得分:0)

为每个JCheckBox添加一个ActionListener(您可以使用相同的ActionListener实例)。每次触发侦听器时,检查选择了哪个JChechBox(比较source的{​​{1}}或actionCommand

根据ActionEvent(已采取行动)的选定状态,从总数中添加或减去所需金额。

这样,您就可以实时运行记录。现在,如果你很聪明,有一些方法可以自动化,所以你所要做的就是提供一些文本和一个值(可能是一个模型),如自定义JCheckBox,它可以采取汽车的它适合你

请参阅How to Use Buttons, Check Boxes, and Radio ButtonsHow to Write an Action Listener

Action

现在,就个人而言,我更倾向于使用import java.awt.BorderLayout; import java.awt.Container; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.NumberFormat; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class FYFGUI extends JFrame implements ActionListener { Container cont = getContentPane(); private GridLayout layout = new GridLayout(6, 2); JPanel panel = new JPanel(layout); JPanel panel2 = new JPanel(); JPanel panel3 = new JPanel(); JCheckBox s1 = new JCheckBox("Mowing", false); JCheckBox s2 = new JCheckBox("Edging", false); JCheckBox s3 = new JCheckBox("Trimming", false); JCheckBox s4 = new JCheckBox("Blowing", false); JCheckBox s5 = new JCheckBox("Mulch", false); JCheckBox s6 = new JCheckBox("Hedges", false); JCheckBox s7 = new JCheckBox("Pruning Trees", false); JCheckBox s8 = new JCheckBox("Landscaping", false); JCheckBox s9 = new JCheckBox("Weeding", false); JCheckBox s10 = new JCheckBox("Leaf Removal", false); JLabel lbl = new JLabel("What services would you like?"); JLabel Sqft = new JLabel("How many Sq. feet?"); JTextField area = new JTextField(4); JButton exit = new JButton("Exit"); JLabel tallyLabel = new JLabel("$0.00"); private double tally; public FYFGUI() { super("FrontYard Fairways"); cont.setLayout(new BorderLayout()); cont.add(panel, BorderLayout.WEST); cont.add(panel2, BorderLayout.SOUTH); cont.add(panel3, BorderLayout.EAST); panel.add(lbl); panel.add(s1); panel.add(s2); panel.add(s3); panel.add(s4); panel.add(s5); panel.add(s6); panel.add(s7); panel.add(s8); panel.add(s9); panel.add(s10); panel2.add(exit); panel2.add(tallyLabel); panel3.add(Sqft); panel3.add(area); exit.addActionListener(this); s1.addActionListener(this); s2.addActionListener(this); s3.addActionListener(this); s4.addActionListener(this); s5.addActionListener(this); s6.addActionListener(this); s7.addActionListener(this); s8.addActionListener(this); s9.addActionListener(this); s10.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == exit) { System.exit(0); } else if (source instanceof JCheckBox) { JCheckBox cb = (JCheckBox) source; // I'd use a Map of some kind as a lookup if ("Mowing".equals(cb.getText())) { updateTally(cb, 10d); } else if ("Edging".equals(cb.getText())) { updateTally(cb, 15d); } else if ("Trimming".equals(cb.getText())) { updateTally(cb, 10d); } else if ("Blowing".equals(cb.getText())) { updateTally(cb, 10d); } else if ("Mulch".equals(cb.getText())) { updateTally(cb, 20d); } else if ("Hedges".equals(cb.getText())) { updateTally(cb, 15d); } else if ("Pruning Trees".equals(cb.getText())) { updateTally(cb, 25d); } else if ("Landscaping".equals(cb.getText())) { updateTally(cb, 35d); } else if ("Weeding".equals(cb.getText())) { updateTally(cb, 100d); } else if ("Leaf Removal".equals(cb.getText())) { updateTally(cb, 10d); } tallyLabel.setText(NumberFormat.getCurrencyInstance().format(tally)); } } protected void updateTally(JCheckBox cb, double amount) { // You could also add a loading based on area here... if (cb.isSelected()) { tally += amount; } else { tally -= amount; } } public static void main(String[] args) { // TODO Auto-generated method stub EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } FYFGUI frame = new FYFGUI(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } } API,这些是自行配置的工作单元。

Action

在这种情况下,public class JobAction extends AbstractAction { private JobModel model; private double amount; public JobAction(JobModel model, String text, double amount) { this.model = model; this.amount = amount; putValue(NAME, text); putValue(SELECTED_KEY, false); } @Override public void actionPerformed(ActionEvent e) { Object value = getValue(SELECTED_KEY); if (value instanceof Boolean) { boolean selected = (boolean) value; if (selected) { model.addJob(getValue(NAME).toString(), amount); } else { model.removeJob(getValue(NAME).toString(), amount); } } } } 只是简单地描述可能发生的行为,在这种情况下添加和删除作业

JobModel

(这让我很想制作一个public interface JobModel { public void addJob(String text, double amount); public void removeJob(String text, double amount); } 界面,其中包含文字和金额,但这就是我的意思

我更喜欢在可能的情况下使用接口,它使代码更灵活,并限制代码的其他区域,以便它们只能执行某些操作,但这就是我。

然后您可以使用类似......

之类的东西来配置按钮
Job

您还需要考虑在模型上提供某种观察者模式(侦听器),用于在模型更改时触发通知。

请查看How to Use Actions了解详情