简体   繁体   English

为JTable中的不同单元格添加不同的JComboBoxes

[英]Adding different JComboBoxes for different cells in a JTable

Say I have an object representing a Person. 说我有一个对象代表一个人。 Each person has a name, and a list of hobbies. 每个人都有一个名字和一份爱好清单。

Now, I want to create a table with 2 columns for the list of persons that I have. 现在,我想创建一个包含两列的表格,用于列出我所拥有的人员。 The first column will show the name of the person, and the second will show the list of hobbies in a combo box. 第一列将显示人员姓名,第二列将在组合框中显示兴趣爱好列表。

The thing is, I iterate over my list of persons in order to populate the table. 事实是,我要遍历我的人员列表以填充表格。 So I don't have a way to know at the beginning "row 1 will have combo box X, row 2 will have combo box Y and so on". 因此,我没有办法在一开始就知道“第1行将具有组合框X,第2行将具有组合框Y,依此类推”。 I will only know these things at runtime. 我只会在运行时知道这些事情。

Got any ideas? 有任何想法吗?

Cell editing is provided by a CellEditor . 单元格编辑由CellEditor提供。 This basically means that each column will have the same cell editor. 这基本上意味着每列将具有相同的单元格编辑器。 There are ways around this, but lets keep it simple. 有许多解决方法,但请保持简单。

Assuming that the list of hobbies is finite, and the list is the same for all people, it would be a simple matter to create a JComboBox based CellEditor and apply it to the table 假定兴趣爱好列表是有限的,并且所有人的列表都是相同的,那么创建一个基于JComboBoxCellEditor并将其应用于表将是一件简单的事情

Start by taking a look at Concepts: Editors and Renderers and Using Other Editors 首先看一下概念:编辑器和渲染器以及使用其他编辑器

组合框编辑器

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;

public class Hobbies {

    public static void main(String[] args) {
        new Hobbies();
    }

    public Hobbies() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                List<Person> people = new ArrayList<>(25);
                people.add(new Person("Mellisa"));
                people.add(new Person("Annabell"));
                people.add(new Person("Margarita"));
                people.add(new Person("Steve"));
                people.add(new Person("Christel"));

                DefaultCellEditor editor = new DefaultCellEditor(new JComboBox(createHobbiesComboBoxModel()));

                PersonTableModel model = new PersonTableModel(people);
                JTable table = new JTable(model);
                table.getColumnModel().getColumn(1).setCellEditor(editor);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        });
    }

    public ComboBoxModel createHobbiesComboBoxModel() {
        String[] hobbies = {"3D Printing",
            "A vintage scrapbook",
            "Amateur radio[1]",
            "Baton twirling",
            "Cleaning",
            "Computer programming",
            "Cooking",
            "Coloring",
            "Cosplaying",
            "Creative writing",
            "Crocheting",
            "Cryptography",
            "Dance",
            "Digital arts",
            "Drama",
            "Drawing",
            "Drinking Coffee",
            "Eating",
            "Electronics",
            "Embroidery",
            "Foreign language learning",
            "Gaming (tabletop games and role-playing games)",
            "Gambling",
            "Genealogy",
            "Homebrewing"};
        return new DefaultComboBoxModel(hobbies);
    }

    public class PersonTableModel extends AbstractTableModel {

        private List<Person> people;

        public PersonTableModel(List<Person> person) {
            people = new ArrayList<>(person);
        }

        @Override
        public int getRowCount() {
            return people.size();
        }

        @Override
        public int getColumnCount() {
            return 2;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return columnIndex == 1;
        }

        @Override
        public String getColumnName(int columnIndex) {
            String value = null;
            switch (columnIndex) {
                case 0:
                    value = "Name";
                    break;
                case 1:
                    value = "Hobby";
                    break;
            }
            return value;
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            if (columnIndex == 1) {
                Person person = people.get(rowIndex);
                person.setHobby(aValue == null ? null : aValue.toString());
                fireTableCellUpdated(rowIndex, columnIndex);
            }
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object value = null;
            Person person = people.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    value = person.getName();
                    break;
                case 1:
                    value = person.getHobby();
                    break;
            }
            return value;
        }

    }

    public class Person {

        private String name;
        private String hobby;

        public Person(String name) {
            this.name = name;
        }

        public void setHobby(String hobby) {
            this.hobby = hobby;
        }

        public String getName() {
            return name;
        }

        public String getHobby() {
            return hobby;
        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM