通过 JButton 和 JComboBox 的元素执行某些操作

发布于 2024-11-17 13:28:04 字数 2655 浏览 3 评论 0原文

我需要找到将 JComboBoxJButton 连接的解决方案。意味着对 JComboBox 中选定的项目执行“按钮”操作。

我为

公共类 DeleteButtonController 实现了 ActionListener{ 创建了一个控制器 私人 OceanGui 视图; 私有 OceanInterface 模型; 私人 JComboBox 列表;

public DeleteButtonController(OceanGui view, Ocean model, JComboBox list) {
    this.view = view;
    this.model = model;
    this.list = list;
}
@Override
public void actionPerformed(ActionEvent arg0) {
    OceanObject obj = (OceanObject) list.getSelectedItem();
    int index = model.getIndexOfClosestOceanObject(obj.getPosition()[0], obj.getPosition()[1]);
    model.delOceanObject(index);
}

在我的GUI

中我这样做了:

    this.buttonArray[1] = new JButton(this.buttonCaptions[1]);
    this.buttonArray[1].addActionListener(new DeleteButtonController(this, model, objects));
    panel.add(this.buttonArray[1]);

并且我因此获得了例外:

线程“AWT-EventQueue-0”中出现异常 java.lang.ClassCastException: java.lang.String 无法转换为 infpp.oceanlife.model.OceanObject 位于 infpp.oceanlife.controller.DeleteButtonController.actionPerformed(DeleteButtonController.java:25) 在 javax.swing.AbstractButton.fireActionPerformed(未知 来源)于 javax.swing.AbstractButton$Handler.actionPerformed(未知 来源)于 javax.swing.DefaultButtonModel.fireActionPerformed(未知 来源)于 javax.swing.DefaultButtonModel.setPressed(未知 来源)于 javax.swing.plaf.basic.BasicButtonListener.mouseReleased(未知 来源)于 java.awt.Component.processMouseEvent(未知 来源)于 javax.swing.JComponent.processMouseEvent(未知 来源)于 java.awt.Component.processEvent(未知 来源)于 java.awt.Container.processEvent(未知 来源)于 java.awt.Component.dispatchEventImpl(未知 来源)于 java.awt.Container.dispatchEventImpl(未知 来源)于 java.awt.Component.dispatchEvent(未知 来源)于 java.awt.LightweightDispatcher.retargetMouseEvent(未知 来源)于 java.awt.LightweightDispatcher.processMouseEvent(未知 来源)于 java.awt.LightweightDispatcher.dispatchEvent(未知 来源)于 java.awt.Container.dispatchEventImpl(未知 来源)于 java.awt.Window.dispatchEventImpl(未知 来源)于 java.awt.Component.dispatchEvent(未知 来源)于 java.awt.EventQueue.dispatchEvent(未知 来源)于 java.awt.EventDispatchThread.pumpOneEventForFilters(未知 来源)于 java.awt.EventDispatchThread.pumpEventsForFilter(未知 来源)于 java.awt.EventDispatchThread.pumpEventsForHierarchy(未知 来源)于 java.awt.EventDispatchThread.pumpEvents(未知 来源)于 java.awt.EventDispatchThread.pumpEvents(未知 来源)于 java.awt.EventDispatchThread.run(未知 来源)

第 25 行显示

    OceanObject obj = (OceanObject) list.getSelectedItem();

I need to find a resolution for connecting a JComboBox with a JButton. Means do "Button" with selected Item in JComboBox.

I created a Controller for that

public class DeleteButtonController implements ActionListener{
private OceanGui view;
private OceanInterface model;
private JComboBox list;

public DeleteButtonController(OceanGui view, Ocean model, JComboBox list) {
    this.view = view;
    this.model = model;
    this.list = list;
}
@Override
public void actionPerformed(ActionEvent arg0) {
    OceanObject obj = (OceanObject) list.getSelectedItem();
    int index = model.getIndexOfClosestOceanObject(obj.getPosition()[0], obj.getPosition()[1]);
    model.delOceanObject(index);
}

}

In my GUI I did that:

    this.buttonArray[1] = new JButton(this.buttonCaptions[1]);
    this.buttonArray[1].addActionListener(new DeleteButtonController(this, model, objects));
    panel.add(this.buttonArray[1]);

And I earn a exception for that:

Exception in thread "AWT-EventQueue-0"
java.lang.ClassCastException:
java.lang.String cannot be cast to
infpp.oceanlife.model.OceanObject at
infpp.oceanlife.controller.DeleteButtonController.actionPerformed(DeleteButtonController.java:25)
at
javax.swing.AbstractButton.fireActionPerformed(Unknown
Source) at
javax.swing.AbstractButton$Handler.actionPerformed(Unknown
Source) at
javax.swing.DefaultButtonModel.fireActionPerformed(Unknown
Source) at
javax.swing.DefaultButtonModel.setPressed(Unknown
Source) at
javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown
Source) at
java.awt.Component.processMouseEvent(Unknown
Source) at
javax.swing.JComponent.processMouseEvent(Unknown
Source) at
java.awt.Component.processEvent(Unknown
Source) at
java.awt.Container.processEvent(Unknown
Source) at
java.awt.Component.dispatchEventImpl(Unknown
Source) at
java.awt.Container.dispatchEventImpl(Unknown
Source) at
java.awt.Component.dispatchEvent(Unknown
Source) at
java.awt.LightweightDispatcher.retargetMouseEvent(Unknown
Source) at
java.awt.LightweightDispatcher.processMouseEvent(Unknown
Source) at
java.awt.LightweightDispatcher.dispatchEvent(Unknown
Source) at
java.awt.Container.dispatchEventImpl(Unknown
Source) at
java.awt.Window.dispatchEventImpl(Unknown
Source) at
java.awt.Component.dispatchEvent(Unknown
Source) at
java.awt.EventQueue.dispatchEvent(Unknown
Source) at
java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown
Source) at
java.awt.EventDispatchThread.pumpEventsForFilter(Unknown
Source) at
java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown
Source) at
java.awt.EventDispatchThread.pumpEvents(Unknown
Source) at
java.awt.EventDispatchThread.pumpEvents(Unknown
Source) at
java.awt.EventDispatchThread.run(Unknown
Source)

