【问题标题】:Dynamic JComboBox content based on the contents of another JComboBox基于另一个 JComboBox 内容的动态 JComboBox 内容
【发布时间】:2016-12-04 12:15:16
【问题描述】:

这段代码很草率,我也欢迎一些反馈。

我正在尝试根据另一个 JComboBox 的值更改 JComboBox 的值。还有一个额外的复杂之处在于我使用了一个额外的类来确定要返回的字符串数组(请参阅我之前的问题)。

理论上,我的代码应该可以工作:

    String[] siteSelectStrings = {"Site", "London", "Long Island"};
    JComboBox regSiteSelectBox = new JComboBox(siteSelectStrings);
    regSiteSelectBox.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent arg0) {
            getBuildingList gbl = new getBuildingList();
            regBuildingSelectBox.addItem(gbl.buildingSelectList((String)(regSiteSelectBox.getSelectedItem())));
            }
        });
    regSiteSelectBox.setBounds(24, 336, 282, 20);
    contentPane.add(regSiteSelectBox);


    regBuildingSelectBox = new JComboBox();
    regBuildingSelectBox.setBounds(24, 367, 282, 20);
    contentPane.add(regBuildingSelectBox);

以及返回Building数组的方法:

public class getBuildingList {

public String[] buildingSelectList(String site)
{
    switch (site)
    {
    case "London":
        return new String[]  {"Building", "Harvell", "LYNX Complex", "Caroline", "Salters"};
    case "Long Island":
        return new String[] {"Building", "Phillips", "Pascal"};
    }
    return new String[] {"Failed to populate buildings"};
    }  
}

但是,它不是返回一个清晰的字符串,而是返回以下内容:

[Ljava.lang.String;@917081d

我不知道如何解码它,虽然它看起来像是一个内存引用。我哪里错了?

【问题讨论】:

  • 为了让我们为您提供帮助,您必须向我们提供getBuildingList.buildingSelectList(String arg) 方法,因为这似乎是事情变得混乱的部分......而且您真的应该习惯于开始使用大写字母的类名,否则其他人阅读您的代码时会感到非常困惑
  • @Raven 我倾向于以 [LC][UC+] 格式命名类,无论它们用作子对象,而不是主要类 - 有一种方法支持这一点,尽管它不是基于 Java 的.从技术上讲,我是一名 C# 程序员......
  • 好吧...但是我们仍然需要那个方法;)
  • @Raven 请看我的编辑
  • 您的第二个组合框是否显示[Ljava.lang.String;@917081d

标签: java swing jcombobox


【解决方案1】:

如果您的方法返回要在组合框中显示的字符串数组,那么您需要创建一个新的 ComboBoxModel 以添加到组合框中。

例如:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;

public class ComboBoxTwo extends JPanel implements ActionListener
{
    private JComboBox<String> mainComboBox;
    private JComboBox<String> subComboBox;
    private Hashtable<String, String[]> subItems = new Hashtable<String, String[]>();

    public ComboBoxTwo()
    {
        String[] items = { "Select Item", "Color", "Shape", "Fruit" };
        mainComboBox = new JComboBox<String>( items );
        mainComboBox.addActionListener( this );

        //  prevent action events from being fired when the up/down arrow keys are used
        mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        add( mainComboBox );

        //  Create sub combo box with multiple models

        subComboBox = new JComboBox<String>();
        subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
        add( subComboBox );

        JButton arrow = SwingUtils.getDescendantOfType(JButton.class, subComboBox, "Text", "");
        Dimension d = arrow.getPreferredSize();
        System.out.println(arrow.getClass());
        System.out.println(d);
        d.width = 100;
        arrow.setPreferredSize(d);

        String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
        subItems.put(items[1], subItems1);

        String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
        subItems.put(items[2], subItems2);

        String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
        subItems.put(items[3], subItems3);
    }

    public void actionPerformed(ActionEvent e)
    {
        String item = (String)mainComboBox.getSelectedItem();
        Object o = subItems.get( item );

        if (o == null)
        {
            subComboBox.setModel( new DefaultComboBoxModel() );
        }
        else
        {
            subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
        }
    }

    private static void createAndShowUI()
    {
        try
        {
//          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception e) { }
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new ComboBoxTwo() );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

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

【讨论】:

  • 完全有必要重新创建模型吗?我尝试遍历数组中的项目,这与遍历数组两次的事实不同。这感觉……很复杂。为什么有必要?
  • @Wolfish,重新创建模型使解决方案非常简单。每组数据都有自己的模型。数据可能来自任何地方。它可以是硬编码的。它可能来自数据库。如果可以来自平面文件。该解决方案可重复使用。
【解决方案2】:

好吧,据我所知,您的问题是您将完整的字符串数组添加为一个项目。然后,JCombobox 通过调用 toString() mehtod 将其转换为单个字符串,这会导致它显示 [Ljava.lang.String;@917081d
为了使您的数组内容在JComboBox 中显示为单个条目,您必须清除它,然后单独添加每个项目:

regBuildingSelectBox.removeAllItems();

for(String currentEntry : gbl.buildingSelectList((String)(regSiteSelectBox.getSelectedItem())) {  
        regBuildingSelectBox.addItem(currentEntry);
}

当您要求对您的代码提供其他反馈时...我建议使用枚举而不是硬编码的字符串数组。这只是一个潜在的错误来源

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2015-03-15
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多