单击“ Make array”按钮(Listener1,调用makeMatrix方法)后,应该实例化JTextFields的数组,当我运行代码时该数组不会显示。没有给出错误,只是没有空的JTextFields。
我尝试过setVisible(true),尝试在添加每个字段之前将文本添加到每个字段。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PanelM extends JPanel
{
public JTextField[][] matrix;
private JButton make;
public JPanel buttons;
public JPanel grid, entersize;
private JLabel enter;
public JTextField sizer;
public PanelM()
{
setLayout(new BorderLayout());
entersize = new JPanel();
entersize.setLayout(new FlowLayout());
enter = new JLabel("Enter size of the matrix: (n * n) ");
entersize.add(enter);
sizer = new JTextField(5);
entersize.add(sizer);
add(entersize, BorderLayout.NORTH);
make = new JButton("Create Matrix");
make.addActionListener(new Listener1());
buttons = new JPanel();
buttons.setLayout(new FlowLayout());
buttons.add(make);
add(buttons, BorderLayout.SOUTH);
}
private class Listener1 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int size = Integer.parseInt(sizer.getText());
makeMatrix(size);
add(grid, BorderLayout.CENTER);
}
}
public void makeMatrix(int size)
{
matrix = new JTextField[size][size];
grid = new JPanel();
grid.setLayout(new GridLayout(size, size, 1, 1));
for(int x = 0 ; x < size ; x++)
{
for(int y = 0 ; y < size ; y++)
{
matrix[x][y] = new JTextField(5);
matrix[x][y].setText("" + x + ", " + y);
matrix[x][y].setVisible(true);
grid.add(matrix[x][y], x, y);
}
}
}
}
它应该在JFrame的中心(未显示驱动程序)建立n * n JTextFields矩阵。没有出现这样的矩阵,但是出现了按钮,标签和“大小调整器”(另一个JTextField)DO。