Pergunta

I am working on a program that needs to determine which JCheckBox was selected. I am using three different button groups, two of which have overlapping text. I need to be able to determine which triggered the event so I can add the appropriate charge (COSTPERROOM vs COSTPERCAR) to the total(costOfHome). What I cant figure out is how to differentiate the checkbox source if the text is the same. I was thinking of trying to change the text on one button group to strings like "one" "two" etc, but that introduces a bigger problem with how I have created the checkboxes in the first place. Any ideas would be appreciated, thanks in advance!

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JMyNewHome extends JFrame implements ItemListener {

    // class private variables
    private int costOfHome = 0;

    // class arrays
    private String[] homeNamesArray = {"Aspen", "Brittany", "Colonial", "Dartmour"};
    private int[] homeCostArray = {100000, 120000, 180000, 250000};

    // class constants 
    private final int MAXROOMS = 3;
    private final int MAXCARS = 4;
    private final int COSTPERROOM = 10500;
    private final int COSTPERCAR = 7775;

    JLabel costLabel = new JLabel();

    // constructor
    public JMyNewHome ()
    {
        super("My New Home");
        setSize(450,150);
        setLayout(new FlowLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Font labelFont = new Font("Time New Roman", Font.BOLD, 24);

        setJLabelString(costLabel, costOfHome);
        costLabel.setFont(labelFont);
        add(costLabel);

        JCheckBox[] homesCheckBoxes = new JCheckBox[homeNamesArray.length];
        ButtonGroup homeSelection = new ButtonGroup();
        for (int i = 0; i < homeNamesArray.length; i++)
        {
            homesCheckBoxes[i] = new JCheckBox(homeNamesArray[i], false);
            homeSelection.add(homesCheckBoxes[i]);
            homesCheckBoxes[i].addItemListener(this);
                add(homesCheckBoxes[i]);
        }

        JLabel roomLabel = new JLabel("Number of Rooms in Home");
        add(roomLabel);

        ButtonGroup roomSelection = new ButtonGroup();
        JCheckBox[] roomCheckBoxes = new JCheckBox[MAXROOMS];
        for (int i = 0; i < MAXROOMS; i++)
        {
            String intToString = Integer.toString(i + 2);
            roomCheckBoxes[i] = new JCheckBox(intToString);
            roomSelection.add(roomCheckBoxes[i]);
            roomCheckBoxes[i].addItemListener(this);
            add(roomCheckBoxes[i]);
        }

        JLabel carLabel = new JLabel("Size of Garage (number of cars)");
        add(carLabel);

        ButtonGroup carSelection = new ButtonGroup();
        JCheckBox[] carCheckBoxes = new JCheckBox[MAXCARS];
        for (int i = 0; i < MAXCARS; i++)
        {
            String intToString = Integer.toString(i);
            carCheckBoxes[i] = new JCheckBox(intToString);
            carSelection.add(carCheckBoxes[i]);
            carCheckBoxes[i].addItemListener(this);
            add(carCheckBoxes[i]);
        }

        setVisible(true);

    }

    private void setJLabelString(JLabel label, int cost)
    {
        String costOfHomeString = Integer.toString(cost);
        label.setText("Cost of Configured Home:  $ " + costOfHomeString + ".00");
        invalidate();
        validate();
        repaint();
    }

    public void itemStateChanged(ItemEvent e) {
        JCheckBox source = (JCheckBox) e.getItem();
        String sourceText = source.getText();
        //JLabel testLabel = new JLabel(sourceText);
        //add(testLabel);
        //invalidate();
        //validate();
        //repaint();
        for (int i = 0; i < homeNamesArray.length; i++)
        {
            if (sourceText == homeNamesArray[i])
            {
                setJLabelString(costLabel, costOfHome + homeCostArray[i]);
            }
        }
    }
}
Foi útil?

Solução

I would

  • Use JRadioButtons for this rather than JCheckBoxes since I think it is GUI standard to have a set of JRadioButtons that only allow one selection rather than a set of JCheckBoxes.
  • Although you may have "overlapping text" you can set the button's actionCommand to anything you want to. So one set of buttons could have actionCommands that are "room count 2", "room count 3", ...
  • But even better, the ButtonGroup can tell you which toggle button (either check box or radio button) has been selected since if you call getSelection() on it, it will get you the ButtonModel of the selected button (or null if none have been selected), and then you can get the actionCommand from the model via its getActionCommand() method. Just first check that the model selected isn't null.
  • Learn to use the layout managers as they can make your job much easier.

For instance, if you had two ButtonGroups:

ButtonGroup fooBtnGroup = new ButtonGroup();
ButtonGroup barBtnGroup = new ButtonGroup();

If you add a bunch of JRadioButtons to these ButtonGroups, you can then check which buttons were selected for which group like so (the following code is in a JButton's ActionListener):

ButtonModel fooModel = fooBtnGroup.getSelection();
String fooSelection = fooModel == null ? "No foo selected" : fooModel.getActionCommand();

ButtonModel barModel = barBtnGroup.getSelection();
String barSelection = barModel == null ? "No bar selected" : barModel.getActionCommand();

System.out.println("Foo selected: " + fooSelection);
System.out.println("Bar selected: " + barSelection);

Assuming of course that you've set the actionCommand for your buttons.

Outras dicas

Checkboxes have item listeners like any other swing component. I would decouple them, and simply add listeners to each {

checkBox.addActionListener(actionListener); 

}

http://www.java2s.com/Code/Java/Swing-JFC/CheckBoxItemListener.htm

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top