【问题标题】:JComboBox added in specific JTable cell does not render在特定 JTable 单元格中添加的 JComboBox 不呈现
【发布时间】:2018-12-02 05:28:34
【问题描述】:

我正在开发一个带有秋千的游戏大厅。我有一个 JTable,所有不同的玩家都登录了房间,我只想在一个单元格中添加一个 JComboBox。 我的问题是组合框无法正确呈现。

我知道有很多关于这个主题的其他主题,但我找不到有同样问题的人。

JComboBox box = new JComboBox();
box.addItem("Warrior");
/* Adds few other items (strings)*/
this.box.addActionListener (new ActionListener () {
    public void actionPerformed(ActionEvent e) {
        /* sends message to server to change character when the combobox's chosen element is changed*/
    }
});
TableUserModel model = new TableUserModel(localUser,this.box); //Specifying the local user as I don't want a JComboBox in the others user's rows.
JTable table = new JTable(this.model);
table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(this.box));

表模型类

public class TableUserModel extends AbstractTableModel{

    private String[] columnNames = {"Username","Class","TeamColor","Action"};
    private Object[][] data = {{null,null,null,null}};
    private User localUser;
    private JComboBox box;
    
    public TableUserModel(User u,JComboBox box) {
        this.localUser = u;
        this.box = box;
    }

    @Override
    public int getColumnCount() {
        return this.columnNames.length;
    }

    @Override
    public int getRowCount() {
        return this.data.length;
    }

    @Override
    public Object getValueAt(int row, int col) {
        return this.data[row][col];
    }
    
    public String getColumnName(int col) {
        return columnNames[col];
    }
    
    public Class getColumnClass(int column) {
        for (int row = 0; row < getRowCount(); row++) {
            Object o = getValueAt(row, column);
            if (o != null) {
                return o.getClass();
            }
        }
        return Object.class;
    }
    
    //The following method updates my data array when the informations are refreshed from the server
    public void refreshUsers(ArrayList<User> users) {
        int elementNumber = 0;
        //clears the data[][] array
        this.data = new Object[][];
        for (User usr : users) {
            this.data[elementNumber][0] = usr.getUsername();
            /*if it's the GriffinBabe's (local user) row */
                this.data[elementNumber][1] = this.box; //HERE!!! I add the JComboBox into the specific cell
            /*else adds a simple string information (for users other than localplayer) */
            this.data[elementNumber][2] = usr.getTeamColor();
            this.data[elementNumber][3] = null;
            elementNumber++;
        }
    }

用户类

只是一个包含一些信息的类,问题肯定不在这里

【问题讨论】:

    标签: java swing user-interface jpanel jcombobox


    【解决方案1】:

    我只想在一个单元格中添加一个 JComboBox。

    这与 TableModel 无关。显示编辑器的是视图(即表格),因此您需要自定义表格。

    一种方法是覆盖JTablegetCellEditor(...) 方法。例如:

    import java.awt.*;
    import java.awt.event.*;
    import java.util.List;
    import java.util.ArrayList;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    
    public class TableComboBoxByRow extends JPanel
    {
        List<String[]> editorData = new ArrayList<String[]>(3);
    
        public TableComboBoxByRow()
        {
            setLayout( new BorderLayout() );
    
            // Create the editorData to be used for each row
    
            editorData.add( new String[]{ "Red", "Blue", "Green" } );
            editorData.add( new String[]{ "Circle", "Square", "Triangle" } );
            editorData.add( new String[]{ "Apple", "Orange", "Banana" } );
    
            //  Create the table with default data
    
            Object[][] data =
            {
                {"Color", "Red"},
                {"Shape", "Square"},
                {"Fruit", "Banana"},
                {"Plain", "Text"}
            };
            String[] columnNames = {"Type","Value"};
    
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            JTable table = new JTable(model)
            {
                //  Determine editor to be used by row
                public TableCellEditor getCellEditor(int row, int column)
                {
                    int modelColumn = convertColumnIndexToModel( column );
    
                    if (modelColumn == 1 && row < 3)
                    {
                        JComboBox<String> comboBox1 = new JComboBox<String>( editorData.get(row));
                        return new DefaultCellEditor( comboBox1 );
                    }
                    else
                        return super.getCellEditor(row, column);
                }
            };
    
            JScrollPane scrollPane = new JScrollPane( table );
            add( scrollPane );
        }
    
        private static void createAndShowUI()
        {
            JFrame frame = new JFrame("Table Combo Box by Row");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( new TableComboBoxByRow() );
            frame.setSize(200, 200);
            frame.setLocationByPlatform( true );
            frame.setVisible( true );
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowUI();
                }
            });
        }
    }
    

    【讨论】:

    • 工作正常!非常感谢。
    • 如果我希望两列具有不同的 JComboBox,我该怎么办?我尝试在 getCellEditor() 覆盖 if (modelColumn == 2 &amp;&amp; row == urow) //urow is the local user row but no problem here 中添加另一个“if”,但它只在我不添加它时起作用。 @camickr
    • but it does nothing more than when I don't add it - 那么你的“if/else”逻辑是错误的。该方法不知道也不关心您是否尝试更改单列或多列的编辑器。
    • 好的,我忘了在 public boolean isCellEditable(int row, int column) 覆盖中设置可编辑的附加列。
    猜你喜欢
    • 2012-03-05
    • 2021-06-20
    • 2012-12-30
    • 1970-01-01
    • 2011-03-16
    • 2016-07-01
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多