java - 动态组合框问题

标签 java swing jtable jcombobox

您好,我正在使用一个表格,其中有两列,即仪器和方法。单击按钮后,我将在每个单元格中添加一行,其中包含组合框作为编辑器。此外,这些组合框将具有 Action 监听器。就像当我选择仪器时,方法组合框列表应该更改。我只使用两个组合框,每次添加行时都会实例化它。我的问题是,每当我添加新行时,现有的行组合都会重新加载最新值。这意味着,即使我以不同的方式实例化它,组合框也是唯一的。动态创建应该具有自己的值的组合框的方法是什么?下面发布我的代码供您引用。

addItem.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {
            comboInstrument = new CeNComboBox();
            comboMethod = new CeNComboBox();
            TableColumn instrumentColumn = table.getColumn("Instrument Used");
            TableColumn methodColumn = table.getColumn("Method Title");
            comboInstrument.removeAllItems();
            listInstruments = analyticalUtil.getInstruments(listAnalysisSummaryPrefs);
            iterateInstruments = listInstruments.iterator();
            while(iterateInstruments.hasNext()){
                comboInstrument.addItem(iterateInstruments.next());
            }
            dtm.addRow(new Object[]{" "," "});
            comboInstrument.setEditable(true);
            instrumentColumn.setCellEditor(new MyComboBoxEditor(comboInstrument));
            instrumentColumn.setCellRenderer(new MyComboBoxRenderer());
            comboMethod.setEditable(true);
            methodColumn.setCellEditor(new MyComboBoxEditor(comboMethod));
            methodColumn.setCellRenderer(new MyComboBoxRenderer());

            comboInstrument.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent argEvent){
                    comboInstrumentActionPerformed();
                }
            });
            comboMethod.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent argEvent){
                    comboMethodActionPerformed();
                }
            });
        }
    });

MyComboBoxEditor.java

public class MyComboBoxEditor extends DefaultCellEditor {



    public MyComboBoxEditor(JComboBox combobox) {
        super(combobox);
    }
}

我对 Swing 很陌生。请帮帮我。

添加一些带有硬编码值的示例代码。如果你运行这个你就会明白我的问题。以此方式进行测试。 1. 从第一列、第一行选择一个值,然后从另一列选择值。 2. 在第二行执行相同的操作,现在检查第一行的第二列。所有值将根据第二行的选择重新加载。 这就是我面临的问题。下面的代码是从以下链接复制和编辑的 JComboBox Action listener

private static final long serialVersionUID = 1L;
        private JComboBox mainComboBox;
        private JComboBox subComboBox;
        private Hashtable<Object, Object> subItems = new Hashtable<Object, Object>();

        public Testing() {
            String[] items = {"","Select Item", "Color", "Shape", "Fruit", "Size"};
            mainComboBox = new JComboBox(items);
            mainComboBox.addActionListener(this);
            mainComboBox.addItemListener(this);
            mainComboBox.setEditable(true);
            //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);
            subComboBox = new JComboBox();//  Create sub combo box with multiple models
            subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
            subComboBox.addItemListener(this);
//          getContentPane().add(subComboBox, BorderLayout.CENTER);
            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);
            String[] subItems4 = {"Select Size", "Big", "Middle", "Small"};
            subItems.put(items[4], subItems4);
            DefaultTableModel model = new DefaultTableModel(new String[]{"Instrument Used","Method Title"},0);
            JTable table = new JTable(model);
            table.getColumn("Instrument Used").setCellEditor(new MyComboBoxEditor(mainComboBox));
            table.getColumn("Instrument Used").setCellRenderer(new MyComboBoxRenderer());
            table.getColumn("Method Title").setCellEditor(new MyComboBoxEditor(subComboBox));
            table.getColumn("Method Title").setCellRenderer(new MyComboBoxRenderer());
            model.addRow(new String[]{""});
            model.addRow(new String[]{""});
            getContentPane().add(table, BorderLayout.CENTER);
        }

        public void actionPerformed(ActionEvent e) {
            String item = (String) mainComboBox.getSelectedItem();
            JOptionPane.showMessageDialog(null, "Action Performed "+item);
            Object o = subItems.get(item);
            if (o == null) {
                subComboBox.setModel(new DefaultComboBoxModel());
            } else {
                subComboBox.setModel(new DefaultComboBoxModel((String[]) o));
            }
        }

        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                if (e.getSource() == mainComboBox) {
                    if (mainComboBox.getSelectedIndex() != 0) {
                        FirstDialog firstDialog = new FirstDialog(Testing.this,
                                mainComboBox.getSelectedItem().toString(), "Please wait,  Searching for ..... ");
                    }
                } 
            }
        }

        private class FirstDialog extends JDialog {

            private static final long serialVersionUID = 1L;

            FirstDialog(final Frame parent, String winTitle, String msgString) {
                super(parent, winTitle);
                //setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
                JLabel myLabel = new JLabel(msgString);
                JButton bNext = new JButton("Stop Processes");
                add(myLabel, BorderLayout.CENTER);
                add(bNext, BorderLayout.SOUTH);
                bNext.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent evt) {
                        setVisible(false);
                    }
                });
                javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        setVisible(false);
                    }
                });
                t.setRepeats(false);
                t.start();
                setLocationRelativeTo(parent);
                setSize(new Dimension(400, 100));
                setVisible(true);
            }
        }

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

