gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:50:26 25 4
gpt4 key购买 nike

我有一个名为“Book”的对象,其中包含标题、作者、bookID 等列...在 Microsoft SQL Server 上创建。一切都与 Netbeans 连接并且工作正常。我还有一个过滤/搜索选项,效果也很好,但我想要一个组合框,其中填充了图书列,如标题、作者等,我想在其中选择一个列并仅在其中进行搜索。

我已经有一个名为 BookComboBoxModelclass ,它返回书籍(代码如下),但我想要该表中的书籍列,而不是 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;
}
}

最佳答案

您可以创建对象(客户)的数组,然后将其传递给组合框,如下所示:combo = 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;
}
}

关于java - 如何创建一个填充对象列的组合框? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56447024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com