Java 在特定JTable单元格中添加的JComboBox不会呈现

Java 在特定JTable单元格中添加的JComboBox不会呈现,java,swing,user-interface,jpanel,jcombobox,Java,Swing,User Interface,Jpanel,Jcombobox,我正在开发一个带有swing的游戏大厅。我有一个JTable,所有不同的玩家都登录了这个房间,我只想在一个单元格中添加一个JComboBox。 我的问题是组合框不能正确渲染 我知道关于这个问题还有很多其他的线索,但我找不到有同样问题的人 JComboBox box = new JComboBox(); box.addItem("Warrior"); /* Adds few other items (strings)*/ this.box.addActionListener

我正在开发一个带有swing的游戏大厅。我有一个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++;
        }
    }
公共类TableUserModel扩展了AbstractTableModel{
私有字符串[]columnNames={“用户名”、“类”、“团队颜色”、“操作”};
私有对象[][]数据={{null,null,null,null};
私有用户localUser;
私人JComboBox;
公共表UserModel(用户u、JComboBox){
this.localUser=u;
this.box=box;
}
@凌驾
public int getColumnCount(){
返回this.columnNames.length;
}
@凌驾
public int getRowCount(){
返回此.data.length;
}
@凌驾
公共对象getValueAt(整数行,整数列){
返回此.data[行][col];
}
公共字符串getColumnName(int-col){
返回列名[col];
}
公共类getColumnClass(int列){
对于(int row=0;row
用户类

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++;
        }
    }
只是一个包含一些信息的类,问题当然不在这里

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

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

一种方法是覆盖
JTable
getCellEditor(…)
方法。例如:

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();
            }
        });
    }
}
import java.awt.*;
导入java.awt.event.*;
导入java.util.List;
导入java.util.ArrayList;
导入javax.swing.*;
导入javax.swing.event.*;
导入javax.swing.border.*;
导入javax.swing.table.*;
公共类TableComboBoxByRow扩展了JPanel
{
List editorData=new ArrayList(3);
公共表ComboxBoxByRow()
{
setLayout(新的BorderLayout());
//创建要用于每行的editorData
add(新字符串[]{“红色”、“蓝色”、“绿色”});
add(新字符串[]{“圆”、“正方形”、“三角形”});
add(新字符串[]{“Apple”、“Orange”、“Banana”});
//使用默认数据创建表
对象[][]数据=
{
{“颜色”,“红色”},
{“形状”,“正方形”},
{“水果”,“香蕉”},
{“纯”、“文本”}
};
字符串[]columnNames={“类型”,“值”};
DefaultTableModel=新的DefaultTableModel(数据、列名称);
JTable表格=新JTable(型号)
{
//确定行要使用的编辑器
公共表CellEditor getCellEditor(int行,int列)
{
int modelColumn=convertColumnIndexToModel(列);
if(modelColumn==1&&row<3)
{
JComboBox comboBox1=新的JComboBox(editorData.get(row));
返回新的DefaultCellEditor(comboBox1);
}
其他的
返回super.getCellEditor(行、列);
}
};
JScrollPane scrollPane=新的JScrollPane(表);
添加(滚动窗格);
}
私有静态void createAndShowUI()
{
JFrame frame=新JFrame(“按行排列的表格组合框”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(新的tableComboxByRow());
框架。设置尺寸(200200);
frame.setLocationByPlatform(真);
frame.setVisible(true);
}
公共静态void main(字符串[]args)
{
invokeLater(新的Runnable()
{
公开募捐
{
createAndShowUI();
}
});
}
}
我只想在一个单元格中添加一个JComboBox

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

一种方法是覆盖
JTable
getCellEditor(…)
方法。例如:

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();
            }
        });
    }
}
import java.awt.*;
导入java.awt.event.*;
导入java.util.List;
导入java.util.ArrayList;
导入javax.swing.*;
导入javax.swing.event.*;
导入javax.swing.border.*;
导入javax.swing.table.*;
公共类TableComboBoxByRow扩展了JPanel
{
List editorData=new ArrayList(3);
公共表ComboxBoxByRow()
{
setLayout(新的BorderLayout());
//创建要用于每行的editorData
add(新字符串[]{“红色”、“蓝色”、“绿色”});
add(新字符串[]{“圆”、“正方形”、“三角形”});
add(新字符串[]{“Apple”、“Orange”、“Banana”});
//使用默认数据创建表
对象[][]数据=
{
{“颜色”,“红色”},