首先:您可以在文本字段中使用数组:
JTextField[][] matrix1TextFields, matrix2TextFields, matrix3TextFields;
private void refreshMatrixComponents(int r, int c) {
matrix1TextFields = new JTextField[r][c];
matrix2TextFields = new JTextField[r][c];
matrix3TextFields = new JTextField[r][c];
for (int row = 0; row < r; row++) {
for (int col = 0; col < c; col++) {
matrix1TextFields[row][col] = new JTextField();
matrix2TextFields[row][col] = new JTextField();
matrix3TextFields[row][col] = new JTextField();
}
}
placeMatrixTextField();
}
对于布局管理器,有很多选项。我会推荐GridLayout
(非常易于使用)或GridBagLayout
(更难使用,但更灵活)或第 3 方之类的东西MigLayout
(您将不得不深入研究语法,但我认为这完全值得付出努力)。我还建议为每个矩阵创建一个JPanel
并将所有文本字段放在那里。然后放置这些JPanels
+其余组件:
JPanel matrix1Panel, matrix2Panel, matrix3Panel;
private void placeMatrixTextField() {
int r = matrix1TextFields.length, c = matrixTextFields[0].length;
matrix1Panel = new JPanel();
matrix2Panel = new JPanel();
matrix3Panel = new JPanel();
matrix1Panel.setLayout(new GridLayout(r, c));
matrix2Panel.setLayout(new GridLayout(r, c));
matrix3Panel.setLayout(new GridLayout(r, c));
for (int row = 0; row < r; row++) {
for (int col = 0; col < c; col++) {
matrix1Panel.add(matrix1TextFields[row][col]);
matrix2Panel.add(matrix2TextFields[row][col]);
matrix3Panel.add(matrix3TextFields[row][col]);
}
}
// now place your panels
}