能不能帮我写一个java swing程序,我需要读取用户在界面上输入的数字n,并在界面上生成一个n*n的方阵,方阵是由n*n个红色的小方块组成
时间: 2023-06-03 13:07:02 浏览: 42
当然可以。以下是一个简单的Java Swing程序,可以实现您的需求:
```
import javax.swing.*;
import java.awt.*;
public class SquareMatrix extends JFrame {
private JPanel panel;
private JTextField textField;
private JButton button;
public SquareMatrix() {
this.setTitle("方阵生成器");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300, 150);
this.setLocationRelativeTo(null);
panel = new JPanel(new GridLayout(2, 1));
textField = new JTextField(10);
button = new JButton("生成方阵");
panel.add(new JLabel("请输入方阵的大小:"));
panel.add(textField);
panel.add(button);
button.addActionListener(e -> {
int n = Integer.parseInt(textField.getText()); // 获取用户输入的数字n
JFrame matrix = new JFrame();
matrix.setTitle("方阵");
matrix.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
matrix.setSize(400, 400);
matrix.setLocationRelativeTo(null);
JPanel matrixPanel = new JPanel(new GridLayout(n, n));
for (int i = 0; i < n * n; i++) {
JPanel square = new JPanel();
square.setBackground(Color.RED);
square.setBorder(BorderFactory.createLineBorder(Color.BLACK)); // 添加黑色边框
matrixPanel.add(square);
}
matrix.add(matrixPanel);
matrix.setVisible(true);
});
this.add(panel);
this.setVisible(true);
}
public static void main(String[] args) {
new SquareMatrix();
}
}
```
运行程序后,用户在文本框中输入数字n,点击“生成方阵”按钮后,程序会生成一个n*n的红色方阵,每个小方块都有黑色边框。注意:为了简化代码,我没有添加输入检查,如果用户输入的是非数字或负数,程序会抛出异常。您可以自行添加相应的检查逻辑。