簡體   English   中英

JComboBox設置標簽和值

[英]JComboBox setting label and value

是否可以為JComboBox設置值和標簽,以便我可以顯示標簽,但獲得的值是不同的?

例如在JavaScript中,我可以這樣做:

document.getElementById("myselect").options[0].value //accesses value attribute of 1st option
document.getElementById("myselect").options[0].text //accesses text of 1st option

您可以將任何對象放在JComboBox中。 默認情況下,它使用對象的toString方法在組合框中使用鍵盤顯示標簽導航。 因此,最好的方法是在組合中定義和使用適當的對象:

public class ComboItem {
    private String value;
    private String label;

    public ComboItem(String value, String label) {
        this.value = value;
        this.label = label;
    }

    public String getValue() {
        return this.value;
    }

    public String getLabel() {
        return this.label;
    }

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

這是一個實用程序界面和類,可以讓組合框輕松使用不同的標簽。 這不使用創建替換ListCellRenderer (並且如果外觀被更改而冒着看起來ListCellRenderer風險),而是使用默認的ListCellRenderer (無論可能是什么),而是將您自己的字符串作為標簽文本而不是文本文本交換由值對象中的toString()定義。

public interface ToString {
    public String toString(Object object);
}

public final class ToStringListCellRenderer implements ListCellRenderer {
    private final ListCellRenderer originalRenderer;
    private final ToString toString;

    public ToStringListCellRenderer(final ListCellRenderer originalRenderer,
            final ToString toString) {
        this.originalRenderer = originalRenderer;
        this.toString = toString;
    }

    public Component getListCellRendererComponent(final JList list,
            final Object value, final int index, final boolean isSelected,
            final boolean cellHasFocus) {
        return originalRenderer.getListCellRendererComponent(list,
            toString.toString(value), index, isSelected, cellHasFocus);
    }

}

正如您所看到的, ToStringListCellRendererToString實現中獲取自定義字符串,然后將其傳遞給原始ListCellRenderer而不是傳遞值對象本身。

要使用此代碼,請執行以下操作:

// Create your combo box as normal, passing in the array of values.
final JComboBox combo = new JComboBox(values);
final ToString toString = new ToString() {
    public String toString(final Object object) {
        final YourValue value = (YourValue) object;
        // Of course you'd make your own label text below.
        return "custom label text " + value.toString();
    }
};
combo.setRenderer(new ToStringListCellRenderer(
        combo.getRenderer(), toString)));

除了使用它來制作自定義標簽之外,如果您創建一個基於系統區域設置創建字符串的ToString實現,您可以輕松地將組合框國際化,而無需更改值對象中的任何內容。

拜托,能給我看一個完整的例子嗎?

Enum實例對此特別方便,因為toString() “返回此枚舉常量的名稱,如聲明中所包含的那樣。”

在此輸入圖像描述

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see http://stackoverflow.com/questions/5661556 */
public class ColorCombo extends JPanel {

    private Hue hue = Hue.values()[0];

    public ColorCombo() {
        this.setPreferredSize(new Dimension(320, 240));
        this.setBackground(hue.getColor());
        final JComboBox colorBox = new JComboBox();
        for (Hue h : Hue.values()) {
            colorBox.addItem(h);
        }
        colorBox.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Hue h = (Hue) colorBox.getSelectedItem();
                ColorCombo.this.setBackground(h.getColor());
            }
        });
        this.add(colorBox);
    }

    private enum Hue {

        Cyan(Color.cyan), Magenta(Color.magenta), Yellow(Color.yellow),
        Red(Color.red), Green(Color.green), Blue(Color.blue);

        private final Color color;

        private Hue(Color color) {
            this.color = color;
        }

        public Color getColor() {
            return color;
        }
    }

    private static void display() {
        JFrame f = new JFrame("Color");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new ColorCombo());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                display();
            }
        });
    }
}

使用ListCellRenderer來實現您想要的效果。 創建一個擴展JLabel並實現ListCellRenderer 使用setRenderer()方法將該類設置為JComboBox的渲染器。 現在,當您從jcombobox訪問值時,它將是jlabel類型。

步驟1創建一個具有JComboBox的兩個屬性的類,例如id,name

public class Product {
    private int id;
    private String name;


    public Product(){

    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    //this method return the value to show in the JComboBox
    @Override
    public String toString(){
       return name;
    }

}

步驟2在表單的設計中,右鍵單擊JComboBox並選擇Properties,現在打開代碼選項卡並在屬性Type Parameters中寫入類的名稱,在我們的示例中它是Product。

在此輸入圖像描述

步驟3現在創建一個方法,使用查詢連接數據庫以生成產品列表,此方法接收JComboBox對象作為參數。

public void showProducts(JComboBox <Product> comboProduct){
    ResultSet res = null;
    try {
        Connection conn = new Connection();
        String query = "select id, name from products";
        PreparedStatement ps = conn.getConecction().prepareStatement(query);
        res = ps.executeQuery();
        while (res.next()) {
            comboProduct.addItem(new Product(res.getInt("id"), res.getString("name")));
        }
        res.close();
    } catch (SQLException e) {
        System.err.println("Error showing the products " + e.getMessage());
    }

}

步驟4您可以從表單中調用該方法

public frm_products() {
    initComponents();

    Product product = new Product(); 

    product.showProducts(this.cbo_product);

}

現在,您可以使用getItemAt方法訪問所選的id

System.out.println(cbo_product.getItemAt(this.cbo_product.getSelectedIndex()).getId());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM