java - 如何更新 2 个组合框

标签 java swing combobox

我有 2 个 Jcombo Box:combo1 和 combo2

我选择 combo1,我可以获得 combo2 的信息,但问题是我可以获取 combo2 的信息,但它没有更新。我也尝试使用 updata.UI() 但它没有帮助。

这是代码

public void actionPerformed(ActionEvent e) { 
    JComboBox cb = (JComboBox)e.getSource();
    String uname1 = (String)cb.getSelectedItem();

        combo2 = update(uname1);
        combo2.updateUI();

}

这是更新中的代码

protected JComboBox update(String name) {
    JComboBox tmp = new JComboBox();
    //Read Content from XML file (University is bigger than Year)
    NodeList nList = doc.getElementsByTagName("University");
    System.out.println("Inside Fn " + name);
    for(int i = 0 ; i < nList.getLength();i++) {
        Element el = (Element)nList.item(i);
        if(name.contentEquals(el.getAttributeNode("name").getNodeValue()))
        {
            NodeList tmpyList = el.getElementsByTagName("Year");
            for(int j = 0 ; j < tmpyList.getLength();j++) 
            {
                Element yl = (Element)tmpyList.item(j);
                System.out.println(yl.getAttribute("yr"));
                tmp.addItem(yl.getAttribute("yr"));
            }
        }
    }
    return tmp; //Return ComboBox to combo2
}

谢谢你的好意,我尝试使用你的代码但是它不起作用(它仍然没有更新),请帮助我

这是我的构造函数

public JFrameExample() {
    String[] comboboxdefault = { "Select" };

    JComboBox combo1 = Universitylist();
    JComboBox combo2 = new JComboBox(comboboxdefault);
    JComboBox combo3 = new JComboBox(comboboxdefault);

    uList.addActionListener(this);
    yList.addActionListener(this);
    dList.addActionListener(this);


    JPanel student_information = new JPanel(new GridLayout(0,1));
    uList.setName("University List");
    yList.setName("Year List");

    // University List

    student_information.add(combo1);
    // Database Year List

    student_information.add(combo2);
    // Programme List

    student_information.add(combo3);
    //Add Components to this container, using the default FlowLayout.
    add(student_information);

}

这是 combo2 更新它是返回字符串数组

protected String[] updateyList(String name)  
{
    String[] tmp = null;

           //Read from XML file
    for(int i = 0 ; i < nList.getLength();i++) {
        Element el = (Element)nList.item(i);
        if(name.contentEquals(el.getAttributeNode("name").getNodeValue()))
        {
            NodeList tmpyList = el.getElementsByTagName("Year");
            tmp = new String[tmpyList.getLength()];
            for(int j = 0 ; j < tmpyList.getLength();j++) 
            {
                Element yl = (Element)tmpyList.item(j);
                //Add to String Array
                tmp[j] = yl.getAttribute("yr");
            }
        }
    }

    return tmp;
}

在 Action 执行中

public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox)e.getSource();
    String uname1 = (String)cb.getSelectedItem();
    System.out.println(cb.getName()); // To make sure I got the combo1. 
    try {
        //I change to the model method 
        DefaultComboBoxModel model = new DefaultComboBoxModel(  updateyList(uname1) );
        System.out.println(model.getSize()); 
        combo2 = new JComboBox(); // If I don't have this line it will throw  error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        combo2.setModel(model);

    } catch (ParserConfigurationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (SAXException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

}

这是为了创建 GUI 功能

private static void createAndShowLoginGUI() {

   //Create and set up the window.
    JFrame frame = new JFrame("Login");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    JFrameExample newContentPane = new JFrameExample();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

这是主要功能

public static void main(String[] args)
{
    //Schedule a job for the event-dispatching thread:

    //creating and showing this application's GUI.

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowLoginGUI(); 
        }
    });
}

我想我做错了什么,但我不知道在哪里

最佳答案

无需使用 updateUI() 方法。

如果您想更改第二个组合框中的数据,那么您应该更改模型(不要创建新的组合框):

comboBox2.setModel(...);

它会自动重绘自己。您可以创建一个 DefaultComboBoxModel 并将数据直接添加到它。

编辑:

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

public class ComboBoxTwo extends JFrame implements ActionListener
{
    private JComboBox mainComboBox;
    private JComboBox subComboBox;
    private Hashtable subItems = new Hashtable();

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

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

        //  Create sub combo box with multiple models

        subComboBox = new JComboBox();
        subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
        getContentPane().add( subComboBox, BorderLayout.EAST );

        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);
//      mainComboBox.setSelectedIndex(1);
    }

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

    public static void main(String[] args)
    {
        JFrame frame = new ComboBoxTwo();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
     }
}

关于java - 如何更新 2 个组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7109798/

相关文章:

java - 用 Java 制作动画的最佳方式?

java - Redhat CentOS 中的 Swing 字体倾斜

java - 从 jDateChooser 更改月份格式

javascript - 如何在多个组合框 JQuery 中禁用选择时的组合框值?

c# - 多列组合框中的选定值

java - 重构访问遗留系统中存储库的域逻辑

java - 使用 google commons 创建集合实例的通用 vs 静态声明

java - Objectify - 注册类期间出现 StackOverflowError

java - 如何使用通配符作为类型对空列表使用react?

ms-access - 刷新组合框查询