如何创建一个填充对象列的组合框?(JAVA)

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (13)

我有一个名为“Book”的对象,其中包含title,author,bookID等...在Microsoft SQL Server上创建的列。一切都与Netbeans有关,工作正常。我也有过滤/搜索选项也很好但我想有一个组合框填充书籍列,如标题,作者等我想要选择一个列,只在其中搜索。

我已经有一个class调用BookComboBoxModel返回书籍(下面的代码),但我希望该表中的书列而不是Book.toString()方法comboBox

//this is my book combo model that returns books into combobox

public class BookComboBoxModel extends AbstractListModel<Book> implements ComboBoxModel<Book> {

    private List <Book> data;
    private Book selectedItem;


    public BookComboBoxModel(List<Book> data) {
        this.data = data;
    }

    public BookComboBoxModel() {
    }

    public void add(List<Book> data) {
        this.data = data;
    }

    @Override
    public int getSize() {
        return data.size();
    }

    @Override
    public Book getElementAt(int index) {
        return data.get(index);
    }

    @Override
    public void setSelectedItem(Object anItem) {
        selectedItem = (Book) anItem;
    }

    @Override
    public Object getSelectedItem() {
        return selectedItem;
    }
}
提问于
用户回答回答于

基于注释,很明显你想要的不是Book对象的模型,而是包含Book类属性的模型。

一个好方法是创建一个小的自定义对象作为JComboBox项:

public class BookAttribute {
    private final String name;
    private final int columnNumber;

    public BookAttribute(String name,
                         int columnNumber) {

        this.name = Objects.requireNonNull(name, "Name cannot be null");
        this.columnNumber = columnNumber;
    }

    public String getName() {
        return name;
    }

    public int getColumnNumber() {
        return columnNumber;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof BookAttribute) {
            return this.columnNumber == ((BookAttribute) obj).columnNumber;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(columnNumber);
    }

    @Override
    public String toString() {
        return name;
    }
}

使用该类,您不需要自定义模型。您只需将实例直接传递给标准JComboBox构造函数即可:

TableModel model = table.getModel();

int count = model.getColumnCount();
Vector<BookAttribute> fields = new Vector<>(count);
for (int col = 0; col < count; col++) {
    fields.add(new BookAttribute(model.getColumnName(col), col));
}

JComboBox<BookAttribute> fieldList = new JComboBox<>(fields);

要使用它,您需要在表的RowSorter中添加一个过滤器:

table.setAutoCreateRowSorter(true);

ActionListener filterUpdater = e -> {
    String searchText = searchField.getText();

    BookAttribute bookAttribute =
        (BookAttribute) fieldList.getSelectedItem();
    int columnNumber = bookAttribute.getColumnNumber();

    TableRowSorter<? extends TableModel> sorter =
        (TableRowSorter<? extends TableModel>) table.getRowSorter();

    sorter.setRowFilter(new RowFilter<TableModel, Integer>() {
        @Override
        public boolean include(
            Entry<? extends TableModel, ? extends Integer> entry) {

            return entry.getStringValue(columnNumber).contains(searchText);
        }
    });
};

searchField.addActionListener(filterUpdater);
fieldList.addActionListener(filterUpdater);

(您可以使用反射,但不应该。反射是不可靠的,容易出错,因为编译器无法检查它是否正确。通常,Java运行时也无法对其进行优化。)

用户回答回答于

您可以创建一个array对象(客户),然后将其传递给comboboxcombo = new JComboBox(customers);

看看这个例子:

import java.awt.BorderLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JFrame {
  JLabel label;
  JComboBox combo;
  public static void main(String args[]) {
    new Main();
  }

  public Main() {
    label = new JLabel("Select a Customer");
    add(label, BorderLayout.NORTH);

    Customer customers[] = new Customer[6];
    customers[0] = new Customer("A", 1);
    customers[1] = new Customer("B", 6);
    customers[2] = new Customer("C", 2);
    customers[3] = new Customer("D", 3);
    customers[4] = new Customer("E", 4);
    customers[5] = new Customer("F", 5);

    combo = new JComboBox(customers);
    combo.addItemListener(e -> {
      Customer c = (Customer) e.getItem();
      label.setText("You selected customer id: " + c.getId());
    });
    JPanel panel = new JPanel();
    panel.add(combo);
    add(panel, BorderLayout.CENTER);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 200);
    setVisible(true);
  }
}

class Customer {
  private String name;
  private int id;

  public Customer(String name, int id) {
    this.name = name;
    this.id = id;
  }

  public String toString() {
    return getName();
  }

  public String getName() {
    return name;
  }

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

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }
}

扫码关注云+社区

领取腾讯云代金券