gpt4 book ai didi

java - Swing - 自定义 JComboBox 项目

转载 作者:行者123 更新时间:2023-11-30 02:44:50 31 4
gpt4 key购买 nike

我在 JFrame 中创建了一个 JComboBox

JComboBox itemsComboBox = new JComboBox();

然后创建一个类

public class ItemCombo {

Product p;

public ItemCombo(Product p) {
this.p = p;
}

@Override
public String toString(){
return p.getName();
}

public Float getPrice() {
return p.getPrice();
}
}

就我对组合框的了解而言,现在我应该能够做到

itemsComboBox.addItem(new ItemCombo(Product));

但是,它说它无法将 ItemCombo 对象转换为字符串。我究竟做错了什么?是否有另一种方法来创建这样的自定义 JComboBox?

最佳答案

您会发现从 JComboBox 模型中添加/删除项目比直接从 JComboBox 中添加/删除项目更好。因此创建一个DefaultComboBoxModel<ItemCombo>对象,让它成为你的JComboBox<ItemCombo>的模型。然后将项目添加到模型中,你应该是金色的。例如:

DefaultComboBoxModel<ItemCombo> comboModel = new DefaultComboBoxModel<>();
JComboBox<ItemCombo> itemsComboBox = new JComboBox<>(comboModel); // *** fixed ***

// ......

comboModel.addItem(new ItemCombo(someProduct));

概念验证代码:

import java.awt.Dimension;
import javax.swing.*;

public class TestCombo extends JPanel {
private static final Product[] products = {
new Product("One", 1.0),
new Product("Two", 2.0),
new Product("Three", 3.0),
new Product("Four", 4.0),
new Product("Five", 5.0),
};

private DefaultComboBoxModel<ItemCombo> comboModel = new DefaultComboBoxModel<>();
private JComboBox<ItemCombo> itemsComboBox = new JComboBox<>(comboModel);

public TestCombo() {
add(itemsComboBox);
for (Product product : products) {
comboModel.addElement(new ItemCombo(product));
}
itemsComboBox.addActionListener(e -> {
ItemCombo itemCombo = (ItemCombo) itemsComboBox.getSelectedItem();
System.out.println("Selection: " + itemCombo.getProduct());
});

setPreferredSize(new Dimension(400, 150));
}

private static void createAndShowGui() {
JFrame frame = new JFrame("TestCombo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TestCombo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}


class ItemCombo {

private Product product;

public ItemCombo(Product p) {
this.product = p;
}

@Override
public String toString(){
return product.getName();
}

public double getPrice() {
return product.getPrice();
}

public Product getProduct() {
return product;
}
}

class Product {

private String name;
private double price;

public Product(String name, double price) {
this.name = name;
this.price = price;
}

public String getName() {
return name;
}

public double getPrice() {
return price;
}

@Override
public String toString() {
return "Product [name=" + name + ", price=" + price + "]";
}
}

关于java - Swing - 自定义 JComboBox 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40497360/

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