Java设计图形用户界面程序实现矩阵运算
时间: 2024-01-06 07:05:27 浏览: 146
以下是一个Java设计图形用户界面程序实现矩阵运算的例子:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MatrixCalculator extends JFrame {
private JTextField[][] matrixFields;
private JButton addButton;
private JButton multiplyButton;
private JTextField resultField;
public MatrixCalculator() {
setTitle("Matrix Calculator");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel matrixPanel = new JPanel(new GridLayout(2, 2));
matrixFields = new JTextField[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
matrixFields[i][j] = new JTextField();
matrixPanel.add(matrixFields[i][j]);
}
}
addButton = new JButton("Add");
multiplyButton = new JButton("Multiply");
resultField = new JTextField();
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int[][] matrix1 = getMatrixValues(0);
int[][] matrix2 = getMatrixValues(1);
int[][] result = addMatrices(matrix1, matrix2);
displayResult(result);
}
});
multiplyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int[][] matrix1 = getMatrixValues(0);
int[][] matrix2 = getMatrixValues(1);
int[][] result = multiplyMatrices(matrix1, matrix2);
displayResult(result);
}
});
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(addButton);
buttonPanel.add(multiplyButton);
JPanel resultPanel = new JPanel(new FlowLayout());
resultPanel.add(new JLabel("Result:"));
resultPanel.add(resultField);
setLayout(new BorderLayout());
add(matrixPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
add(resultPanel, BorderLayout.NORTH);
}
private int[][] getMatrixValues(int matrixIndex) {
int[][] matrix = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
matrix[i][j] = Integer.parseInt(matrixFields[i][j].getText());
}
}
return matrix;
}
private int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
int[][] result = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
return result;
}
private int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {
int[][] result = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}
private void displayResult(int[][] result) {
resultField.setText("");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
resultField.setText(resultField.getText() + result[i][j] + " ");
}
resultField.setText(resultField.getText() + "\n");
}
}
public static void main(String[] args) {
MatrixCalculator calculator = new MatrixCalculator();
calculator.setVisible(true);
}
}
```
阅读全文