In line 25 it says

    OceanObject obj = (OceanObject) list.getSelectedItem();

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

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

发布评论

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

评论(4

江城子 2024-11-24 13:28:04

为模型提供一个公共方法 deleteSelectedItem() 并让按钮的 ActionListener 调用该方法。按钮/操作监听器不需要知道项目是如何删除的;它需要知道和做的就是向模型发送一条消息来执行此操作。

Give the model a public method deleteSelectedItem() and have the button's ActionListener call that method. The button/action listener don't need to know how the item is deleted; all it needs to know and do is to send a message to the model to do this.

苏佲洛 2024-11-24 13:28:04

第 25 行和异常告诉您需要了解的一切。您正在将项目从 JComboBox 中取出并转换为 OceanObject,但异常告诉您它们是 String

您必须使用字符串填充 JComboBox 的模型。要么用 OceanObject 填充它们,然后您的转换就会起作用,或者从 JComboBox 中取出 String 对象并以某种方式取回您的 OceanObject

    Vector<OceanItem> oceanItems = new Vector<OceanItem>();
    oceanItems.add(new OceanItem(...));
    oceanItems.add(new OceanItem(...));
    oceanItems.add(new OceanItem(...));
    JComboBox box = new JComboBox(oceanItems);

Line 25 and the exception tells you everything you need to know. You are pulling items out of the JComboBox and casting to OceanObject, but the exception tells you they are Strings.

You must be populating your JComboBox's model with Strings. Either populate them with OceanObjects and then your cast will work, or pull out the String object from the JComboBox and somehow get back your OceanObject.

    Vector<OceanItem> oceanItems = new Vector<OceanItem>();
    oceanItems.add(new OceanItem(...));
    oceanItems.add(new OceanItem(...));
    oceanItems.add(new OceanItem(...));
    JComboBox box = new JComboBox(oceanItems);
独孤求败 2024-11-24 13:28:04

“将 JComboBox 与 JButton 连接。使用所选项目执行按钮”是什么意思?您的意思是希望用户能够在组合框中选择一个项目,然后按下按钮,并且您询问如何对组合框中选定的项目执行某些操作?

如果是,只需通过 addActionListener() 将 ActionListener 添加到按钮,并在该操作侦听器中获取所选的项目。

comboBox = new JComboBox();
container.add(comboBox);
button = new JButton("Button");
container.add(button);
button.addActionListener(myButtonListener);

...

myButtonListener = new ActionListener()
{
    public void actionPerformed(ActionEvent ae)
    {
        System.out.println("Selected item is: " + comboBox.getSelectedItem());
        OceanObject myObject = (OceanObject)comboBox.getSelectedItem();
        // do something else with myObject here
    }
};

如果我正确理解你的要求,我认为这正是你想要的。根据你所说的,听起来你不需要搞乱你正在进入的任何其他东西。它就像制作和添加组合框和按钮一样简单,并向按钮添加一个动作侦听器,该按钮在其 actionPerformed() 中对组合框执行某些操作。

好的,根据您的评论,我想我现在明白您的问题所在。尽管如此,我仍然坚持我的观点,即您不需要额外的开销。 JComboBox 有一个 getSelectedItem()。我修改了上面的代码,以便在您的逻辑所在的位置,我替换了关于“将您的逻辑放在这里”的评论,并将输出放在那里,以便您可以看到它的使用。

正如您所看到的,我什至不必跟踪所做更改时选择的内容。

(编辑)
回应您编辑的问题:抛出异常是因为您没有OceanObject添加到ComboBox,而是添加了String。所以这个问题可以追溯到代码中向 ComboBox 添加内容的地方。那看起来像什么?

What do you mean by "connect a JComboBox with a JButton. do button with selected item"? Do you mean that you want the user to be able to select an item in the combo box, then press the button, and you are asking how to perform some action upon the selected item in the combo box?

If yes, just add an ActionListener to the button via addActionListener(), and in that action listener get the item that is selected.

comboBox = new JComboBox();
container.add(comboBox);
button = new JButton("Button");
container.add(button);
button.addActionListener(myButtonListener);

...

myButtonListener = new ActionListener()
{
    public void actionPerformed(ActionEvent ae)
    {
        System.out.println("Selected item is: " + comboBox.getSelectedItem());
        OceanObject myObject = (OceanObject)comboBox.getSelectedItem();
        // do something else with myObject here
    }
};

If I understand what you are asking correctly, I think that is exactly what you want. According to what you've said, it doesn't sound like you need to mess with any of the other stuff you're getting into there. It's as simple as making and adding your combo box and button, and adding an action listener to the button that does something to the combo box in its actionPerformed().

Ok, based on your comment I think I see now where your problem lies. Still, I stand by my comment that you don't need that extra overhead. JComboBox has a getSelectedItem(). I have modified my code above so that, in the spot where your logic for this goes, I have replaced my comment about "put your logic here" and put an output there instead so that you can see this used.

As you can see, I don't even have to keep track of what was selected as the changes were made.

(edit)
In response to your edited question: The exception is being thrown because you are not adding OceanObjects to the ComboBox, you are adding Strings. So this problem goes back to the place in your code where you are adding things to your ComboBox. What does that look like?

笑梦风尘 2024-11-24 13:28:04

感谢大家的帮助。
我只是用我的新知识构建一个解决方案。我希望其他人能找到一些帮助。

   public class DeleteButtonController implements ActionListener {
    private OceanGui view;

    public DeleteButtonController(OceanGui view) {
        this.view = view;
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        try {
            OceanObject obj = (OceanObject) view.getObjects().getSelectedItem();
            int index = view.getModel().getIndexOfClosestOceanObject(
                    obj.getPosition()[0], obj.getPosition()[1]);
            view.getModel().delOceanObject(index);

            view.getObjects().removeAllItems();
            Iterator<OceanObject> iterator = view.getModel().getOceanObjects()
                    .iterator();
            while (iterator.hasNext()) {
                view.getObjects().addItem(iterator.next());
            }

        } catch (NullPointerException e) {
            JOptionPane.showMessageDialog(null, "No more OceanObjects in Ocean.", "Error", JOptionPane.ERROR_MESSAGE);
        }

    }
}

Thanks for your help everyone.
I just buildet a solution with my new know how. I hope someone else will find some help with it.

   public class DeleteButtonController implements ActionListener {
    private OceanGui view;

    public DeleteButtonController(OceanGui view) {
        this.view = view;
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        try {
            OceanObject obj = (OceanObject) view.getObjects().getSelectedItem();
            int index = view.getModel().getIndexOfClosestOceanObject(
                    obj.getPosition()[0], obj.getPosition()[1]);
            view.getModel().delOceanObject(index);

            view.getObjects().removeAllItems();
            Iterator<OceanObject> iterator = view.getModel().getOceanObjects()
                    .iterator();
            while (iterator.hasNext()) {
                view.getObjects().addItem(iterator.next());
            }

        } catch (NullPointerException e) {
            JOptionPane.showMessageDialog(null, "No more OceanObjects in Ocean.", "Error", JOptionPane.ERROR_MESSAGE);
        }

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