整数计算:
用swing组件来实现整数计算,需要对整数计算的值进行校验。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class IntegerCalculator extends JFrame implements ActionListener {
private JCheckBox[] checkBoxes;
private JTextField[] textFields;
private JButton selectAllButton;
private JButton multiSelectButton;
private JButton sumButton;
private JTextField sumDisplayField;
public IntegerCalculator(int numIntegers) {
setTitle("选择整数计算");
setSize(600, 400);
this.setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(numIntegers + 3, 2));
checkBoxes = new JCheckBox[numIntegers];
textFields = new JTextField[numIntegers];
for (int i = 0; i < numIntegers; i++) {
checkBoxes[i] = new JCheckBox();
textFields[i] = new JTextField();
panel.add(checkBoxes[i]);
panel.add(textFields[i]);
}
this.selectAllButton = new JButton("全选");
panel.add(selectAllButton);
this.selectAllButton.addActionListener(this);
this.multiSelectButton = new JButton("多项选择");
panel.add(multiSelectButton);
this.multiSelectButton.addActionListener(this);
this.sumButton = new JButton("求和");
panel.add(sumButton);
this.sumButton.addActionListener(this);
sumDisplayField = new JTextField();
sumDisplayField.setEditable(false);
panel.add(sumDisplayField);
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == this.selectAllButton) {
for (JCheckBox checkBox : checkBoxes) {
checkBox.setSelected(true);
}
} else if (event.getSource() == this.multiSelectButton) {
int[] selectedIntegers = new int[checkBoxes.length];
int count = 0;
for (int i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].isSelected()) {
String text = textFields[i].getText();
if (!text.isEmpty()) {
try {
selectedIntegers[count++] = Integer.parseInt(text);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, text + "不能转换成数字,忽略");
return;
}
}
}
}
int[] validSelectedIntegers = new int[count];
for (int i = 0; i < count; i++) {
validSelectedIntegers[i] = selectedIntegers[i];
}
if (count > 0) {
String displayText = "[";
for (int i = 0; i < count; i++) {
displayText += validSelectedIntegers[i];
if (i < count - 1) {
displayText += ", ";
}
}
displayText += "]";
JOptionPane.showMessageDialog(null, "选择整数:" + displayText);
}
} else if (event.getSource() == this.sumButton) {
int sum = sum(textFields);
if (sum != 0) {
sumDisplayField.setText(String.valueOf(sum));
} else {
sumDisplayField.setText("0");
}
}
}
public int sum(JTextField[] text) {
int sum = 0;
for (int i = 0; i < text.length; i++) {
String textArea = text[i].getText();
if (!textArea.isEmpty() && checkBoxes[i].isSelected()) {
try {
int x = Integer.parseInt(textArea);
sum += x;
} catch (Exception e) {
String str = textArea + "不能被转换成数字,忽略";
JOptionPane.showMessageDialog(null, str);
return 0;
}
}
}
return sum;
}
public static void main(String[] args) {
IntegerCalculator calculator = new IntegerCalculator(6);
}
}