最佳答案

感谢您提供新代码。这非常有帮助。

我玩了你的 examplelpe 并重写它以正确地与编辑器一起使用。

注意以下部分:

  1. 测试。我删除了 subComboBox,这里不需要它。我删除了 mainComboBox 的 actionListener。
  2. MyComBobBoxEditor。我实现了方法getTableCellEditorComponent()。这是编辑器中的一个主要方法。在此方法中,我检查当前行中选择了哪个仪器,并为特定仪器准备编辑器组合框。

此示例尚不包含可编辑的组合框。但我希望它对你有帮助。

public class Testing extends JFrame implements ItemListener{
    private static final long serialVersionUID = 1L;
        private JComboBox mainComboBox;
        private Hashtable<Object, Object> subItems = new Hashtable<Object, Object>();

        public Testing() {
            String[] items = {"","Select Item", "Color", "Shape", "Fruit", "Size"};
            mainComboBox = new JComboBox(items);
            mainComboBox.addItemListener(this);
            mainComboBox.setEditable(true);
            String[] subItems1 = {"Select Color", "Red", "Blue", "Green"};
            subItems.put(items[2], subItems1);
            String[] subItems2 = {"Select Shape", "Circle", "Square", "Triangle"};
            subItems.put(items[3], subItems2);
            String[] subItems3 = {"Select Fruit", "Apple", "Orange", "Banana"};
            subItems.put(items[4], subItems3);
            String[] subItems4 = {"Select Size", "Big", "Middle", "Small"};
            subItems.put(items[5], subItems4);
            DefaultTableModel model = new DefaultTableModel(new String[]{"Instrument Used","Method Title"},0);
            JTable table = new JTable(model);
            table.getColumn("Instrument Used").setCellEditor(new DefaultCellEditor(mainComboBox));
            //table.getColumn("Instrument Used").setCellRenderer(new MyComboBoxRenderer());
            table.getColumn("Method Title").setCellEditor(new MyComboBoxEditor());
            //table.getColumn("Method Title").setCellRenderer(new MyComboBoxRenderer());
            model.addRow(new String[]{""});
            model.addRow(new String[]{""});
            getContentPane().add(table, BorderLayout.CENTER);
        }

       public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                if (e.getSource() == mainComboBox) {
                    if (mainComboBox.getSelectedIndex() != 0) {
                        FirstDialog firstDialog = new FirstDialog(Testing.this,
                                mainComboBox.getSelectedItem().toString(), "Please wait,  Searching for ..... ");
                    }
                } 
            }
        }

        private class FirstDialog extends JDialog {

            private static final long serialVersionUID = 1L;

            FirstDialog(final Frame parent, String winTitle, String msgString) {
                super(parent, winTitle);
                //setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
                JLabel myLabel = new JLabel(msgString);
                JButton bNext = new JButton("Stop Processes");
                add(myLabel, BorderLayout.CENTER);
                add(bNext, BorderLayout.SOUTH);
                bNext.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent evt) {
                        setVisible(false);
                    }
                });
                javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        setVisible(false);
                    }
                });
                t.setRepeats(false);
                t.start();
                setLocationRelativeTo(parent);
                setSize(new Dimension(400, 100));
                setVisible(true);
            }
        }

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

    class MyComboBoxEditor extends AbstractCellEditor implements TableCellEditor, ItemListener {

            private JComboBox editorComboBox;

            public MyComboBoxEditor() {
                editorComboBox = new JComboBox();
            editorComboBox.addItemListener(this);
            }

            public Object getCellEditorValue()
            {
                return editorComboBox.getSelectedItem();
            }

            public Component getTableCellEditorComponent(JTable table,
                    Object value,
                    boolean isSelected,
                    int row,
                    int column)
            {
                // which instrument is selected?
                String instrument = (String) table.getValueAt(row, 0);
                String[] methods = (String[]) subItems.get(instrument);
                editorComboBox.setModel(new DefaultComboBoxModel(methods));
                editorComboBox.setSelectedItem(value);
                return editorComboBox;
            }

        public void itemStateChanged(ItemEvent e)
        {
            stopCellEditing();
        }
        }
}

关于java - 动态组合框问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11794308/

相关文章:

Java/Swing : Problem with key listener

java - 单击 JFrame 中的 JButton 时如何更改现有图像? ( java )

java - 我的教科书中的小程序设置与默认设置的比较

java - 为什么 JTable 滚动占用这么多内存?

java - 如何给 JTable 单元格边框(左、右、上、下)不同的颜色?

java - gson 无法使用 GsonBuilder.setDateFormat ("yyyy-MM-dd' T'HH :mm:ss. SSSZ"进行解析"

java - 内存不足错误 : Java heap memory (GC heap)

java - 如何将 BST 中的删除方法从递归切换为迭代?

java - 在 JTable Netbeans 中插入单选按钮

java - 'javac' 不是内部或外部命令,也不是可运行的程序或批处理文件。在 VS Code 中,使用 Code Runner 扩展