简体   繁体   English

如何在jSwing组合框中到达对象?

[英]How can I reach an object in jSwing combobox?

I'm working on a maven based java desktop application and I'm using jSwing frames for interface. 我正在基于Maven的Java桌面应用程序上工作,并且正在使用jSwing框架作为界面。 I need to show people Tasks with their names at combobox, but I'm not sure about I did it well. 我需要在combobox上向人们展示Tasks及其名称,但是我不确定我做得如何。

In this code section, I got Tasks from my database as Lists, then I showed them at combobox. 在此代码部分中,我从数据库中以列表的形式获得了Tasks ,然后将它们显示在combobox上。

List<TmsTask> task;
    int i;
    try {
        task = Application.getApp().getMainService().getTasksList();
        for (i = 0; i <= task.size(); i++) {
            jComboBoxTask.setModel(new javax.swing.DefaultComboBoxModel<>(new String[]{task.get(i).getTaskName(), 
                                                                                       task.get(i + 1).getTaskName(),
                                                                                       task.get(i + 2).getTaskName()}));
        }

    } catch (Exception ex) {
        Logger.getLogger(BindTask.class.getName()).log(Level.SEVERE, null, ex);
    }

It's oke , I can see Task names at combobox. 好的,我可以在组合框看到任务名称。

The problem is; 问题是; I want to save an other info to database using that task. 我想使用该任务将其他信息保存到数据库。 But as you see, selected things(at combobox) just task names, not task objects. 但是,正如您所看到的,(在组合框中)选定的对象只是任务名称,而不是任务对象。

How can I put task objects at combobox option sections? 如何将任务对象放在组合框选项部分?

In this code section, I used to try taking Task objects from database and showing them at combobox sections, but combobox sections all shows same taskname. 在这段代码中,我曾经尝试从数据库中获取Task对象,并在combobox部分中显示它们,但是combobox部分都显示相同的任务名称。

private void jComboBoxTaskMousePressed(java.awt.event.MouseEvent evt) {                                           
    TmsTask task;

    try {
        task = Application.getApp().getMainService().getTasks();

            jComboBoxTask.setModel(new javax.swing.DefaultComboBoxModel<>(new String[]{task.getTaskName(), 
                                                                                       task.getTaskName(),
                                                                                       task.getTaskName()}));


    } catch (Exception ex) {
        Logger.getLogger(BindTask.class.getName()).log(Level.SEVERE, null, ex);
    }

}

Thanks for your help, best regards. 谢谢您的帮助,最诚挚的问候。

for (i = 0; i <= task.size(); i++) 
{
    jComboBoxTask.setModel(new javax.swing.DefaultComboBoxModel<>(
       new String[]{task.get(i).getTaskName(), task.get(i + 1).getTaskName(),

You can't keep creating a new model. 您无法继续创建新模型。 This means only the last task will ever be displayed. 这意味着将仅显示最后一个任务。

You need to: 你需要:

  1. set the model outside the loop 在循环之外设置模型
  2. use the addItem(...) method of the combo box to add each item. 使用组合框的addItem(...)方法添加每个项目。

Although I question if you should even be using a combo box. 尽管我质疑您是否甚至应该使用组合框。

I would suggest a JTable , which displays the data in row and columns would be better. 我建议使用JTable ,它在行和列中显示数据会更好。 Read the section from the Swing tutorial on How to Use Tables for more information. 阅读Swing教程中有关如何使用表的部分, 获取更多信息。

Edit: 编辑:

You can store any object in a combo box. 您可以将任何对象存储在组合框中。 The default renderer simply uses the toString() method of the object to display the value in the combo box. 默认渲染器仅使用对象的toString()方法在组合框中显示值。

So you can add a Task object to the combo box and then you will need to create a custom renderer to display the "task name" in the combo box. 因此,您可以将Task对象添加到组合框中,然后需要创建一个自定义渲染器以在组合框中显示“任务名称”。 See Combobox With Custom Renderer for more information on this topic and a simple example of a renderer. 有关此主题的更多信息以及渲染器的简单示例,请参见带有自定义渲染器的组合框。

@camickr is right (in comments). @camickr是正确的(在评论中)。 Using a combo box to show all fields from an Object doesn't make much sense. 使用组合框显示对象的所有字段没有多大意义。 Just override the toString method from your object and the default renderer will show it. 只需从您的对象覆盖toString方法,默​​认渲染器便会显示它。

Here is how you do it with a simple Person object (name,age). 使用简单的Person对象(名称,年龄)的方法如下。

package test;

import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class ObjectsInComboBox extends JFrame {
    public ObjectsInComboBox() {
        super("combo boxes");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(300, 300));
        getContentPane().setLayout(new FlowLayout());

        JComboBox<Person> personComboBox = new JComboBox<>();
        getContentPane().add(personComboBox);
        pack();
        personComboBox.addItem(new Person("John", 31));
        personComboBox.addItem(new Person("George", 55));
        personComboBox.addItem(new Person("Mike", 12));
        personComboBox.addItem(new Person("Brian", 36));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ObjectsInComboBox frame = new ObjectsInComboBox();
            frame.setVisible(true);
        });
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return name + " - " + age; //toString override so renderer can show it.
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM