当 JCheckBox 文本相同时,如何确定哪个 JCheckBox 引发了事件

发布于 2024-12-06 11:27:14 字数 3543 浏览 1 评论 0原文

我正在开发一个需要确定选择了哪个 JCheckBox 的程序。我使用三个不同的按钮组,其中两个具有重叠的文本。我需要能够确定哪个触发了事件,以便我可以将适当的费用(COSTPERROOM 与 COSTPERCAR)添加到总计(costOfHome)中。我不知道的是,如果文本相同,如何区分复选框源。我正在考虑尝试将一个按钮组上的文本更改为“一”“二”等字符串,但这给我如何创建复选框带来了一个更大的问题。任何想法将不胜感激,提前致谢!

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜司空 2024-12-13 11:27:14

我会

  • 使用 JRadioButtons 而不是 JCheckBoxes,因为我认为拥有一组只允许一个选择而不是一组 JCheckBoxes 的 JRadioButtons 是 GUI 标准。
  • 尽管您可能有“重叠文本”,但您可以将按钮的 actionCommand 设置为您想要的任何内容。因此,一组按钮的操作命令可以是“房间数 2”、“房间数 3”……
  • 但更好的是,ButtonGroup 可以告诉您选择了哪个切换按钮(复选框或单选按钮),因为如果你对其调用 getSelection() ,它将获取所选按钮的 ButtonModel(如果没有选择,则返回 null),然后你可以通过其 从模型中获取 actionCommand getActionCommand() 方法。首先检查所选模型是否不为空。
  • 学习使用布局管理器,因为它们可以使您的工作变得更加轻松。

例如,如果您有两个 ButtonGroup:

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

如果您向这些 ButtonGroup 添加一堆 JRadioButton,则可以像这样检查为哪个组选择了哪些按钮(以下代码位于 JButton 的 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);

当然假设您“已经为您的按钮设置了actionCommand。

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.

姐不稀罕 2024-12-13 11:27:14

与任何其他 Swing 组件一样,复选框也具有项目侦听器。我会将它们解耦,然后简单地为每个添加监听器
{

checkBox.addActionListener(actionListener); 

}

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文