gpt4 book ai didi

java - 当另一个 ComboBox 更改索引时动态更新 JComboBox 项目

转载 作者:行者123 更新时间:2023-12-01 23:03:09 24 4
gpt4 key购买 nike

我有一个 Swing UI,有两个组合框,第一个由来自 obj1 数组的字符串填充,第二个组合框需要用存储在该对象内的数组中的字符串填充。

为了更好地理解这里有一个例子。您有学校类(class),每门类(class)可以有多个部分。在一个组合框中选择一门类(class)后,我希望部分的组合框填充与该类(class)关联的部分。

最佳答案

当第一个组合框中发生事件时更改第二个组合框的模型。像这样的东西:

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

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 );

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()
{
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();
}
});
}
}

关于java - 当另一个 ComboBox 更改索引时动态更新 JComboBox 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23205642/

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