Swing中是否有一个函数可以让您将JTable中的行数分配给变量?

问题描述

我正在创建一个JTable来显示String数据。我想将表中的行数设置为将由用户定义的特定变量。如果不使用非常复杂的模型和方法,是否有可能?要创建该表,我只需将其从调色板中拖放,以使生成代码不可编辑。谢谢。


对于任何努力根据用户指定的数组列表大小创建x个行的人,这对我有用:

以下是可以添加到类或框架并在构造函数调用方法代码

方法名称为addRowToTable;调用方法时将传递ArrayList。我的数组称为questionList,但您可以根据自己的目的替换它。

private void addRowToTable(ArrayList<QuestionManager> questionList){

这将设置模型*注意:YOURTABLENAME是表的名称,并且通过替换它,您可以将行添加到该表中。

 DefaultTableModel model =  (DefaultTableModel) YOURTABLENAME.getModel();

rowData是一个变量名;新对象[NUMBER]将列数设置为该数字

Object rowData[] = new Object[4];

setRowHeight允许您更改行的高度 您还可以使用许多其他有趣的方法,请参考API(https://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html) 为此(尽管我必须说,对于初学者来说,这是非常压倒性的。)

YOURTABLENAME.setRowHeight(50);

此for循环基本上逐行填充您的表,这里没有什么特别重要的。

for(int row = 0; row < questionList.size(); row++){
    rowData[0] = questionList.get(row).getGenNum1() + " + " + questionList.get(row).getGenNum2();
    rowData[1] = questionList.get(row).getUserAnswer();
    rowData[2] = questionList.get(row).getGenNum1() + questionList.get(row).getGenNum2();
    rowData[3] = questionList.get(row).getCorrect();

这部分很重要;它将数据行添加到表中。

   model.addRow(rowData);
}
}

调用方法,只需说 addRowToTable(questionList); 其中questionList是您的数组。我在构造函数中执行了此操作,以在出现框架时立即显示表,但您可以根据需要放置它。

总结一下,这是完整的代码

private void addRowToTable(ArrayList<QuestionManager> questionList){
DefaultTableModel model =  (DefaultTableModel) scoreTable.getModel();
Object rowData[] = new Object[4];
scoreTable.setRowHeight(50);
for(int row = 0; row < questionList.size(); row++){
    rowData[0] = questionList.get(row).getGenNum1() + " + " + questionList.get(row).getGenNum2();
    rowData[1] = questionList.get(row).getUserAnswer();
    rowData[2] = questionList.get(row).getGenNum1() + questionList.get(row).getGenNum2();
    rowData[3] = questionList.get(row).getCorrect();
    model.addRow(rowData);
}
}

您需要更改:传入的ArrayList,获取模型时的表名称,行中的列数以及如何填充表。希望这会有所帮助。

解决方法

您可以这样实现。

//First get the number of rows that user need to display on the table using a jTextField or any input mechanism you prefer from the GUI.

int noOfRows = Integer.parseInt(jTextFieldNoOfRows.getText()); //Here I am getting the user input from a text field.

 DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
 model.setRowCount(0);
 int count = 0;
 for(Sensor tempSensor: tempSensorList){//tempSensorList is the list which holds your data set which you want to display in the jTable. Here I am not showing the codes about the way I retrieved it. 
     if(count == noOfRows){
            break;
     }
     model.insertRow(0,new Object[]{tempSensor.getId(),tempSensor.getSensorName(),tempSensor.getFloorNumber(),tempSensor.getRoomNumber(),tempSensor.getSmokeLevel(),tempSensor.getCoLevel(),status}); //Setting your attributes to the table cells 
     count++;
 }
 jTable1.setModel(model);//Finally setting the Model to jTable
  

请注意,这里的tempSensorList是用于保存需要在JTable中显示的项目的数据集.Sensors是相关的模型对象。为了简单起见,这里我没有提及Sensor模型类或tempSensorList的初始化部分。